此为shiro学习总结,适用于快速入门shiro。
一、相关概念
首先是用户(user)具有role、permission、principal、credential这四个概念:
对于已经登录的用户,具有角色role,比如admin/customer等;不同角色可能具有不同的权限permission,如read/write/export等,principal是一个subject的唯一标识,可以是username,也可以是一个user对象,总之是能够唯一标识此subject的;credential就是密码。这四个需要开发者自己去定义相关表。
UsernamePasswordToken、AuthenticationToken:我个人测试的结果,发现这两个其实是一样的玩意,可以用来储存前台传递的用户名、密码。
AuthenticationInfo和AuthorizationInfo:注意看这两个,是不一样的对象。AuthenticationInfo是用来认证用户(user)的,存储的是从数据库中获取的用户信息,其中的内容会与UsernamePasswordToken(AuthenticationToken)中的用户信息相比较,相匹配则登录成功,反之会抛出相应异常。AuthorizationInfo中存储的是已经通过认证的用户,所具有的角色以及权限信息等。
二、shiro组件
DelegatingFilterProxy:配置在web.xml的fliter,用于拦截所有进行权限管理的URL,在spring容器启动后,会寻找定义的shiroFliter这个bean。
shiroFliter:实现类为ShiroFliterFactoryBean,对于这个组件我个人的理解是,用来定义拦截URL的具体规则,以及认证不通过时默认跳转的页面等等。具体配置项意义会在shiro的配置文件中注释说明。
SecurityManager:shiro管理的核心,shiro的许多类都注入了SecurityManager,一般情况下不用对SecurityManager进行修改,只需要记得注入SecurityManager即可。另外如果追踪源码的话,你会发现哪哪都有这玩意。
CredentialsMatcher:默认实现类HashedCredentialsMatcher,这个组件使用来匹配用户名和密码的,如果你对密码进行了加密的话,需要指明其algorithmName(加密算法)、hashIterations(散列次数),要注意的是你加密的算法和散列次数一定要和在CredentialsMatcher配置的一致。
cacheManager:缓存管理器,注意在查询用户角色和权限的时候,数据库的查询量还是很大的,所以缓存用户角色和权限信息很有必要,但不是硬性配置,可以选取的缓存常有ehcache框架或者redis等缓存。
Relam:这个是重中之重,需要用户个人去自定义的,包含两个方法doGetAuthenticationInfo(),doGetAuthorizationInfo()。
doGetAuthenticationInfo()是用来认证用户的,在用户登录的时候会调用此方法;doGetAuthorizationInfo()是用来查询已经通过认证的用户(已登录的用户)角色以及身份信息的。
Subject:这个组件是一个宏观上的东西,理解起来很抽象,你可以将其理解成当前user。之所以把这个放到最后来说,是因为查看Subject源码中的方法,可以知道,这个组件是与permission、role、Principal、session这些概念相关的,理解了这些概念,也就知道Subject是什么了。
三、搭建项目
配置web.xml:
<!-- shiro配置 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<!-- 拦截的url类型,仅拦截do -->
<url-pattern>*.do</url-pattern>
</filter-mapping>
shiro的配置文件applicationContext-shiro.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自定义的realm-->
<bean id="userRealm" class="shiro.security.UserRealm">
<!--可以引入的credentialsMatcher对密码进行加密
<property name="credentialsMatcher" ref="credentialsMatcher" />
</bean>
-->
<!-- 配置安全管理器SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<!--给shiro添加缓存机制,与ehcache整合-->
<property name="cacheManager" ref="cacheManager"></property>
</bean>
<!-- 定义ShiroFilter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<!--没有登录的用户请求需要登录的页面时自动跳转到登录页面 -->
<property name="loginUrl" value="/user/loginp.do"/>
<!--权限不足跳转的页面-->
<property name="unauthorizedUrl" value="/accessDenied.do"/>
<property name="filterChainDefinitions">
<!--定义url拦截规则-->
<value>
/user/loginp.do=anon
/user/login.do=anon
/user/registp.do=anon
/user/regist.do=anon
/test/getAllRolesSn.do=anon
/adminAccess.do=roles[admin]
/**=authc
</value>
</property>
</bean>
<!-- 开启shiro注解支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<bean id="ehCacheManager" class ="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:shiro-ehcache.xml" />
<property name="shared" value="true"></property>
</bean>
</beans>
上述配置项的说明:
在userRealm中注入的credentialsMatcher是可选项,主要credentialsMatcher主要功能是对密码加密,这里取消配置。
shiroFilter中配置的url拦截规则:
anno代表用户不需要验证就可以访问的资源;roles[admin]代表具有admin角色的用户才可以访问;authc代表用户必须通过验证(登录)后才可以访问的资源。
除了可以在xml中配置规则外,还使用注解进行配置,前提是在配置文件中开启了shiro注解。
以上关于url拦截的更多配置内容可以参考博客https://www.cnblogs.com/koal/p/5152671.html、https://www.cnblogs.com/pingxin/p/p00115.html。总结的很好。
接下来是自定义的UserRealm.java:
package shiro.security;
import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import shiro.mapper.CustomRoleDao;
import shiro.pojo.User;
public class UserRealm extends AuthorizingRealm {
@Autowired
CustomRoleDao customRoleDao;
//这个方法只是用来认证用户的,并不涉及任何roles,permission相关
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
throws AuthenticationException {
// 从token中获取登录的用户名, 查询数据库返回用户信息
String username = (String) authcToken.getPrincipal();
User user = customRoleDao.getUserByUsername(username);
if (user == null) {
return null;
}
String password = user.getPassword();
// SimpleAuthenticationInfo中的第一个参数即为principle,这里是对象,也可以是string(username,id)
// 第二个参数,credential即密码
// 第三个参数为credentialsSalt,这里没有加盐
// getName()对应的参数为realm_name,即UserRealm,在创建principleCollection时需要使用
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,
ByteSource.Util.bytes(user.getUsername()), getName());
return info;
}
}
/**
* 查询用户角色、权限信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
User user = (User) principals.getPrimaryPrincipal();
List<String> permissions = new ArrayList<String>();
List<String> roles = new ArrayList<String>();
if ("admin".equals(user.getUsername())) {
// 拥有所有权限
permissions.add("*:*");
// 查询所有角色
roles = customRoleDao.getAllRoleSn();
} else {
// 根据用户id查询该用户所具有的角色
roles = customRoleDao.getRoleSnByUserId(user.getId());
// 根据用户id查询该用户所具有的权限
permissions = customRoleDao.getPermissionResourceByUserId(user.getId());
}
for (String role : roles) {
System.err.println("打印roles信息");
System.out.println("role:"+role);
}
for (String permission : permissions) {
System.err.println("打印permissions信息");
System.out.println("permission:"+permission);
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(permissions);
info.addRoles(roles);
return info;
}
然后是login方法:
@RequestMapping("/login")
public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password) {
//用来加密密码的类
PasswordHelper ph = new PasswordHelper();
UsernamePasswordToken token = new UsernamePasswordToken(username, ph.encryptPassword(password));
//打印token信息
System.err.println("开始打印token信息");
System.err.println(token.getUsername());
System.err.println(token.getPassword());
System.err.println(token.getCredentials());
System.err.println(token.getPrincipal());
Subject subject = SecurityUtils.getSubject();
subject.login(token);
try {
//在调用login()方法前,会调用UserRealm中的AuthenticationInfo()
subject.login(token);
System.out.println(subject.isAuthenticated());
} catch (IncorrectCredentialsException ice) {
// 捕获密码错误异常
ModelAndView mv = new ModelAndView("error");
mv.addObject("message", "password error!");
return mv;
} catch (UnknownAccountException uae) {
// 捕获未知用户名异常
ModelAndView mv = new ModelAndView("error");
mv.addObject("message", "username error!");
return mv;
} catch (ExcessiveAttemptsException eae) {
// 捕获错误登录过多的异常
ModelAndView mv = new ModelAndView("error");
mv.addObject("message", "times error");
return mv;
}
catch (AuthenticationException ae) {
// 捕获其他异常
ModelAndView mv = new ModelAndView("error");
mv.addObject("message", "AuthenticationException error");
return mv;
}
User user = customRoleDao.getUserByUsername(username);
subject.getSession().setAttribute("user", user);
return new ModelAndView("success");
}
上面的subject.login()是shiro提供的方法,通过这个方法会判断AuthenticationInfo和AuthenticationToken(UsernamePasswordToken)中的内容,上述已经有过说明。
四、shiro流程总结
首先在web.xml中配置的fliter在应用启动的时候,会在spring容器中找bean_shiroFliter,shiroFliter的作用是对URL进行拦截,其中定义了拦截URL的规则。
当用户进行登录时,将前台传递过来的用户名/密码存储在UsernamePasswordToken中,在调用subject.login()时会首先访问realm中的doGetAuthenticationInfo()方法,这个方法中的逻辑是查询数据库,并将查询到的用户名/密码存入AuthenticationInfo对象。将UsernamePasswordToken、AuthenticationInfo中的内容比较,即可得出用户认证(登录)的结果。
用户认证成功后,在访问url时,会涉及到角色以及权限的问题,只有满足相应的角色/权限,才可以访问url。url权限的限定可以在xml中定义,也可以使用注解。
以上只是是大致的流程,具体的建议自己去看看源码,搞清楚各个组件、方法的作用。