Shiro的认证原理(Subject#login的背后故事)
登录操作一般都是我们触发的:
Subject subject = SecurityUtils.getSubject();
AuthenticationToken authenticationToken = new ...
subject.login(authenticationToken);
Subject的登录将委托给SecurityManager,SecurityManager的login方法实际上是产生了一个新的Subject,然后将相关属性赋予当前调用者Subject:
public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentitiesInternal();
Subject subject = securityManager.login(this, token);
PrincipalCollection principals;
String host = null;
if (subject instanceof DelegatingSubject) {
DelegatingSubject delegating = (DelegatingSubject) subject;
//we have to do this in case there are assumed identities - we don't want to lose the 'real' principals:
principals = delegating.principals;
host = delegating.host;
} else {
principals = subject.getPrincipals();
}
if (principals == null || principals.isEmpty()) {
String msg = "Principals returned from securityManager.login( token ) returned a null or " +
"empty value. This value must be non null and populated with one or more elements.";
throw new IllegalStateException(msg);
}
this.principals = principals;
this.authenticated = true;
if (token instanceof HostAuthenticationToken) {
host = ((HostAuthenticationToken) token).getHost();
}
if (host != null) {
this.host = host;
}
Session session = subject.getSession(false);
if (session != null) {
this.session = decorate(session);
} else {
this.session = null;
}
}
DefaultSecurityManager实现了login方法:
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = authenticate(token);
} catch (AuthenticationException ae) {
try {
onFailedLogin(token, ae, subject);
} catch (Exception e) {
if (log.isInfoEnabled()) {
log.info("onFailedLogin method threw an " +
"exception. Logging and propagating original AuthenticationException.", e);
}
}
throw ae; //propagate
}
Subject loggedIn = createSubject(token, info, subject);
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}

父类AuthenticatingSecurityManager实现authenticate方法:
public abstract class AuthenticatingSecurityManager extends RealmSecurityManager {
private Authenticator authenticator;
public AuthenticatingSecurityManager() {
super();
this.authenticator = new ModularRealmAuthenticator();
}
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
return this.authenticator.authenticate(token);
}
//......
}
利用一个ModularRealmAuthenticator类型的authenticator来实现:
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
if (realms.size() == 1) {
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
return doMultiRealmAuthentication(realms, authenticationToken);
}
}
然后根据realms集合是单个还是多个分别处理,最终无非是这样:
AuthenticationInfo info = realm.getAuthenticationInfo(token);
父类AuthenticatingRealm的getAuthenticationInfo方法实现了info的获取和身份的校验,仅仅调用自己实现的realm的doGetAuthenticationInfo方法,初步验证后构造一个SimpleAuthenticationInfo:
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(principals, this.getName());
return new SimpleAuthenticationInfo(principalCollection, authenticationInfo.getCredentials());
AuthenticatingRealm的getAuthenticationInfo方法逻辑如下:
首先去缓存找info:
AuthenticationInfo info = getCachedAuthenticationInfo(token);
缓存没有则调用子类实现的方法:
info = doGetAuthenticationInfo(token);
info不为null的时候就要验证了(这里还可以加密验证):
assertCredentialsMatch(token, info);
两次创建Subject
进入AbstractShiroFilter的时候,会默认创建一个Subject,这个是在Subject接口中的内部类实现的,但是同样也是调用了DefaultSecurityManager中的createSubject方法:
public Subject createSubject(SubjectContext subjectContext) {
//create a copy so we don't modify the argument's backing map:
SubjectContext context = copy(subjectContext);
//ensure that the context has a SecurityManager instance, and if not, add one:
context = ensureSecurityManager(context);
//Resolve an associated Session (usually based on a referenced session ID), and place it in the context before
//sending to the SubjectFactory. The SubjectFactory should not need to know how to acquire sessions as the
//process is often environment specific - better to shield the SF from these details:
context = resolveSession(context);
//Similarly, the SubjectFactory should not require any concept of RememberMe - translate that here first
//if possible before handing off to the SubjectFactory:
context = resolvePrincipals(context);
Subject subject = doCreateSubject(context);
//save this subject for future reference if necessary:
//(this is needed here in case rememberMe principals were resolved and they need to be stored in the
//session, so we don't constantly rehydrate the rememberMe PrincipalCollection on every operation).
//Added in 1.2:
save(subject);
return subject;
}
初次进入shiroFilter,会创建一个Subject,这个Subject没有验证通过,保留了三个属性:request,response,securityManager。
当我们调用subject.login的时候,我们在DefaultSecurityManager中为subjectContext设置了相关属性:
protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info, Subject existing) {
SubjectContext context = createSubjectContext();
context.setAuthenticated(true);
context.setAuthenticationToken(token);
context.setAuthenticationInfo(info);
if (existing != null) {
context.setSubject(existing);
}
// 这个方法的具体实现在上面
return createSubject(context);
}
一个save方法为我们构造了session:
save(subject);
这个session是根据我们的principals(放在登录成功返回的那个AuthenticationInfo中)构造的。
下一次进入的时候,依然是:
final Subject subject = createSubject(request, response);
但是下面的方法为我们找回了session,通过request.getSession(false)就可以取到。
context = resolveSession(context);
有了session后其他的东西都可以恢复,这样就可以识别并维持一个subject的状态,即使每次都重新创建了Subject对象。
具体是在DefaultWebSubjectFactory这个方法里恢复的,并且通过构造器赋值给下一个新的subject了:
public Subject createSubject(SubjectContext context) {
if (!(context instanceof WebSubjectContext)) {
return super.createSubject(context);
}
WebSubjectContext wsc = (WebSubjectContext) context;
SecurityManager securityManager = wsc.resolveSecurityManager();
Session session = wsc.resolveSession();
boolean sessionEnabled = wsc.isSessionCreationEnabled();
PrincipalCollection principals = wsc.resolvePrincipals();
boolean authenticated = wsc.resolveAuthenticated();
String host = wsc.resolveHost();
ServletRequest request = wsc.resolveServletRequest();
ServletResponse response = wsc.resolveServletResponse();
return new WebDelegatingSubject(principals, authenticated, host, session, sessionEnabled,
request, response, securityManager);
}
举两个例子:
PrincipalCollection principals = wsc.resolvePrincipals();
-> principals = (PrincipalCollection) session.getAttribute(PRINCIPALS_SESSION_KEY);
boolean authenticated = wsc.resolveAuthenticated();
-> Session session = resolveSession();
if (session != null) {
Boolean sessionAuthc = (Boolean) session.getAttribute(AUTHENTICATED_SESSION_KEY);
authc = sessionAuthc != null && sessionAuthc;
}
通过上面两个方法就恢复了Subject的两个属性,其实都是存放在session中。
其实只要你使用了Shiro,不管你是否登录,核心过滤器都会为我们构造Subject实例,当我们主动调用subject.login方法时,会间接调用我们自己实现的realm的doGetAuthenticationInfo,根据我们在数据库中获取的信息(存放在info中)和调用login方法时传递的AuthenticationToken中的信息对比。
当info为null或者抛出了AuthenticationException异常,都视为登录失败。
Shiro的认证原理(Subject#login的背后故事)的更多相关文章
- Shiro授权认证原理和流程
先来张图: 这是一张shiro的功能图: Authentication: 身份认证/登录,验证用户是否拥有相应的身份 Authorization: 授权/权限验证,验证某个已认证的用户是否拥有某个权限 ...
- shiro入门与认证原理
一.shiro介绍 1.什么是shiro shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证.用户授权. 2.shiro的优点 (1)shiro将安全认证相关的功能抽取出 ...
- Shiro第二篇【介绍Shiro、认证流程、自定义realm、自定义realm支持md5】
什么是Shiro shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证.用户授权. spring中有spring security (原名Acegi),是一个权限框架,它和sp ...
- 在web项目中使用shiro(认证、授权)
一.在web项目中实现认证 第一步,在web项目中导入shiro依赖的包 第二步,在web.xml中声明shiro拦截权限的过滤器 <filter> <filter-name> ...
- shiro学习笔记-Subject#login(token)实现过程
本博文所有的代码均为shiro官网(http://shiro.apache.org/)中shiro 1.3.2版本中的源码. 追踪Subject的login(AuthenticationToken t ...
- Shiro身份认证授权原理
shiro在应用程序中的使用是用Subject为入口的, 最终subject委托给真正的管理者ShiroSecurityMannager Realm是Shiro获得身份认证信息和来源信息的地方(所以这 ...
- shiro学习笔记-Subject#login(token)源码实现过程
追踪Subject的login(AuthenticationToken token)方法,其调用的为DelegatingSubject类的login方法,DelegatingSubject实现了Sub ...
- Shiro中的subject.login()
当调用ShiroHandler中的subject.login()的时候,会自动调用Realm中的doGetAuthenticationInfo方法.
- Shiro的认证和权限控制
权限控制的方式 从类别上分,有两大类: - 认证:你是谁?–识别用户身份. - 授权:你能做什么?–限制用户使用的功能. 权限的控制级别 从控制级别(模型)上分: - URL级别-粗粒度 - 方法级别 ...
随机推荐
- JAVA嵌套类:静态嵌套类和非静态嵌套类
1.内部类定义 内部类在维基百科的定义为: 面向对象编程中,内部类(又叫做嵌套类)是在另一个类或者接口中进行声明的类.内部类不同于子类(subclass).(译者注:wiki的注解有误,内部类和嵌套 ...
- 编译redis时 提示make cc Command not found
在linux系统上对redis源码进行编译时提示提示“make cc Command not found,make: *** [adlist.o] Error 127”. 这是由于系统没有安装gcc环 ...
- python实现备份gitlab版本库并更改文件名
脚本的功能是实现备份gitlab版本库,并修改备份后的文件名,成功后发送邮件至相关负责人,脚本如下: #!/usr/bin/env python # -*- coding:utf-8 -*- impo ...
- 12.24笔记(关于//UIDynamic演练//多对象的附加行为//UIDynamic简单演练//UIDynamic//(CoreText框架)NSAttributedString)
12.24笔记1.UIDynamic注意点:演示代码:上面中设置视图旋转的时候,需要注意设置M_PI_4时,视图两边保持平衡状态,达不到仿真效果.需要偏移下角度.2.吸附行为3.推动行为初 ...
- Unity下的ECS框架 Entitas简介
最近随着守望先锋制作组在gdc上发布的一个关于ecs的talk,ecs这个架构算是得到了一定的曝光度. 在这之前,github上就一直有一个C#的ecs框架名为Entitas,截止现在已经有1300+ ...
- document的属性与方法小结
document节点是文档的根节点,每张网页都有自己的document节点.属性:1:document.doctype----它是一个对象,包含了当前文档类型 (Document Type Decla ...
- list互转datatable 支持Nullable转换
/// <summary> /// list转datatable /// </summary> /// <param name="list">& ...
- 【遍历集合】Java遍历List,Map,Vector,Set的几种方法
关于list,map,set的区别参考http://www.cnblogs.com/qlqwjy/p/7406573.html 1.遍历list @Test public void testList( ...
- OSI与TCP/IP各层的结构与功能,都有哪些协议
前言: 今天更新一下计算机网络的一些非常重要的知识,可能很多人都不知学计算机网络有什么用,我想说的是它真的比较重要,像咱们学校只要是学计算机这个专业都要学习这门课程.另外大家要是去一些像BAT,阿里, ...
- linux percpu机制解析【转】
转自:http://blog.csdn.net/wh8_2011/article/details/53138377 一.概述 每cpu变量是最简单也是最重要的同步技术.每cpu变量主要是数据结构数组, ...