前不久负责项目中刚好也使用了Shiro做权限控制,趁着空闲期想把之前做的整理一下。在日常项目开发中,权限认证是不可少的模块。比较常用的有Spring Security,或是轻量级的Apache Shiro。相对来说Shiro提供了认证、授权、加密、会话管理、与Web集成、缓存等。这些都是日常会用到的,而且Shiro的API比较简洁,学习成本相对低。接下来将整理一下在SpringBoot中如何集成Shiro:
- RBAC介绍
- SpringBoot集成Shiro和配置
- Shiro的登录和认证
- 当前不足点
**RBAC(Role-Based Access Control )**基于角色访问控制,在权限设计上用户是基于角色进行权限认证,而角色又是和资源相关联的。这样在设计和管理上简化了权限的操作,它们都是层级依赖,更方便我们的管理。如此一来,数据库表设计可以如下图:

在pom.xml中加入以下依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.5</version>
</dependency>
在配置之前,首先了解一下Shiro中主要功能,并看看它们主要是做什么的。
- Subject 安全视角下与软件交互的实体(用户,第三方服务等等)
- Authenticator 用户登录时进行账户的认证
- Authorizer 用户登录时进行账户的权限资源认证
- Realms每当执行认证或授权时,shiro会从程序配置的一个或多个Realm中查询
新建JAVA类ShiroRealm用于继承Shiro的AuthorizingRealm抽象类,并复写doGetAuthenticationInfo和doGetAuthorizationInfo用于账户和权限的认证。
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName = token.getUsername();
String password = new String((char[])token.getCredentials());
//这里可以自行查询数据库进行验证
if(userName != "zhangshan" && password != DigestUtils.md5Hex("123456")) {
throw new UnknownAccountException ("未知的账户认证失败");
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userName, //用户名
DigestUtils.md5Hex("123456"),