springboot(十):springboot整合shiro权限控制
1.数据库设计
2.引入的pom
<dependencies>
<!--springboot web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--springboot test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<!-- shiro 权限控制 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--spring data jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
3.对应的实体类
数据库中的user3表对应的user3实体类:
为了保证返回值是restful风格,可以使用一个ResponseBean来规范返回值的格式:
4.查询数据库的service和dao层
dao层:通过用户名查询数据库中的user3
service中也是通过用户名查询用户对象user3
5.controller层
用户的登陆管理的controller:
/** * 这是一个用户接入的controller */
@RestController
public class UserAccessController {
@Autowired
private UserService userService;
/** * 登陆:完成JWT的注册 * @param username * @param password * @return */
@PostMapping("/login")
public ResponseBean login(@RequestParam("username") String username,
@RequestParam("password") String password) {
User3 userBean = userService.getUserByUserName(username);
if (userBean.getPassword().equals(password)) {
return new ResponseBean(200, "Login success", JWTUtil.sign(username, password));
} else {
throw new UnauthorizedException();
}
}
/** * 所有人都可以访问,但是用户与游客看到的内容不同 * @return */
@GetMapping("/article")
public ResponseBean article() {
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
return new ResponseBean(200, "You are already logged in", null);
} else {
return new ResponseBean(200, "You are guest", null);
}
}
/** * 登入的用户才可以进行访问 * @return */
@GetMapping("/require_auth")
@RequiresAuthentication //需要登陆的用户,也就是用户请求request的头部含有“Authentication”标签
public ResponseBean requireAuth() {
return new ResponseBean(200, "You are authenticated", null);
}
/** * admin的角色用户才可以登入 * @return */
@GetMapping("/require_role")
@RequiresRoles("admin") //需要角色为admin
public ResponseBean requireRole() {
return new ResponseBean(200, "You are visiting require_role", null);
}
/** * 拥有view和edit权限的用户才可以访问 * @return */
@GetMapping("/require_permission")
@RequiresPermissions(logical = Logical.AND, value = {"view", "edit"}) //需要permission是view或者edit
public ResponseBean requirePermission() {
return new ResponseBean(200, "You are visiting permission require edit,view", null);
}
/** * 未授权的用户访问,跳转到此页面 * @return */
@RequestMapping(path = "/401")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ResponseBean unauthorized() {
return new ResponseBean(401, "Unauthorized", null);
}
}
异常处理的controller:
/** * 全局异常处理:如果请求没有带有 token 或者带了 token 但权限认证不通过, * 则会报 UnauthenticatedException 异常,但是我在 ExceptionController 类对这些异常进行了集中处理 */
@RestControllerAdvice
public class ExceptionController {
// 捕捉shiro的异常
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(ShiroException.class)
public ResponseBean handle401(ShiroException e) {
return new ResponseBean(401, e.getMessage(), null);
}
// 捕捉UnauthorizedException
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException.class)
public ResponseBean handle401() {
return new ResponseBean(401, "Unauthorized", null);
}
// 捕捉其他所有异常
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean globalException(HttpServletRequest request, Throwable ex) {
return new ResponseBean(getStatus(request).value(), ex.getMessage(), null);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
6.shiro的工作原理
shiro架构图如下:
Authentication(认证):用户身份识别,通常被称为用户“登录”
Authorization(授权):访问控制。比如某个用户是否具有某个操作的使用权限。
Session Management(会话管理):特定于用户的会话管理,甚至在非web 或 EJB 应用程序。
Cryptography(加密):在对数据源使用加密算法加密的同时,保证易于使用
在概念层,Shiro 架构包含三个主要的理念:Subject,SecurityManager和 Realm。下面的图展示了这些组件如何相互作用,我们将在下面依次对其进行描述。
应用代码直接交互的对象是Subject。
-
Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者;
-
SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过- SpringMVC,你可以把它看成DispatcherServlet前端控制器;
-
Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。
7.token的载体
package com.qianliu.springboot_test.shiro.tokenBean;
import org.apache.shiro.authc.AuthenticationToken;
/** * token的载体 */
public class JwtToken implements AuthenticationToken {
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
8.token的辅助工具类
JWTUtil 实现了注册token,验证已有的token用密钥是否可以验证token的正确性,获取token中的数据(此处是username)。
package com.qianliu.springboot_test.utils.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Date;
/** * 使用用户自己的密码充当加密密钥,这样保证了token 即使被他人截获也无法破解。 * 并且我们在token中附带了username信息,并且设置密钥5分钟就会过期。 */
public class JWTUtil {
// 过期时间5分钟
private static final long EXPIRE_TIME = 5*60*1000;
/** * 校验token是否正确 * @param token 密钥 * @param secret 用户的密码 * @return 是否正确 */
public static boolean verify(String token, String username, String secret) {
try {
//根据密码生成JWT效验器
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
//校验TOKEN
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
}
}
/** * 获得token中的信息无需secret解密也能获得 * @return token中包含的用户名 */
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}
/** * 生成签名,5min后过期 * @param username 用户名 * @param secret 用户的密码 * @return 加密的token */
public static String sign(String username, String secret) {
Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带username信息
return JWT.create()
.withClaim("username", username)
.withExpiresAt(date)
.sign(algorithm);
}
}
9.自定义的一个过滤器
JwtFilter 用于验证所有网页请求的是否含有“Authorization”字段的头部(没有“Authorization”直接交给“/401”页面),和头部内容中的token是否有效,实现跨域使用token,实现登陆的token验证交给了realm。
package com.qianliu.springboot_test.shiro.filter;
import com.qianliu.springboot_test.shiro.tokenBean.JwtToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/** * 使用shiro来拦截token,那就需要我们自己写一个jwt过滤器来作为shiro的过滤器 * * 执行流程:preHandle->isAccessAllowed->isLoginAttempt->executeLogin */
public class JwtFilter extends BasicHttpAuthenticationFilter {
private Logger LOGGER = LoggerFactory.getLogger(this.getClass());
/** * 对跨域提供支持 */
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态
if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
return super.preHandle(request, response);
}
/** * 这里我们详细说明下为什么最终返回的都是true,即允许访问 * 例如我们提供一个地址 GET /article * 登入用户和游客看到的内容是不同的 * 如果在这里返回了false,请求会被直接拦截,用户看不到任何东西 * 所以我们在这里返回true,Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入 * 如果有些资源只有登入用户才能访问,我们只需要在方法上面加上 @RequiresAuthentication 注解即可 * 但是这样做有一个缺点,就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法),但实际上对应用影响不大 */
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//判断请求的请求头是否带上 "Token"
if (isLoginAttempt(request, response)) {
try {
//如果存在,则进入 executeLogin 方法执行登入,检查 token 是否正确
executeLogin(request, response);
} catch (Exception e) {
response401(request, response);
}
}
//如果请求头不存在 Token,则可能是执行登陆操作或者是游客状态访问,无需检查 token,直接返回 true
return true;
}
/** * 判断用户是否想要登入。 * 检测header里面是否包含Authorization字段即可 */
@Override
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
HttpServletRequest req = (HttpServletRequest) request;
String authorization = req.getHeader("Authorization"); //头部带有Authorization表示希望登陆,不带有就是游客
return authorization != null;
}
/** * subject.isAuthenticated()和带有@RequiresAuthentication标签的方法会触发此方法,进行验证是否登陆 */
@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
System.out.println("executeLogin");
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authorization = httpServletRequest.getHeader("Authorization");
JwtToken token = new JwtToken(authorization);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
getSubject(request, response).login(token); //这一步就是提交给了realm进行处理
// 如果没有抛出异常则代表登入成功,返回true
// 如果在 token 校验的过程中出现错误,如 token 校验失败,那么我会将该请求视为认证不通过,则重定向到 /unauthorized/**
return true;
}
/**
* 将非法请求跳转到 /401
*/
private void response401(ServletRequest req, ServletResponse resp) {
try {
HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
httpServletResponse.sendRedirect("/401");
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}
10.shiro的配置
ShiroConfig这个配置实现securityManager的初始化,配置url(所有的过滤器都经过“jwt”过滤器,但是“/401”不经过jwt,而是直接使用系统的anon过滤器),添加注解支持
package com.qianliu.springboot_test.shiro.shiroConfig;
import com.qianliu.springboot_test.shiro.filter.JwtFilter;
import com.qianliu.springboot_test.shiro.realm.MyRealm;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean("securityManager")
public DefaultWebSecurityManager getManager(MyRealm realm) {
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
// 使用自己的realm
manager.setRealm(realm);
/* * 关闭shiro自带的session,详情见文档 * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29 */
DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
manager.setSubjectDAO(subjectDAO);
return manager;
}
/** * 配置过滤器 * @param securityManager 权限管理 * @return */
@Bean("shiroFilter")
public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
// 添加自己的过滤器并且取名为jwt
Map<String, Filter> filterMap = new HashMap<>();
filterMap.put("jwt", new JwtFilter());
factoryBean.setFilters(filterMap);
factoryBean.setSecurityManager(securityManager);
factoryBean.setUnauthorizedUrl("/401");
/* * 自定义url规则 * http://shiro.apache.org/web.html#urls- */
Map<String, String> filterRuleMap = new HashMap<>();
// 所有请求通过我们自己的JWT Filter
filterRuleMap.put("/**", "jwt");
// 访问401和404页面不通过我们的Filter
//1.多个过滤器 AnonymousFilter 匿名过滤器 简称anon
//2.FormAuthenticationFilter 认证过滤器 简称authc
//此处的用意: 因为jwt过滤器会跳转到"/401",所以需要声明一下,为anon匿名过滤器,
// 所有“/401”都走anon过滤器而不是jwt,而不是jwt跳到jwt,会形成一个递归
filterRuleMap.put("/401", "anon");
factoryBean.setFilterChainDefinitionMap(filterRuleMap);
return factoryBean;
}
/** * 下面的代码是添加注解支持 */
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
// 强制使用cglib,防止重复代理和可能引起代理出错的问题
// https://zhuanlan.zhihu.com/p/29161098
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
11.Realm解决permission和登陆的验证
package com.qianliu.springboot_test.shiro.realm;
import com.qianliu.springboot_test.model.User3;
import com.qianliu.springboot_test.service.UserService;
import com.qianliu.springboot_test.shiro.tokenBean.JwtToken;
import com.qianliu.springboot_test.utils.jwt.JWTUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@Component
public class MyRealm extends AuthorizingRealm {
private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
/** * 大坑!,必须重写此方法,不然Shiro会报错 */
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
/** * 只有当需要检测用户权限的时候才会调用此方法,例如checkRole,checkPermission和@RequiresPermissions标签之类的 * * 利用 token 中获得的 username,分别从数据库查到该用户所拥有的角色,权限,存入 SimpleAuthorizationInfo 中 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("doGetAuthorizationInfo principals");
String username = JWTUtil.getUsername(principals.toString()); //将token中的内容拿出来
User3 user = userService.getUserByUserName(username); //从数据库中更具username拿出user
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();//获取授权中心
simpleAuthorizationInfo.addRole(user.getRole()); //角色
Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(","))); //用户的权限,可能是多种,放在一个set中
simpleAuthorizationInfo.addStringPermissions(permission);
return simpleAuthorizationInfo;
}
/** * 默认使用此方法进行用户名正确与否验证,所有***拦截下来的访问都会经过该方法,错误抛出异常即可。 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
System.out.println("doGetAuthenticationInfo AuthenticationToken");
String token = (String) auth.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JWTUtil.getUsername(token);
if (username == null) {
throw new AuthenticationException("token invalid");
}
User3 userBean = userService.getUserByUserName(username);
if (userBean == null) {
throw new AuthenticationException("User didn't existed!");
}
if (! JWTUtil.verify(token, username, userBean.getPassword())) {
throw new AuthenticationException("Username or password error");
}
return new SimpleAuthenticationInfo(token, token, "my_realm");
}
}