我们先从一段最基础的代码开始
@Test
public void testHelloWorld(){
// 获取SecurityManager工厂,此处使用ini配置文件初始化SecurityManager
IniSecurityManagerFactory managerFactory = new IniSecurityManagerFactory
("classpath:shiro.ini");
// 得到SecurityManager实例 并绑定给SecurityUtils
SecurityManager manager = managerFactory.getInstance();
SecurityUtils.setSecurityManager(manager);
// 得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang","123".toCharArray(),true);
try {
subject.login(token);
} catch (AuthenticationException e) {
// 身份验证失败
e.printStackTrace();
}
// 断言 登录是否成功
Assert.assertEquals(true,subject.isAuthenticated());
Session session = subject.getSession();
System.out.println(session.getId());
System.out.println(subject.getPrincipal());// zhang
// 设置属性
session.setAttribute("name",subject.getPrincipal());
// 获取属性
session.getAttribute("name");
Collection<Object> attributeKeys = session.getAttributeKeys();
Iterator<Object> iterator = attributeKeys.iterator();
while (iterator.hasNext()){
System.out.println("所有的属性KEY :"+iterator.next());
}
// 退出
subject.logout();
}
这里我们可以不用关心SecurityManager到底是怎么创建的,反正就是加载配置文件。
跟踪代码
SecurityUtils.setSecurityManager(manager);
public abstract class SecurityUtils {
private static SecurityManager securityManager;
public SecurityUtils() {
}
public static void setSecurityManager(SecurityManager securityManager) {
SecurityUtils.securityManager = securityManager;
}
SecurityUtils.getSubject();
public abstract class SecurityUtils {
public static Subject getSubject() {
// 第一步:
// 注意这里的ThreadContext是个什么鬼
Subject subject = ThreadContext.getSubject();
if(subject == null) {
// 第二步:
subject = (new Builder()).buildSubject();
ThreadContext.bind(subject);
}
return subject;
}
第一步:
// 注意这里的ThreadContext是个什么鬼
Subject subject = ThreadContext.getSubject();
public abstract class ThreadContext {
private static final Logger log = LoggerFactory.getLogger(ThreadContext.class);
public static final String SECURITY_MANAGER_KEY =
ThreadContext.class.getName() + "_SECURITY_MANAGER_KEY";
public static final String SUBJECT_KEY =
ThreadContext.class.getName() + "_SUBJECT_KEY";
// 注意这个变量,ThreadLocal是当前线程用来保存信息的,每个线程都有一个ThreadLocal,
//多线程环境下只能各自取各自ThreadLocal中保存的信息
private static final ThreadLocal<Map<Object, Object>> resources =
new ThreadContext.InheritableThreadLocalMap();
public static Subject getSubject() {
return (Subject)get(SUBJECT_KEY);
}
private static Object getValue(Object key) {
return ((Map)resources.get()).get(key);
}
public static Object get(Object key) {
if(log.isTraceEnabled()) {
String value = "get() - in thread [" + Thread.currentThread().getName() + "]";
log.trace(value);
}
Object value1 = getValue(key);
if(value1 != null && log.isTraceEnabled()) {
String msg = "Retrieved value of type [" + value1.getClass().getName() + "] for key [" + key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]";
log.trace(msg);
}
return value1;
}
可以看到,ThreadContext.getSubject();最终调用的是getValue()方法,然后从ThreadLocal中取出Subject。那ThreadLocal中的Subject怎么来的呢?看第二步。
第二步:
(new Builder()).buildSubject()
public interface Subject {
xxxx省略其他代码,重点是Subject里面有一个静态的Builder类
public static class Builder {
private final SubjectContext subjectContext;
private final SecurityManager securityManager;
public Builder() {
this(SecurityUtils.getSecurityManager());
}
public Subject buildSubject() {
return this.securityManager.createSubject(this.subjectContext);
}
来看看buildSubject干了啥:
public interface SecurityManager extends Authenticator, Authorizer, SessionManager {
Subject login(Subject var1, AuthenticationToken var2) throws AuthenticationException;
void logout(Subject var1);
Subject createSubject(SubjectContext var1);
}
它是一个接口,我们找一个实现类,就找DefaultSecurityManager看看吧
public class DefaultSecurityManager extends SessionsSecurityManager {
private static final Logger log = LoggerFactory.getLogger(DefaultSecurityManager.class);
protected RememberMeManager rememberMeManager;
protected SubjectDAO subjectDAO;
protected SubjectFactory subjectFactory;
protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info, Subject existing) {
// 这里的token是我们之前写的UsernamePasswordToken
SubjectContext context = this.createSubjectContext();
context.setAuthenticated(true);
context.setAuthenticationToken(token);
context.setAuthenticationInfo(info);
if(existing != null) {
context.setSubject(existing);
}
return this.createSubject(context);
}
这里都是在组装必要的参数,我们直接看最后一句:
public Subject createSubject(SubjectContext subjectContext) {
SubjectContext context = this.copy(subjectContext);
context = this.ensureSecurityManager(context);
context = this.resolveSession(context);
context = this.resolvePrincipals(context);
Subject subject = this.doCreateSubject(context);
this.save(subject);
return subject;
}
注意其中的两个方法:doCreateSubject(context)和save(subject)
先来看创建的:
protected Subject doCreateSubject(SubjectContext context) {
return this.getSubjectFactory().createSubject(context);
}
// 使用工厂类创建Subject
public class DefaultSubjectFactory implements SubjectFactory {
public DefaultSubjectFactory() {
}
public Subject createSubject(SubjectContext context) {
SecurityManager securityManager = context.resolveSecurityManager();
Session session = context.resolveSession();
boolean sessionCreationEnabled = context.isSessionCreationEnabled();
PrincipalCollection principals = context.resolvePrincipals();
boolean authenticated = context.resolveAuthenticated();
String host = context.resolveHost();
return new DelegatingSubject(principals, authenticated, host, session, sessionCreationEnabled, securityManager);
}
// 注意这里有个SecurityManager,这个就是SecurityUtils中的那个静态变量
public class DelegatingSubject implements Subject {
public DelegatingSubject(PrincipalCollection principals, boolean authenticated, String host, Session session, boolean sessionCreationEnabled, SecurityManager securityManager) {
if(securityManager == null) {
throw new IllegalArgumentException("SecurityManager argument cannot be null.");
} else {
this.securityManager = securityManager;
this.principals = principals;
this.authenticated = authenticated;
this.host = host;
if(session != null) {
this.session = this.decorate(session);
}
this.sessionCreationEnabled = sessionCreationEnabled;
}
}
再看save(subject)方法,它是怎么保存的,其实应该也能想到了,肯定是用ThreadLocal来保存的,我们来看看:先回到DefaultSecurityManager
protected void save(Subject subject) {
this.subjectDAO.save(subject);
}
public interface SubjectDAO {
Subject save(Subject var1);
void delete(Subject var1);
}
找个SubjectDAO的实现类:
public class DefaultSubjectDAO implements SubjectDAO {
public Subject save(Subject subject) {
if(this.isSessionStorageEnabled(subject)) {
this.saveToSession(subject);
} else {
log.trace("Session storage of subject state for Subject [{}] has been disabled: identity and authentication state are expected to be initialized on every request or invocation.", subject);
}
return subject;
}
public Subject save(Subject subject) {
if(this.isSessionStorageEnabled(subject)) {
this.saveToSession(subject);
} else {
log.trace("Session storage of subject state for Subject [{}] has been disabled: identity and authentication state are expected to be initialized on every request or invocation.", subject);
}
return subject;
}
protected void saveToSession(Subject subject) {
this.mergePrincipals(subject);// 保存principals信息
this.mergeAuthenticationState(subject);// 保存验证的状态
}
咦,咋跟我想象的不一样呢?
原因是我忽略了SecurityUtils.getSubject();中还有重要的一步,ThreadContext.bind(subject);这才是我之前设想那样。进入这个方法来看看:
public abstract class ThreadContext {
private static final Logger log = LoggerFactory.getLogger(ThreadContext.class);
public static final String SECURITY_MANAGER_KEY = ThreadContext.class.getName() + "_SECURITY_MANAGER_KEY";
public static final String SUBJECT_KEY = ThreadContext.class.getName() + "_SUBJECT_KEY";
private static final ThreadLocal<Map<Object, Object>> resources = new ThreadContext.InheritableThreadLocalMap();
public static void bind(Subject subject) {
if(subject != null) {
put(SUBJECT_KEY, subject);
}
}
public static void put(Object key, Object value) {
if(key == null) {
throw new IllegalArgumentException("key cannot be null");
} else if(value == null) {
remove(key);
} else {
((Map)resources.get()).put(key, value);
if(log.isTraceEnabled()) {
String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" + key + "] to thread " + "[" + Thread.currentThread().getName() + "]";
log.trace(msg);
}
}
}
看到put(Object key, Object value)方法中的((Map)resources.get()).put(key, value);你还想不到这是个什么操作吗。
subject.login(token);
public void login(AuthenticationToken token) throws AuthenticationException {
this.clearRunAsIdentitiesInternal();
Subject subject = this.securityManager.login(this, token);
}
public class DefaultSecurityManager extends SessionsSecurityManager {
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = this.authenticate(token);
} catch (AuthenticationException var7) {
AuthenticationException loggedIn = var7;
try {
this.onFailedLogin(token, loggedIn, subject);
} catch (Exception var6) {
if(log.isInfoEnabled()) {
log.info("onFailedLogin method threw an exception. Logging and propagating original AuthenticationException.", var6);
}
}
throw var7;
}
Subject loggedIn1 = this.createSubject(token, info, subject);
this.onSuccessfulLogin(token, info, loggedIn1);
return loggedIn1;
}
登录就是将Subject交给SecurityManager去一步步的验证,然后根据配置保存需要保存的信息。
总结:1、理解Subject,SecurityManager之间的关系
一个SecurityManager可以管理多个Subject,且能在多线程下良好使用
2、ThreadLocal的使用
网友评论