1. 准备配置
1.1 配置 SecurityManager
在 web.xml 中配置
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"/>
<!-- 配置多个 Realm -->
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
</bean>
1.2 配置缓存 CacheManager
配置缓存后, 认证一次后再次访问需授权页面时, 读取缓存即可
配置 CacheManager 需要加入 ehcache 的 jar 包及配置文件
在 web.xml 中配置
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
1.3 配置认证相关信息
在 web.xml 中配置
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<!-- 配置认证策略 -->
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/>
</property>
</bean>
1.4 配置 Realm
直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean
在 web.xml 中配置
<bean id="jdbcRealm" class="com.tc.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密算法名字 -->
<property name="hashAlgorithmName" value="MD5"/>
<!-- 加密次数 -->
<property name="hashIterations" value="1024"/>
</bean>
</property>
</bean>
1.5 配置 LifecycleBeanPostProcessor
可以自动的来调用配置在 Spring IOC 容器中 Shiro Bean 的生命周期方法
在 web.xml 中配置
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
1.6 启用 IOC 容器中的使用 shiro 的注解
必须在配置了 LifecycleBeanPostProcessor 之后才可以使用
在 web.xml 中配置
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
1.7 配置 shiroFilter
在 web.xml 中添加
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
DelegatingFilterProxy 实际上是 Filter 的一个代理对象. 默认情况下, Spring 会到 IOC 容器中查找和
< filter-name > 对应的 filter bean.
也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id, 在< filter > 中添加
<init-param>
<param-name>targetBeanName</param-name>
<param-value>filterName</param-value>
</init-param>
在 spring 的配置文件 applicationContext.xml 中配置
id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 < filter-name > (或 targetBeanName) 一致, 若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 < filter-name > 名字对应的 Filter Bean, 找不到自然会抛异常
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/list.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<property name="filterChainDefinitions">
<value>
<!-- 配置 URL 权限 -->
...
</value>
</property>
</bean>
2. 认证
2.1 实现认证 Realm
继承 org.apache.shiro.realm.AuthenticatingRealm, 重写 doGetAuthenticationInfo 方法, 此类还有其他子类, 可自行选择, 盐值加密部分代码看不懂可以继续往下看
public class ShiroRealm extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 1. 把 AuthenticationToken 转换为 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
// 2. 从 UsernamePasswordToken 中来获取 username
String username = upToken.getUsername();
// 3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息");
// 4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
if ("unknown".equals(username)) {
throw new UnknownAccountException("用户不存在");
}
// 5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常
if ("lock".equals(username)) {
throw new LockedAccountException("用户被锁定");
}
// 6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回.
// 通常使用的实现类为: SimpleAuthenticationInfo
// 以下信息是从数据库中获取的
// 6.1 principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象
Object principal = username;
// 6.2 credentials: 密码
Object credentials = null;
if ("admin".equals(username)) {
credentials = "038bdaf98f2037b31f1e75b5b4c9b26e"; // MD5 盐值加密后的密码
} else if ("user".equals(username)) {
credentials = "098d2c478e9c11555ce2823231e02ec1"; // MD5 盐值加密后的密码
}
// 6.3 realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
String realmName = getName();
// 6.4 盐值
ByteSource credentialSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialSalt, realmName);
return info;
}
}
2.2 认证策略 AuthenticationStrategy
AuthenticationStrategy 接口的默认实现:
- FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第
一个 Realm 身份验证成功的认证信息,其他的忽略; - AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和
FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信
息; - AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有
Realm身份验证成功的认证信息,如果有一个失败就失败了。
ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy 策略
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/>
</property>
</bean>
2.3 密码的普通加密与盐值加密
无论是普通加密还是盐值加密, 都要在 web.xml 文件中配置的 Realm 的 Bean 里添加 credentialsMatcher 认证匹配器:
<bean id="shirotRealm" class="com.tc.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密算法名字 -->
<property name="hashAlgorithmName" value="MD5"/>
<!-- 加密次数 -->
<property name="hashIterations" value="1024"/>
</bean>
</property>
</bean>
指定传入的 password 以哪种加密方式进行匹配
例如: 输入密码为 123456, 比较时, 会先将 123456 通过 MD5 加密 1024 次, 再与第 3 点的图中的 credentials 参数比较 (注意, credentials 参数应该从数据库中获取, 图中为了方便, 才直接写出来)
加密方式有三种:
- MD5
- SHA1
- SHA256
- 普通加密
通过加密算法直接进行加密
缺点: 当用户密码相同时, 得到的加密字符串也相同String hashAlgorithmName = "MD5"; // 加密方式 Object credentials = "123456"; // 用户传入的 password Object salt = null; int hashIterations = 1024; // 加密次数 Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations); System.out.println(result);
- 盐值加密
通过加密算法与传入的盐值进行加密, 密码相同, 盐值不同, 则得到的加密字符串也不同String hashAlgorithmName = "MD5"; // 加密方式 Object credentials = "123456"; // 用户传入的 password Object salt = ByteSource.Util.bytes("user"); // 盐值, "user"可以是不重复任意值 int hashIterations = 1024; // 加密次数 Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations); // 加密后的密码 System.out.println(result); // 098d2c478e9c11555ce2823231e02ec1
3. 授权
3.1 URL 权限配置
配置哪些页面需要受保护, 以及访问这些页面需要的权限
- anon: 可以被匿名访问
- authc: 必须认证(即登录)后才可访问
- logout: 登出
- roles: 角色过滤器
遵循第一匹配优先原则: 由上至下扫描, 使用第一个匹配到的权限, 即使后面还有匹配项
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout
/user.jsp = roles[user]
/admin.jsp = roles[admin]
# 匹配其他所有 URL
/** = authc
</value>
</property>
其他权限:
3.2 动态配置 URL 权限
可以不用上面的那种方式, 而是动态配置 URL 权限, 在 ShiroFilter 的 Bean 中添加
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"/>
新建一个 filterChainDefinitionMap 实例工厂, 在其中可以动态添加权限
public class FilterChainDefinitionMapBuilder {
public LinkedHashMap<String, String> buildFilterChainDefinitionMap() {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("/login.jsp", "anon");
map.put("/**", "authc");
return map;
}
}
然后通过工厂配置 filterChainDefinitionMap
<bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapBuilder"
factory-method="buildFilterChainDefinitionMap"/>
<bean id="filterChainDefinitionMapBuilder" class="com.tc.shiro.factory.FilterChainDefinitionMapBuilder"/>
3.3 认证与授权
授权需要继承 AuthorizingRealm 类, 并实现其 doGetAuthorizationInfo 方法
AuthorizingRealm 类继承自 AuthenticatingRealm, 但没有实现 AuthenticatingRealm 中的
doGetAuthenticationInfo, 所以认证和授权只需继承 AuthorizingRealm 就可以了, 同时实现它的两个抽象方法
public class TestRealm extends AuthorizingRealm {
/**
* 用于授权的方法
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
/**
* 用于认证的方法
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 1. 从 PrincipalCollection 中来获取登录用户的信息
// 得到的是 doGetAuthenticationInfo 方法中传入 SimpleAuthenticationInfo 的 principal(即 username)
Object principal = principals.getPrimaryPrincipal();
// 2. 利用登录的用户的信息来获取当前用户的角色或权限(可能需要查询数据库)
// 用 user 登录, 只有 user 角色, 用 admin 登录, 有 user 和 admin 两个角色
Set<String> roles = new HashSet<>();
roles.add("user");
if ("admin".equals(principal)) {
roles.add("admin");
}
// 3. 创建 SimpleAuthorizationInfo, 并设置其 roles 属性
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
// 4. 返回 SimpleAuthorizationInfo 对象
return info;
}
}
4. Shiro 标签
-
pincipal 标签: 显示用户身份信息, 默认调用 Subject.getPrincipal() 获取, 即 Primary Principal
<shiro:principal property="username"/>
-
hasRole 标签: 如果当前 Subject 有角色, 将显示 body 体内容
<shiro:hasRole name="admin"> 用户<shiro:principal/>拥有角色 admin </shiro:hasRole>
-
guest 标签: 用户没有身份验证时显示相应信息,即游客访问
<shiro:guest> 欢迎游客访问, <a href="login.jsp">登录</a> </shiro:guest>
-
user 标签:用户已经经过认证 / 记住我登录后, 显示相应的信息
<shiro:user> 欢迎<shiro:principal/>登录, <a href="login.jsp">退出</a> </shiro:user>
-
authenticated 标签: 用户已经身份验证通过, 即 Subject.login 登录成功, 不是记住我登录的
<shiro:authenticated> 用户<shiro:principal/>已通过身份验证 </shiro:authenticated>
-
notAuthenticated 标签: 用户未进行身份验证, 即没有调用 Subject.login 进行登录, 包括记住我自动登录的也属于未进行身份验证
<shiro:noAuthenticated> 未身份验证(包括记住我) </shiro:noAuthenticated>
-
hasAnyRoles 标签: 如果当前 Subject 有任意一个角色(或关系)将显示 body 体内容
<shiro:hasAnyRoles name="admin, user"> 用户<shiro:principal/>拥有角色 admin 或 user </shiro:hasAnyRoles>
-
lacksRole 标签: 如果当前 Subject 没有指定角色, 将显示 body 体内容
<shiro:lacksRole name="admin"> 用户<shiro:principal/>没有角色 admin </shiro:lacksRole>
-
hasPermission 标签: 如果当前 Subject 有指定权限, 将显示 body 体内容
<shiro:hasPermission name="user:create"> 用户<shiro:principal/>拥有权限 user:create </shiro:hasPermission>
-
lacksPermission 标签: 如果当前 Subject 没有指定权限, 将显示body体内容
<shiro:lacksPermission name="org:create"> 用户<shiro:principal/>没有权限 org:create </shiro:lacksPermission>
5. 权限注解
- @RequiresAuthentication: 表示当前 Subject 已经通过 login 进行了身份验证, 即 Subject.isAuthenticated() 返回 true
- @RequiresUser: 表示当前 Subject 已经身份验证或者通过记住我登录的
- @RequiresGuest: 表示当前 Subject 没有身份验证或通过记住我登录过, 即是游客身份
- @RequiresRoles(value = {“admin”, “user”}, logical = Logical.AND): 表示当前 Subject 需要角色 admin 和 user
- @RequiresPermissions (value = {“user:a”, “user:b”}, logical = Logical.OR): 表示当前 Subject 需要权限 user:a 或 user:b
这些注解可以加到 Service 层, 也可以加到 Controller 层, 但是当 Service 层的方法加了 @Transaction 注解时, 就只能加到 Controller 层了, 否则在注入 Service 时, 会抛出类型转换异常
6. 会话 Session
类似于 JavaEE 的 Session, 代表一次会话, 不过 Shiro 的 Session 在 JavaSE 下也可以使用
6.1 Session API
- Subject.getSession(): 获取会话, 其等价于 Subject.getSession(false)
- Subject.getSession(true): 即如果当前没有创建 Session 对象会去创建
一个 - Subject.getSession(false): 如果当前没有创建 Session 则返回 null
- session.getId(): 获取当前会话的唯一标识
- session.getHost(): 获取当前 Subject 的主机地址
- session.getTimeout() & session.setTimeout(毫秒): 获取 / 设置当前 Session 的过期时间
- session.getStartTimestamp() & session.getLastAccessTime(): 获取会话的启动时间及最后访问时间; 如果是 JavaSE 应用需要自己定期调用 session.touch() 去更新最后访问时间; 如果是 Web 应用,每次进入 ShiroFilter 都会自动调用 session.touch() 来更新最后访问时间
- session.touch() & session.stop():更新会话最后访问时间及销毁会话; 当调用 Subject.logout() 时会自动调用 stop 方法来销毁会话, 如果在 Web 中, 调用 HttpSession.invalidate() 也会自动调用 Shiro 的 Session.stop 方法进行销毁 Shiro 的会话
- session.setAttribute(key, val) & session.getAttribute(key) & session.removeAttribute(key): 设置 / 获取 / 删除会话属性, 在整个会话范围内都可以对这些属性进行操作
6.2 Service 中的 Session
在 Controller 中可以使用 HttpSession.setAttribute, 在 Service 中可以通过 SecurityUtils.getSubject().getSession() 的方式得到 Shiro 的 Session, 通过 Shiro 的 Session 可以得到 HttpSession 中存放的值
@RequestMapping("/testShiroSession")
public String testShiroSession(HttpSession session) {
session.setAttribute("key", "value12345");
shiroService.testMethod();
return "redirect:/list.jsp";
}
public class ShiroService {
public void testMethod() {
System.out.println("TestMethod, time: " + new Date());
Session session = SecurityUtils.getSubject().getSession();
Object val = session.getAttribute("key");
System.out.println(val); // value12345
}
}
6.3 SessionDao
SessionDao 用来对 Session 对象进行存储与取出操作
在 ehcache.xml 中添加:
<cache name="shiro-activeSessionCache"
maxElementsInMemory="10000"
overflowToDisk="false"
eternal="false"
timeToLiveSeconds="0"
timeToIdleSeconds="0"
diskPersistent="false"
statistics="true"/>
配置 Bean:
<!-- Session ID 生成器 -->
<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
<!-- SessionDao, 继承 EnterpriseCacheSessionDAO -->
<bean id="sessionDao" class="com.tc.shiro.realms.MySessionDao">
<property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
<property name="sessionIdGenerator" ref="sessionIdGenerator"/>
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">
<property name="globalSessionTimeout" value="1800000"/>
<property name="deleteInvalidSessions" value="true"/>
<property name="sessionValidationSchedulerEnabled" value="true"/>
<property name="sessionDAO" ref="sessionDao"/>
</bean>
在 securityManager 的 Bean 中添加:
<property name="sessionManager" ref="sessionManager"/>
新建数据表, session 是存放对象序列化之后的数据
新建 MySessionDao 类, 继承 EnterpriseCacheSessionDAO
建立对象序列化与反序列化工具类 SerializableUtils
8. Remember Me
概念:
- subject.isAuthenticated(): 表示用户进行了身份验证登录的, 即使用 Subject.login 进行了登录
- subject.isRemembered(): 表示用户是通过记住我登录的, 此时可能并不是真正的你(如你的朋友使用你的电脑, 或者你的 cookie 被窃取)在访问的
- 两者二选一,即 subject.isAuthenticated() == true, 则 subject.isRemembered() == false, 反之一样
建议:
- 访问一般网页: 如个人在主页之类的, 我们使用 user 拦截器即可, user 拦截器只要用户登录(isRemembered() || isAuthenticated())过即可访问成功
- 访问特殊网页: 如我的订单, 提交订单页面, 我们使用 authc 拦截器即可, authc 拦截器会判断用户是否是通过 Subject.login(isAuthenticated() == true)登录的, 如果是, 才放行, 否则会跳转到登录页面让你重新登录
设置 RememberMe
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
token.setRememberMe(true);
在 securityManager 中设置 RememberMe 的 Cookie 的失效时间, 单位为 s
注意: 这么配在运行时是可以读取到的(debug试验过), 只是 IDEA 写的时候会报红
<property name="rememberMeManager.cookie.maxAge" value="10"/>
也可以详细配置: