实现动态权限控制及用户身份认证的SpringBoot+SpringSecurity+Jwt整合项目
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Security依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- MybatisPlus 核心库 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 引入阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<!-- StringUtilS工具 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!-- JSON工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.45</version>
</dependency>
<!-- JWT依赖 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
</dependencies>
数据库表结构
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : spring_security
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 19/08/2020 11:37:17
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for menu
-- ----------------------------
DROP TABLE IF EXISTS `menu`;
CREATE TABLE `menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pattern` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '请求路径匹配规则',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of menu
-- ----------------------------
INSERT INTO `menu` VALUES (1, '/db/**');
INSERT INTO `menu` VALUES (2, '/admin/**');
INSERT INTO `menu` VALUES (3, '/user/**');
-- ----------------------------
-- Table structure for menu_role
-- ----------------------------
DROP TABLE IF EXISTS `menu_role`;
CREATE TABLE `menu_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mid` int(11) NOT NULL COMMENT 'menu表外键',
`rid` int(11) NOT NULL COMMENT 'role表外键',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of menu_role
-- ----------------------------
INSERT INTO `menu_role` VALUES (1, 1, 1);
INSERT INTO `menu_role` VALUES (2, 2, 2);
INSERT INTO `menu_role` VALUES (3, 3, 3);
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`nameZh` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'dba', '数据库管理员');
INSERT INTO `role` VALUES (2, 'admin', '系统管理员');
INSERT INTO `role` VALUES (3, 'user', '用户');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`enabled` tinyint(1) NULL DEFAULT NULL,
`locked` tinyint(1) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'root', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', 1, 0);
INSERT INTO `user` VALUES (2, 'admin', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', 1, 0);
INSERT INTO `user` VALUES (3, 'sang', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', 1, 0);
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NULL DEFAULT NULL,
`rid` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES (1, 1, 1);
INSERT INTO `user_role` VALUES (2, 1, 2);
INSERT INTO `user_role` VALUES (3, 2, 2);
INSERT INTO `user_role` VALUES (4, 3, 3);
SET FOREIGN_KEY_CHECKS = 1;
编写实体类
User类:
需要实现UserDetails接口,用于SpringSecurity的用户状态认证(登录用户名密码、用户是否锁定、用户账号是否可用…)
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Data
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
/**
* 用户具备的角色
*/
@TableField(exist = false)
private List<Role> roles;
/**
* 登录后返回的token
*/
@TableField(exist = false)
private String token;
/**
* 该方法用来获取当前用户所具有的角色
* @return 角色的集合
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>(roles.size());
roles.forEach(role -> {
authorities.add(new SimpleGrantedAuthority(role.getName()));
});
return authorities;
}
/**
* Returns the password used to authenticate the user.
* 返回将要被认证的用户密码
* @return
*/
@Override
public String getPassword() {
return password;
}
/**
* Returns the username used to authenticate the user. Cannot return <code>null</code>.
* 返回将要认证的用户的用户名,不能为空
* @return
*/
@Override
public String getUsername() {
return username;
}
/**
* Indicates whether the user's account has expired. An expired account cannot be authenticated.
* 账户是否过期,过期的账户不能被认证
* @return
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
/**
* Indicates whether the user is locked or unlocked. A locked user cannot be authenticated.
* 账户是否被锁定,锁定的账户不能被认证
* @return
*/
@Override
public boolean isAccountNonLocked() {
return !locked;
}
/**
* Indicates whether the user's credentials (password) has expired. Expired credentials prevent authentication.
* 账户密码是否过期
* @return
*/
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* Indicates whether the user is enabled or disabled. A disabled user cannot be authenticated.
* 账户是否可用
* @return
*/
@Override
public boolean isEnabled() {
return enabled;
}
}
Role类:
import lombok.Data;
@Data
public class Role {
private Integer id;
private String name;
private String nameZh;
}
Menu类:
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.util.List;
@Data
public class Menu {
private Integer id;
private String pattern;
/**
* 当前路径需要具备的角色
*/
@TableField(exist = false)
private List<Role> roles;
}
核心配置类SecurityConfig
该类负责注册有关权限控制和用户登录校验的类
package com.changan.config;
import com.changan.filter.JwtFilter;
import com.changan.filter.JwtLoginFilter;
import com.changan.filter.MyPermissionFilter;
import com.changan.service.auth.AuthUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* @author NieChangan
* @date 2020/8/17 22:52
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
AuthUserDetailsServiceImpl authUserDetailsService;
@Autowired
MyPermissionFilter myPermissionFilter;
@Autowired
CustomAccessDecisionManager customAccessDecisionManager;
//使用的密码加密方式
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//注册登录认证方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authUserDetailsService);
}
//配置登录及注销及权限配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//注册MyFilter和customAccessDecisionManager进行权限管理
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setAccessDecisionManager(customAccessDecisionManager);
o.setSecurityMetadataSource(myPermissionFilter);
return o;
}
})
//路径为“/doLogin”的POST请求自动放行
.antMatchers(HttpMethod.POST, "/doLogin")
.permitAll()
//其它请求都需要认证
.anyRequest().authenticated()
.and()
//添加登录的过滤器,当请求路径为"/doLogin"时该过滤器截取请求
.addFilterBefore(new JwtLoginFilter("/doLogin",
authenticationManager()), UsernamePasswordAuthenticationFilter.class)
//添加token校验的过滤器,每次发起请求都被该过滤器截取
.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf().disable();
}
}
登录认证
定义JwtLoginFilter类,用户登录时会被该过滤器截取下来,defaultFilterProcessesUrl代表登录的请求路径,如果定义为“/doLogin”时,用户请求登录"/doLogin"将会来到该过滤器的attemptAuthentication()方法进行用户名和密码的校验,如果校验成功则会生成token返回给客户端
package com.changan.filter;
import com.changan.bean.User;
import com.changan.utils.JsonResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
/**
* @author NieChangan
* @date 2020/8/17 11:16
*/
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {
public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
setAuthenticationManager(authenticationManager);
}
/**
* 从登录参数中提取出用户名密码, 然后调用 AuthenticationManager.authenticate() 方法去进行自动校验
* @param req
* @param resp
* @return
* @throws AuthenticationException
* @throws IOException
* @throws ServletException
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse resp) throws AuthenticationException, IOException, ServletException {
String username = req.getParameter("username");
String password = req.getParameter("password");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
return getAuthenticationManager().authenticate(token);
}
/**
* 校验成功的回调函数,生成jwt的token
* @param req
* @param resp
* @param chain
* @param authResult
* @throws IOException
* @throws ServletException
*/
@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse resp, FilterChain chain, Authentication authResult) throws IOException, ServletException {
Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
StringBuffer roles = new StringBuffer();
//遍历用户角色,将其写入jwt中
for (GrantedAuthority authority : authorities) {
roles.append(authority.getAuthority())
.append(",");
}
String jwt = Jwts.builder()
.claim("authorities", roles)//配置用户角色
.setSubject(authResult.getName())//设置jwt的主题为用户的用户名
.setExpiration(new Date(System.currentTimeMillis() + 10 * 60 * 1000))//设置过期时间为10分钟
.signWith(SignatureAlgorithm.HS512,"turing-team") //使用密钥对头部和载荷进行签名
.compact();//生成jwt
//返回给前端
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
User user = (User) authResult.getPrincipal();
user.setToken(jwt);
JsonResultUtil jsonResultUtil = JsonResultUtil.success("登录成功", user);
System.out.println(jsonResultUtil.toString());
out.write(new ObjectMapper().writeValueAsString(jsonResultUtil));
out.flush();
out.close();
}
/**
* 校验失败的回调函数
* @param req
* @param resp
* @param failed
* @throws IOException
* @throws ServletException
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp, AuthenticationException failed) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
JsonResultUtil failure = JsonResultUtil.failure("用户名或密码错误,请重新登录!", null);
out.write(new ObjectMapper().writeValueAsString(failure));
out.flush();
out.close();
}
}
验证token过滤器
package com.changan.filter;
import com.changan.utils.JsonResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* @author NieChangan
* @date 2020/8/17 11:43
* 用户携带的token是否有效
*/
public class JwtFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
//获取token
String cliToken = req.getHeader("token");
PrintWriter pw;
if("".equals(cliToken) || cliToken == null){
pw = resp.getWriter();
resp.setContentType("application/json;charset=utf-8");
JsonResultUtil jsonResult = JsonResultUtil.failure("必须传递用户的认证信息", null);
pw.write(new ObjectMapper().writeValueAsString(jsonResult));
pw.flush();
pw.close();
return ;
}
//解析token
Jws<Claims> jws;
try {
jws = Jwts.parser()
.setSigningKey("turing-team") //设置生成jwt时使用的密钥
.parseClaimsJws(cliToken);
}catch (JwtException ex){
pw = resp.getWriter();
resp.setContentType("application/json;charset=utf-8");
JsonResultUtil jsonResult = JsonResultUtil.failure("登录已过期,请重新登陆", null);
pw.write(new ObjectMapper().writeValueAsString(jsonResult));
pw.flush();
pw.close();
return ;
}
Claims claims = jws.getBody();
//获取用户的用户名,在生成token时指定了主题为用户名
String username = claims.getSubject();
//获取用户的所有角色,以逗号分割的字符串
String authoritiesStr = (String) claims.get("authorities");
//转成用户的所有角色对象
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesStr);
//对用户进行校验
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(token);
//放行
filterChain.doFilter(servletRequest, servletResponse);
}
}
获取请求路径所需角色过滤器
package com.changan.filter;
import com.changan.bean.Menu;
import com.changan.bean.Role;
import com.changan.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.List;
/**
* @author NieChangan
* @date 2020/8/17 23:05
* 定义过滤器,分析出用户的请求地址匹配逻辑并分析出需要哪些角色
*/
@Component
public class MyPermissionFilter implements FilterInvocationSecurityMetadataSource {
//路径匹配类,用于检查用户的请求路径是否与数据库中某个路径规则匹配
AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
MenuService menuService;
//每次用户发出请求都会先进入该方法,分析出该请求地址需要哪些角色
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//强转对象
FilterInvocation filterInvocation = (FilterInvocation) o;
//获取用户请求地址
String requestUrl = filterInvocation.getRequestUrl();
//获取所有路径规则
List<Menu> menus = menuService.findAllMenusWithRoles();
//遍历路径规则
for (Menu menu : menus) {
//判断与哪一条路由规则匹配
if(antPathMatcher.match(menu.getPattern(), requestUrl)){
//获取访问该路径所需要的所有角色
List<Role> roles = menu.getRoles();
//转化为返回值类型
String[] rolesStr = new String[roles.size()];
for (int i = 0; i < rolesStr.length; i++) {
rolesStr[i] = roles.get(i).getName();
}
return SecurityConfig.createList(rolesStr);
}
}
//全部都匹配不上,则返回一个默认的标识符,表示该路径是登录后就可以访问的路径
return SecurityConfig.createList("ROLE_login");
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
//是否支持该方式,返回true
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
用户权限验证
package com.changan.config;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Collection;
/**
* @author NieChangan
* @date 2020/8/17 23:33
* 判断请求当前用户具有哪些角色,如果用户具备访问路径须具备的角色则允许访问,否则判为非法请求
*/
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
/**
* 核心方法,判断用户是否可以有权限访问该路径
* @param authentication 可以获取登录的用户信息
* @param o 实际是FilterInvocation对象,可以获取请求路径
* @param collection 访问该路径所需要的角色,是MyFilter中的返回值
* @throws AccessDeniedException 非法请求,权限不够
* @throws InsufficientAuthenticationException
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//遍历访问该路径所需要的所有角色名字
for (ConfigAttribute configAttribute : collection) {
//如果是登录后可访问,直接放行
if("ROLE_login".equals(configAttribute.getAttribute())){
//判断用户是否登录
if(authentication instanceof AnonymousAuthenticationToken){
throw new AccessDeniedException("尚未登录,请前往登录!");
}
return ;
}
//获取当前用户所具有的所有角色
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//遍历该用户的所有角色并判断是否具有必须具备的角色
for (GrantedAuthority authority : authorities) {
if(authority.getAuthority().equals(configAttribute.getAttribute())){
return ;
}
}
}
throw new AccessDeniedException("权限不足,请联系管理员!");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
AuthUserDetailsServiceImpl
package com.changan.service.auth;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changan.bean.Role;
import com.changan.bean.User;
import com.changan.service.RoleService;
import com.changan.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class AuthUserDetailsServiceImpl implements UserDetailsService {
@Resource
private RoleService roleService;
@Resource
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.loadUserByUsername(username);
if(user==null){
throw new UsernameNotFoundException(String.format("%s.这个用户不存在",username));
}else{
List<Role> roles = roleService.findRolesByUserId(user.getId());
user.setRoles(roles);
}
return user;
}
}
HelloController
package com.changan.controller;
import com.changan.utils.JsonResultUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public JsonResultUtil hello(){
return JsonResultUtil.success("成功访问公共接口", null);
}
@GetMapping("/db/hello")
public JsonResultUtil db(){
return JsonResultUtil.success("成功访问dba角色的接口", null);
}
@GetMapping("/admin/hello")
public JsonResultUtil admin(){
return JsonResultUtil.success("成功访问admin角色的接口", null);
}
@GetMapping("/user/hello")
public JsonResultUtil user(){
return JsonResultUtil.success("成功访问user角色的接口", null);
}
}
流程解析
当用户发起非登录请求时,首先会被JwtFilter截取请求进行token有效性校验,判断用户是否处于已登录状态;若已登录接下来被MyPermissionFilter截取请求,判断该请求需要用户具备哪些角色才可以访问,然后把需要的角色封装起来传递到请求访问管理类CustomAccessDecsionManager判断用户是否具有任意一个相应的角色,如果具有则此次访问是正常地访问,否则说明该访问是非法的,不允许访问,抛出异常。
接口测试
用户 | root | admin | sang |
---|---|---|---|
角色 | admin, db | admin | user |
可访问接口规则 | /admin/** ,/db/** | /admin/** | /user/** |