Shiro Subject设计概念
Subject
其拥有的行为:
Subject代表着用户,用户所拥有的行为包括:登录、退出、校验权限、获得Session等,符合面向对象,门自己把自己关上了。
Subject.Builder
其拥有的行为:
接口里定义了Subject具备的行为,接口里边写Builder类,Subject通过Subject.Builder创建:(new Subject.Builder()).buildSubject();
其具备SubjectContext(拥有Subject的所有属性信息)、SecurityManager(主要职责就是创建Subject)
该类负责SubjectContext的组装,为其设置host、session、principals等
// 默认构造器中注入SecurityManager public Builder() { this(SecurityUtils.getSecurityManager()); } // 创建SubjectContext public Builder(SecurityManager securityManager) { if (securityManager == null) { throw new NullPointerException("SecurityManager method argument cannot be null."); } this.securityManager = securityManager; this.subjectContext = newSubjectContextInstance(); if (this.subjectContext == null) { throw new IllegalStateException("Subject instance returned from 'newSubjectContextInstance' " + "cannot be null."); } this.subjectContext.setSecurityManager(securityManager); } protected SubjectContext newSubjectContextInstance() { return new DefaultSubjectContext(); }
组装SubjectContext
// 为SubjectContext设置值然后返回Builder实例 public Builder sessionId(Serializable sessionId) { if (sessionId != null) { this.subjectContext.setSessionId(sessionId); } return this; } public Builder host(String host) { if (StringUtils.hasText(host)) { this.subjectContext.setHost(host); } return this; } public Builder session(Session session) { if (session != null) { this.subjectContext.setSession(session); } return this; } // 使用 Builder builder = new Subject.Builder(); builder.sessionId("helloBuilder") .host("127.0.0.1");
创建Subject,使用SecurityManager根据SubjectContext创建Subject
public Subject buildSubject() { return this.securityManager.createSubject(this.subjectContext); }
创建Subject的过程设计概念
Subject$Builder.buildSubject(SubjectContext) ==> SecurityManager.createSubject(SubjectContext) ==> SubjectFactory.createSubject(SubjectContext)