本文将带你从0开始搭建一个Springboot+shiro动态权限控制
首先你得知道什么是Shiro?
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解API,你可以快速、轻松地获取任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
官网:[点我进入]
开发环境:
<!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <!-- springboot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> </parent>
1.编写LoginController
@PostMapping("/login")
@ApiOperation("登录系统")
@Log(module = "登录系统", description = "登陆系统")
public ResultResponse login(@RequestBody LoginInoutDTO inoutDTO) {
if (StringUtils.isBlank(inoutDTO.getUsername()) || StringUtils.isBlank(inoutDTO.getPassword())) {
return new ResultResponse(false, ErrorDetail.RC_0401001.getIndex(), "参数不全", null);
}
//当前登录的用户
Subject currentUser = SecurityUtils.getSubject();
// 如果这个用户没有登录,进行登录功能
if (!currentUser.isAuthenticated()) {
try {
// 验证身份和登陆
UsernamePasswordToken token = new UsernamePasswordToken(inoutDTO.getUsername(), inoutDTO.getPassword());
currentUser.login(token);
permissionsConfig.updatePermission();
} catch (UnknownAccountException e) {
return new ResultResponse(false, ErrorDetail.RC_0401001.getIndex(), "此账号不存在!", null);
} catch (IncorrectCredentialsException e) {
return new ResultResponse(false, ErrorDetail.RC_0401001.getIndex(), "用户名或者密码错误,请重试!", null);
} catch (LockedAccountException e) {
return new ResultResponse(false, ErrorDetail.RC_0401001.getIndex(), "该账号已被锁定,请联系管理员!", null);
} catch (AuthenticationException e) {
return new ResultResponse(false, ErrorDetail.RC_0401001.getIndex(), "未知错误,请联系管理员!", null);
}
}
return new ResultResponse(true, ErrorDetail.RC_0000000.getIndex(), "登录成功", userInfo);
}
}
2.自定义Realm
/**
* Created by Eagga_Lo on 2019/11/26 14:19
*/
@Slf4j
public class ShiroRealm extends AuthorizingRealm {
@Autowired
UserService userService;
@Autowired
RoleService roleService;
@Autowired
MenuService menuService;
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
log.info("--------------开始授权操作--------------");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principalCollection.getPrimaryPrincipal();
log.info("user:{}", user.toString());
Set<String> rolesSet = new HashSet<>();
Set<String> permsSet = new HashSet<>();
try {
List<Role> roleList = roleService.selectRoleByUserId(user.getById());
for (Role role : roleList) {
rolesSet.add(role.getRoleId());
List<XtZzjgMenu> menuList = menuService.selectMenuByRoleId(role.getRoleId());
for (XtZzjgMenu menu : menuList) {
permsSet.add(menu.getResource());
}
}
log.info("--------------当前用户的角色:{}--------------", rolesSet);
log.info("--------------当前角色的权限:{}--------------", permsSet);
//将查到的权限和角色分别传入authorizationInfo中
authorizati