文章目录
Spring Security介绍
要对Web资源进行保护,最好的办法莫过于Filter
要想对方法调用进行保护,最好的办法莫过于AOP。
Spring Security进行认证和鉴权的时候,就是利用的一系列的Filter来进行拦截的。
如图所示,一个请求想要访问到API就会从左到右经过蓝线框里的过滤器,其中绿色部分是负责认证的过滤器,蓝色部分是负责异常处理,橙色部分则是负责授权。进过一系列拦截最终访问到我们的API。
这里面我们只需要重点关注两个过滤器即可:
UsernamePasswordAuthenticationFilter
负责登录认证,
FilterSecurityInterceptor
负责权限授权。
一般Web应用的需要进行认证和授权。
认证(Authentication)
:验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户
授权(Authorization)
:经过认证后判断当前用户是否有权限进行某个操作
而认证和授权就是SpringSecurity作为安全框架的核心功能。
说明:Spring Security的核心逻辑全在这一套过滤器中,过滤器里会调用各种组件完成功能,掌握了这些过滤器和组件你就掌握了Spring Security!这个框架的使用方式就是对这些过滤器和组件进行扩展。
Spring Security案例
1、快速搭建一个springboot工程
此步骤省略
建议整合knif4j方便调试
访问接口文档:http://localhost:8081/doc.html(端口为自己设置的端口,默认是8080)
springboot工程搭建完成
2、导入SpringSecurity整合springboot工程
- 导入SpringSecurity依赖(版本跟随boot版本)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
- 重新启动项目进行测试:访问路径:http://localhost:8081/ayo/hhy/1
这时我们可以看到当我们访问我们的接口的时候,就会自动跳转到一个SpringSecurity的默认登陆页面
(后期是需要整合到自己系统的登录页面来做认证)
这时候需要我们登录才可以进行访问,
我们可以看到控制台有一串字符串,其实那就是SpringSecurity初始化生成给我的密码
用户名
默认为 :
user
密码
在控制台打印出来了
输入用户和密码登录后,就可以正常访问接口了
3、认证
3.1、登录流程校验
核心是通过用户输入的用户名和密码去和数据库中的数据进行比对,如果比对无误
那么就会使用jwt工具根据用户名和密码去生成一个token传给前端存储起来
在登录过后用户想要访问别的资源都要在请求头里面携带token,后端会对前端请求的token拿到并且解析出来用户的id
根据用户的id获取相关的信息,来判断用户是否有访问资格,如果有,则访问目标资源返回给前端,若没有,则返回错误信息(无权限访问)
3.2、入门案例的原理
前后端进行认证的流程:
具体流程:
在上面的案例整合springSecurity,进入默认的登录页面进行登录的时候,是
查询内存中的用户名和密码
的,后期我们做项目肯定是要改成去数据库里面查询用户名和密码比对
其中:
- Authentication接口:它的实现类,表示当前访问系统的用户,封装了用户相关信息。
- AuthenticationManager接口:定义了认证Authentication的方法。
- UserDetailsService接口:加载用户特定数据的核心接口。里面定义了一个根据用户名查询用户信息的方法。
- UserDetails接口:提供核心用户信息。通过
UserDetailsService
根据用户名获取处理的用户信息要封装成UserDetails
对象返回。然后将这些信息封装到Authentication
对象中。
3.3、实现思路
登录流程:
- 登录认证成功之后根据用户名和密码通过
jwt生成一个token
返回给前端(前端每次请求都会携带token到请求里面),同时将token存入redis(其中用户id作为key,用户信息作为value)(主要是为了不让后续的校验流程频繁的查询数据库) - 这里的
UserDetailsService
默认是去查内存来认证用户名和密码的,需要自定义UserDetailsService
这个接口去查自己的数据库的数据进行认证 - 我们可以自定义一个UserDetailsService,让SpringSecurity使用我们的UserDetailsService。我们自己的UserDetailsService可以从数据库中查询用户名和密码。
校验流程:
获取token,解析token获取到其中的userId;
根据userId,从redis中获取用户信息,存入SecurityContextHolder。
- 前端每次发送请求的时候,请求头都会携带token。
- 后端从redis根据key去拿到token,并且通过jwt解析出用户的信息。
- 通过用户的信息查询用户可以使用的权限,然后返回给前端去访问能访问的资源
3.4、实现认证流程(自定义)
准备工作:
1. 引入依赖(jjwt、reids、fastjson,mysql,mybatis-plus)
<!--redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- fastjson2--><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.25</version></dependency><!--jjwt--><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
2. 添加相关配置
redis建议直接使用stringRedisTemplate,如果使用redisTemplate需要对数据进行序列化做相关的配置
参考链接:redisTemplate和stringRedisTemplate对比、redisTemplate几种序列化方式比较
因为是前后端分离,所以需要一统一结果返回类 R类(不唯一能用就行)
@DatapublicclassR<T>implementsSerializable{privateInteger code;//编码:1成功,0和其它数字为失败privateString msg;//错误信息privateT data;//数据privateMap map =newHashMap();//动态数据publicstatic<T>R<T>success(T object){R<T> r =newR<T>();
r.data = object;
r.code =1;return r;}publicstatic<T>R<T>success(String msg,T object){R<T> r =newR<T>();
r.data = object;
r.code =1;
r.msg = msg;return r;}publicstatic<T>R<T>error(String msg){R r =newR();
r.msg = msg;
r.code =0;return r;}publicstatic<T>R<T>success(String msg){R r =newR();
r.msg = msg;
r.code =1;return r;}publicR<T>add(String key,Object value){this.map.put(key, value);returnthis;}}
导入jwt工具类
/**
* JWT工具类
*/publicclassJwtUtil{//有效期为publicstaticfinalLongJWT_TTL=60*60*1000L;// 60 * 60 *1000 一个小时//设置秘钥明文publicstaticfinalStringJWT_KEY="qx";publicstaticStringgetUUID(){String token =UUID.randomUUID().toString().replaceAll("-","");return token;}/**
* 生成jtw jwt加密
* @param subject token中要存放的数据(json格式)
* @return
*/publicstaticStringcreateJWT(String subject){JwtBuilder builder =getJwtBuilder(subject,null,getUUID());// 设置过期时间return builder.compact();}/**
* 生成jtw jwt加密
* @param subject token中要存放的数据(json格式)
* @param ttlMillis token超时时间
* @return
*/publicstaticStringcreateJWT(String subject,Long ttlMillis){JwtBuilder builder =getJwtBuilder(subject, ttlMillis,getUUID());// 设置过期时间return builder.compact();}/**
* 创建token jwt加密
* @param id
* @param subject
* @param ttlMillis
* @return
*/publicstaticStringcreateJWT(String id,String subject,Long ttlMillis){JwtBuilder builder =getJwtBuilder(subject, ttlMillis, id);// 设置过期时间return builder.compact();}privatestaticJwtBuildergetJwtBuilder(String subject,Long ttlMillis,String uuid){SignatureAlgorithm signatureAlgorithm =SignatureAlgorithm.HS256;SecretKey secretKey =generalKey();long nowMillis =System.currentTimeMillis();Date now =newDate(nowMillis);if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;}long expMillis = nowMillis + ttlMillis;Date expDate =newDate(expMillis);returnJwts.builder().setId(uuid)//唯一的ID.setSubject(subject)// 主题 可以是JSON数据.setIssuer("sg")// 签发者.setIssuedAt(now)// 签发时间.signWith(signatureAlgorithm, secretKey)//使用HS256对称加密算法签名, 第二个参数为秘钥.setExpiration(expDate);}publicstaticvoidmain(String[] args)throwsException{//jwt加密String jwt =createJWT("123456");//jwt解密Claims claims =parseJWT(jwt);String subject = claims.getSubject();System.out.println(subject);System.out.println(jwt);}/**
* 生成加密后的秘钥 secretKey
* @return
*/publicstaticSecretKeygeneralKey(){byte[] encodedKey =Base64.getDecoder().decode(JwtUtil.JWT_KEY);SecretKey key =newSecretKeySpec(encodedKey,0, encodedKey.length,"AES");return key;}/**
* jwt解密
*
* @param jwt
* @return
* @throws Exception
*/publicstaticClaimsparseJWT(String jwt)throwsException{SecretKey secretKey =generalKey();returnJwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();}}
导入实体类
/**
* 用户表(User)实体类
*
*
*/@Data@AllArgsConstructor@NoArgsConstructor@TableName("sys_user")publicclassUserimplementsSerializable{privatestaticfinallong serialVersionUID =-40356785423868312L;/**
* 主键
*/@TableIdprivateLong id;/**
* 用户名
*/privateString userName;/**
* 昵称
*/privateString nickName;/**
* 密码
*/privateString password;/**
* 账号状态(0正常 1停用)
*/privateString status;/**
* 邮箱
*/privateString email;/**
* 手机号
*/privateString phonenumber;/**
* 用户性别(0男,1女,2未知)
*/privateString sex;/**
* 头像
*/privateString avatar;/**
* 用户类型(0管理员,1普通用户)
*/privateString userType;/**
* 创建人的用户id
*/privateLong createBy;/**
* 创建时间
*/privateDate createTime;/**
* 更新人
*/privateLong updateBy;/**
* 更新时间
*/privateDate updateTime;/**
* 删除标志(0代表未删除,1代表已删除)
*/privateInteger delFlag;}
数据库建表并且配置数据库
CREATETABLE `sys_user` (
`id` bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'主键',
`user_name` varchar(64)NOTNULLDEFAULT'NULL'COMMENT'用户名',
`nick_name` varchar(64)NOTNULLDEFAULT'NULL'COMMENT'昵称',
`password` varchar(64)NOTNULLDEFAULT'NULL'COMMENT'密码',
`status` char(1)DEFAULT'0'COMMENT '账号状态(0正常 1停用)',
`email` varchar(64)DEFAULTNULLCOMMENT'邮箱',
`phonenumber` varchar(32)DEFAULTNULLCOMMENT'手机号',
`sex` char(1)DEFAULTNULLCOMMENT '用户性别(0男,1女,2未知)',
`avatar` varchar(128)DEFAULTNULLCOMMENT'头像',
`user_type` char(1)NOTNULLDEFAULT'1'COMMENT '用户类型:1代表普通用户,0代表管理员',
`create_by` bigint(20)DEFAULTNULLCOMMENT '创建人的用户id',
`create_time` datetime DEFAULTNULLCOMMENT'创建时间',
`update_by` bigint(20)DEFAULTNULLCOMMENT'更新人',
`update_time` datetime DEFAULTNULLCOMMENT'更新时间',
`del_flag` int(11)DEFAULT'0'COMMENT '删除标志(0代表未删除,1代表已删除)',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=14787164048663DEFAULTCHARSET=utf8mb4 COMMENT='用户表';
datasource:
druid:
driver-class-name:com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/security?characterEncoding=utf-8&useSSL=false
username: root
password: root
定义mapper、service、serviceImpl并测试mapper能正常使用
省略(可以使用代码生成器)
3.5、正式实现
3.5.1 实现数据库的校验
- 创建一个类实现
UserDetailsService
接口,重写其中的(loadUserByUsername)
方法。增加用户名从数据库中查询用户信息 - 这里只是查了用户信息,对于用户权限还没有查(这部分是属于授权部分的内容),因为最后是把用户信息和权限信息封装成UserDetails进行返回的
@ServicepublicclassUserDetailsServiceImplimplementsUserDetailsService{@AutowiredprivateUserService userService;@OverridepublicUserDetailsloadUserByUsername(String username)throwsUsernameNotFoundException{//查询用户信息User user = userService.getOne(newLambdaUpdateWrapper<User>().eq(User::getUserName, username));//如果没有查询到用户就抛出异常if(Objects.isNull(user)){thrownewCustomException("用户名或密码错误");}//TODO 查询对应的权限信息//把数据封装成UserDetails返回returnnewLoginUser(user);}}
自定义一个实现UserDetails的(LoginUser)类,实现接口的方法;用来接收存储数据(用户信息和权限信息)
- 将用户属性注入进来,更改里面获取用户名和密码的get方法,使其获得user的信息
@Data@NoArgsConstructor@AllArgsConstructorpublicclassLoginUserimplementsUserDetails{privateUser user;//这里先不管权限信息这个集合@OverridepublicCollection<?extendsGrantedAuthority>getAuthorities(){returnnull;}//获取用户的用户的密码@OverridepublicStringgetPassword(){return user.getPassword();}@OverridepublicStringgetUsername(){return user.getUserName();}@OverridepublicbooleanisAccountNonExpired(){returntrue;}@OverridepublicbooleanisAccountNonLocked(){returntrue;}@OverridepublicbooleanisCredentialsNonExpired(){returntrue;}@OverridepublicbooleanisEnabled(){returntrue;}}
此次再次启动服务访问任意接口:(这个时候走的就是查我们自己的数据库了,可以在实现类里面打断点测试)
此时后端控制台就不会打印出在内存中的密码了,因为我们重写了UserDetailsService 接口的loadUserByUsername,程序走我们自己的方法。
注意:点击登录后,这里会出现一个问题
当输入正确的用户名和密码还是会显示密码错误
控制台打印的错误信息可以看出
- 因为我们数据库的密码是明文保存的,而PasswordEncoder方法其实是将数据库的加密的密码解密后再和用户输入的明文密码进行比对的
处理办法:在 Spring Security 中,{noop} 前缀告诉系统直接将密码存储为明文,即未经过哈希或其他加密算法处理。
再次登录测试:能够成功访问接口方法
3.5.2 密码加密存储
- 实际项目中我们不会把密码明文存储在数据库中。 默认使用的
PasswordEncoder
要求数据库中的密码格式为:{id}password
,它会根据id去判断密码的加密方式。但是我们一般不会采用这种方式,所以需要替换PasswordEncoder
。\ - 我们一般使用SpringSecurity为我们提供的
BCryptPasswordEncoder
。 - 我们只需要把
BCryptPasswordEncoder对象注入Spring容器
,SpringSecurity就会使用该PasswordEncoder
来进行密码校验。
**我们可以定义一个SpringSecurity的配置类,SpringSecurity要求这个配置类要
继承WebSecurityConfigurerAdapter
。**
@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//创建BCryptPasswordEncoder注入容器@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}}
相当于将原来的PasswordEncoder 中的方法覆盖掉,转而执行BCryptPasswordEncoder中的方法
其中BCryptPasswordEncoder对象中的三个方法分别作用是:
- encode : 用于对密码进行加密
- matches:用于判断给定的原始密码与已加密的密码是否匹配
- upgradeEncoding:用于升级密码的加密方式
这个时候数据库里面的用户密码必须是加密过的密码,这样在进行认证的时候,根据用户名查询到加密的密码,然后再根据passwordEncoder中的密码匹配方法来判断密码是否正确。(若数据库还是明文密码,那么肯定是会密码错误认证失败的)
咱可以先把数据库的明文密码加密放回原用户:(编写Test方法加密用户密码)
@TestpublicvoidtestPasswordEncoder(){BCryptPasswordEncoder passwordEncoder =newBCryptPasswordEncoder();String encode = passwordEncoder.encode("123456");System.out.println(encode);}
得到加密的密码填入数据库:
重启系统登录测试,登陆成功,正常访问接口
3.5.3 自定义登陆接口实现
其实质就是不让登录走整合SpringSecurity默认的登录页面了,而是走我们自己定义的登录接口
接下我们需要自定义登陆接口,然后让SpringSecurity对这个接口放行,让用户访问这个接口的时候不用登录也能访问
。
在接口中我们通过
AuthenticationManager
的
authenticate方法
来进行用户认证,所以需要
在SecurityConfig中配置把AuthenticationManager注入容器
。
认证成功的话要
生成一个jwt
,放入响应中返回。并且为了让
用户下回请求时能通过jwt识别出具体的是哪个用户
,我们需要把
用户信息存入redis
,可以把用户id作为key。
**创建
LoginController
登录接口**
- 其中LoginService 接口和实现接口类省略
@RestController@RequestMapping("/user")publicclassLoginController{@AutowiredprivateLoginService loginService;@PostMapping("/login")publicRlogin(@RequestBodyUser user){return loginService.login(user);}
那么我们可以在loginService实现类中编写login方法
其中验证是通过
通过AuthenticationManager的authenticate方法
来进行用户认证,需要在
SecurityConfig中配置把AuthenticationManager注入容器
并且进行一个
configure的配置
才能使用
·
SecurityConfig·
@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//创建BCryptPasswordEncoder注入容器@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}//把AuthenticationManager注入容器@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}}@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
http
//关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();}
这个时候就可以编写登录接口了
- 通过
UsernamePasswordAuthenticationToken
获取用户名和密码 2.AuthenticationManager
委托机制对authenticationToken
进行用户认证 - 如果认证没有通过,给出对应的提示
- 如果认证通过,使用user生成jwt , jwt存入R返回
- 如果认证通过,拿到这个当前登录用户信息
- 把完整的用户信息存入redis
userid为key``````用户信息为value
此时只有用户信息,还没有包括权限信息,后续授权会完善
@ServicepublicclassLoginServiceImplimplementsLoginService{@AutowiredprivateUserService userService;//认证委托@AutowiredprivateAuthenticationManager authenticationManager;@AutowiredprivateStringRedisTemplate redisTemplate;@OverridepublicRlogin(User user){//通过UsernamePasswordAuthenticationToken获取用户名和密码UsernamePasswordAuthenticationToken authenticationToken=newUsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());//AuthenticationManager委托机制对authenticationToken 进行用户认证Authentication authenticate = authenticationManager.authenticate(authenticationToken);//如果认证没有通过,给出对应的提示if(Objects.isNull(authenticate)){thrownewRuntimeException("登录失败");}//如果认证通过,使用user生成jwt jwt存入R 返回//如果认证通过,拿到这个当前登录用户信息LoginUser loginUser =(LoginUser) authenticate.getPrincipal();//获取当前用户的useridString userid = loginUser.getUser().getId().toString();String jwt =JwtUtil.createJWT(userid);Map<String,String> map =newHashMap<>();
map.put("token",jwt);//把完整的用户信息存入redis userid为key 用户信息为value 将对象转换为 JSON 字符串 存入redisString jsonString =JSONUtil.toJsonStr(loginUser);
redisTemplate.opsForValue().set("login"+userid, jsonString );returnR.success("登陆成功",map);}}
重启服务进行登录测试(建议打断点一步步测试数据)
这里我们用postman进行登录测试
user/login被放行,可以不用登录认证直接访问
输入url:localhost:8081/user/login
通过json传输用户信息
结果返回:
并且查看reids
此时认证成功~
3.5.4 自定义实现认证过滤器
我们需要自定义一个过滤器,这个
过滤器会去获取请求头中的token
,对token进行解析取出其中的
userid
。
使用userid去redis中获取对应的
LoginUser对象
。然后封装
Authentication
对象存入
SecurityContextHolder
**定义过滤类:
JwtAuthenticationTokenFilter
**
流程:
- 过滤器拦截到请求,并且从请求头中拿到token
- 根据拿到的token根据jwt工具类解析得到用户的ID(userId)
- 根据userId(也就是之前reids存token的key)去redis拿到用户信息
- 若用户信息不为null,代表该用户没有登录过,抛异常
- 若能拿到用户信息封装Authentication对象存入
SecurityContextHolder
并且获取权限信息封装到Authentication中
(这里属于授权过程,暂不实现) - 放行
封装Authentication对象:包括两部分
- 用户信息
- 用户权限信息
@ComponentpublicclassJwtAuthenticationTokenFilterextendsOncePerRequestFilter{@AutowiredprivateStringRedisTemplate redisTemplate;@OverrideprotectedvoiddoFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain)throwsServletException,IOException{//从前端发起请求的请求头获取tokenString token = request.getHeader("token");if(!StringUtils.hasText(token)){//放行
filterChain.doFilter(request, response);return;}//解析tokenString userid;try{Claims claims =JwtUtil.parseJWT(token);
userid = claims.getSubject();}catch(Exception e){
e.printStackTrace();thrownewCustomException("token非法");}//从redis中获取用户信息String redisKey ="login:"+ userid;//将json转换为对象类String json = redisTemplate.opsForValue().get(redisKey);LoginUser loginUser =JSONUtil.toBean(json,LoginUser.class);if(Objects.isNull(loginUser)){thrownewRuntimeException("用户未登录");}//封装Authentication对象存入SecurityContextHolder//TODO 获取权限信息封装到Authentication中UsernamePasswordAuthenticationToken authenticationToken =newUsernamePasswordAuthenticationToken(loginUser,null,null);SecurityContextHolder.getContext().setAuthentication(authenticationToken);//放行
filterChain.doFilter(request, response);}}
**把token校验过滤器添加到过滤器链中(注入到配置类(
SecurityConfig
)加入过滤器链)**
//把token校验过滤器注入配置类@AutowiredJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;//把token校验过滤器添加到过滤器链中并且添加到UsernamePasswordAuthenticationFilter之前
http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);
@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//创建BCryptPasswordEncoder注入容器@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}//把AuthenticationManager注入容器@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}//把token校验过滤器注入配置类@AutowiredJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
http
//关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();//把token校验过滤器添加到过滤器链中
http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);}}
测试:
- 编写一个接口来判断登录过后是否可以拿到token并且解析出用户信息
测试1:不登录直接访问:访问路径localhost:8081/ayo/coo
断点调试
JwtAuthenticationTokenFilter
:
- 此时过滤器拦截到请求,发现请求头里面没有token(代表用户没有登录),直接放行retrun 认证失败
测试2:登录后设置请求头(登录生成的token)再次访问 :访问路径localhost:8081/ayo/coo
记录登录成功的token值
在访问路径localhost:8081/ayo/coo时,在请求头加上登录过后生成的token
此时断点调试
JwtAuthenticationTokenFilter
:成功从请求头拿到token
然后根据token解析到用户的id(userId),根据userId从redis取出用户的信息,然后将用户的信息(和权限信息)
封装成Authentication对象
存入
SecurityContextHolder
- SecurityContextHolder
SecurityContextHolder 类提供了一种方便的方式来获取当前用户的安全信息,如身份验证信息和角色信息。它是一个线程本地的存储,可以在应用程序的不同层级中访问
返回此次调用接口的数据:
3.5.5 退出登录
流程:
- 执行退出登录的请求时,请求头携带token
- 进入
doFilterInternal
过滤器,解析token,得到用户userId - 根据userId从redis中拿到用户信息,并且将用户信息封装成
Authentication
对象,并且存入SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
- 执行controller的方法—>service中的logout方法
- 从
SecurityContextHolder中获取用户的userid
- 根据
userid找到redis对应值进行删除
controller层
@GetMapping("/logout")publicRlogin(){return loginService.logout();}
service实现类:
/**
* 注销接口
* @return
*/@OverridepublicRlogout(){//从SecurityContextHolder中的useridUsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();LoginUser loginUser =(LoginUser) authentication.getPrincipal();Long userid = loginUser.getUser().getId();//根据userid找到redis对应值进行删除
redisTemplate.delete("login:"+userid);returnR.success("注销成功");}
其中的核心是通过过滤器将用户的
userId
放入
SecurityContextHolder
中中了,在注销登录的时候可以直接拿到userId再去
删除redis中的token信息
注意:这个时候再去访问其他接口的时候,发送过来的请求的请求头所携带的
还是之前的登录时的token
,这个时候进入过滤器的时候可以根据
token获得用户的userId
,但是在根据userId去redis获得用户信息的时候是获取不到的(
注销的时候已经删除该用户对应的信息
),抛出未登录异常.
控制台报错:
4、授权
权限系统的作用:让不同的用户可以使用不同的功能。
实现
:不能只依赖前端去判断用户的权限来选择显示哪些菜单哪些按钮。因为
让前端判断权限,别人可以根据对应功能的接口地址,直接发送请求来实现相关的操作
。
所以,我们还需要在后台进行用户权限的判断,判断当前用户是否有响应的权限,必须具有所需权限才能进行相应的操作。
4.1 授权基本流程
在
SpringSecurity
中,会使用默认的
FilterSecurityInterceptor
来进行权限校验。在
FilterSecurityInterceptor
中,会从
SecurityContextHolder
获取其中的
Authentication
,然后获取其中的权限信息。当前用户是否拥有访问当前资源所需的权限。
所以我们在项目中需要把当前登录用户的权限信息也存入Authentication
,然后设置我们的资源所需要的权限即可。
4.2 授权实现(不结合数据库)
4.2.1 限制访问资源所需权限
SpringSecurity为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的方式,我们可以
使用注解去指定访问对应的资源所需的权限
。
使用前先在SpringSecurity配置类上开启相关配置
@EnableGlobalMethodSecurity(prePostEnabled =true)
这样就代表开启了使用注解去指定访问权限的功能,例如:
@ApiOperation(value ="权限测试接口")@PreAuthorize("hasAuthority('tset')")@GetMapping("/auth")publicRauth(){returnR.success("权限测试接口访问成功");}
@PreAuthorize(“hasAuthority(‘tset’)”) 的含义是
只有具有 "tset" 权限的用户才能够调用被注解的方法
。
hasAuthority() 是 Spring Security 提供的一个表达式,用于检查用户是否具有指定的权限
。在这种情况下,只有
当用户拥有 "tset" 权限(权限名称为 "tset")时
,才能访问被注解的方法。
4.2.2 封装权限信息
封装权限信息的步骤
- 首先在用户进行认证登录成功之后就会在
UserDetailsService
接口的实现类方法loadUserByUsername
去获得用户信息和权限信息
,把数据封装成UserDetails返回。
这里的权限信息集合我们先写死成
“test”
(后续是从数据库根据用户查出来的权限信息集合)
此时LoginUser需要封装user和AuthList两个对象
,所以需要
改造登录封装类LoginUser
改造登录封装类LoginUser
- 就是将登录认证后查到的权限集合,封装到LoginUser,默认框架是不会去调用我们自己定义的权限集合的,需要将自己传入的权限集合通过getAuthorities()方法封装成一个属性为
SimpleGrantedAuthority
的权限集合,供框架做权限控制。
小细节:因为将数据存到redis是会序列化的,但是SimpleGrantedAuthority序列化会报错,所以,存入权限信息的时候存入
permissions
就可以了(string类型)
使用注解@JSONField(serialize = false)
让其不序列化
- 然后再过滤器中,根据每次请求携带的token(进行登录的时候,所有的用户信息和权限信息都在redis中),解析用户id,然后根据用户id去redis查询用户信息和权限信息,
将权限信息和用户信息封装到Authentication中
。
断点测试:
- 在进行登录的时候通过委托认证中的
loadUserByUsername
方法将权限信息和用户信息封装成LoginUser对象。 - 在登录验证通过后,会将完整的信息存入redis中
reids数据如下:
这里为什么redis显示
authorities
没有数据呢,其实数据已经存进去了,只是在属性上加上了注解
@JSONField(serialize = false)
使其不序列化展示出来,数据还是有的
访问带权限的接口时:
- 过滤器会根据解析token的用户id去redis查询用户的所有信息,
封装到Authentication
对象交给框架去做方法授权,其中里面包括了权限信息(这里举例:test)
能够成功访问:
同理:如果这个controller设置的权限,通过不了框架的授权验证,肯定是不能访问的,会报错。
、、、、、、、、更新中
4.3 授权实现(结合数据库)
因为之前实现授权,是将权限集合写死了,我们通常在项目中,权限应该是从数据库根据用户对应的角色中查出来的,如下图:
RBAC权限模型:也就是上图
RBAC权限模型(Role-Based Access Control)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用的权限模型。
4.3.1 设计数据库表
需要设置角色表、权限表,以及用户角色关联表,角色权限关联表
CREATETABLE `sys_user` (
`id` bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'主键',
`user_name` varchar(64)NOTNULLDEFAULT'NULL'COMMENT'用户名',
`nick_name` varchar(64)NOTNULLDEFAULT'NULL'COMMENT'昵称',
`password` varchar(64)NOTNULLDEFAULT'NULL'COMMENT'密码',
`status` char(1)DEFAULT'0'COMMENT '账号状态(0正常 1停用)',
`email` varchar(64)DEFAULTNULLCOMMENT'邮箱',
`phonenumber` varchar(32)DEFAULTNULLCOMMENT'手机号',
`sex` char(1)DEFAULTNULLCOMMENT '用户性别(0男,1女,2未知)',
`avatar` varchar(128)DEFAULTNULLCOMMENT'头像',
`user_type` char(1)NOTNULLDEFAULT'1'COMMENT '用户类型:1代表普通用户,0代表管理员',
`create_by` bigint(20)DEFAULTNULLCOMMENT '创建人的用户id',
`create_time` datetime DEFAULTNULLCOMMENT'创建时间',
`update_by` bigint(20)DEFAULTNULLCOMMENT'更新人',
`update_time` datetime DEFAULTNULLCOMMENT'更新时间',
`del_flag` int(11)DEFAULT'0'COMMENT '删除标志(0代表未删除,1代表已删除)',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=14787164048663DEFAULTCHARSET=utf8mb4 COMMENT='用户表';CREATETABLE `sys_menu` (
`id` bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'菜单ID',
`menu_name` varchar(50)NOTNULLCOMMENT'菜单名称',
`path` varchar(200)DEFAULT '' COMMENT'路由地址',
`component` varchar(255)DEFAULTNULLCOMMENT'组件路径',
`visible` char(1)DEFAULT'0'COMMENT '菜单状态(0显示 1隐藏)',
`status` char(1)DEFAULT'0'COMMENT '菜单状态(0正常 1停用)',
`perms` varchar(100)DEFAULTNULLCOMMENT'权限标识',
`icon` varchar(100)DEFAULT'#'COMMENT'菜单图标',
`create_by` bigint(20)DEFAULTNULLCOMMENT'创建者',
`create_time` datetime DEFAULTNULLCOMMENT'创建时间',
`update_by` bigint(20)DEFAULTNULLCOMMENT'更新者',
`update_time` datetime DEFAULTNULLCOMMENT'更新时间',
`remark` varchar(500)DEFAULT '' COMMENT'备注',
`del_flag` int(11)DEFAULT'0',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=2029DEFAULTCHARSET=utf8mb4 COMMENT='菜单权限表';CREATETABLE `sys_role` (
`id` bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'角色ID',
`name` varchar(128)DEFAULTNULLCOMMENT'角色名称',
`role_key` varchar(100)DEFAULTNULLCOMMENT '角色权限字符串',
`status` char(1)NOTNULLCOMMENT '角色状态(0正常 1停用)',
`del_flag` int(1)DEFAULT'0'COMMENT '删除标志(0代表存在 1代表删除)',
`create_by` bigint(20)DEFAULTNULLCOMMENT'创建者',
`create_time` datetime DEFAULTNULLCOMMENT'创建时间',
`update_by` bigint(20)DEFAULTNULLCOMMENT'更新者',
`update_time` datetime DEFAULTNULLCOMMENT'更新时间',
`remark` varchar(500)DEFAULTNULLCOMMENT'备注',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8mb4 COMMENT='角色信息表';CREATETABLE `sys_role_menu` (
`role_id` bigint(200)NOTNULLAUTO_INCREMENTCOMMENT'角色ID',
`menu_id` bigint(200)NOTNULLDEFAULT'0'COMMENT'菜单ID',PRIMARYKEY(`role_id`,`menu_id`))ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8mb4 COMMENT='角色和菜单关联表';CREATETABLE `sys_user_role` (
`user_id` bigint(200)NOTNULLAUTO_INCREMENTCOMMENT'用户ID',
`role_id` bigint(200)NOTNULLDEFAULT'0'COMMENT'角色ID',PRIMARYKEY(`user_id`,`role_id`))ENGINE=InnoDBDEFAULTCHARSET=utf8mb4 COMMENT='用户和角色关联表';
导入菜单实体类:
/**
* 菜单表(Menu)实体类
*
*/@TableName(value="sys_menu")@Data@AllArgsConstructor@NoArgsConstructor@JsonInclude(JsonInclude.Include.NON_NULL)publicclassMenuimplementsSerializable{privatestaticfinallong serialVersionUID =-54979041104113736L;@TableIdprivateLong id;/**
* 菜单名
*/privateString menuName;/**
* 路由地址
*/privateString path;/**
* 组件路径
*/privateString component;/**
* 菜单状态(0显示 1隐藏)
*/privateString visible;/**
* 菜单状态(0正常 1停用)
*/privateString status;/**
* 权限标识
*/privateString perms;/**
* 菜单图标
*/privateString icon;privateLong createBy;privateDate createTime;privateLong updateBy;privateDate updateTime;/**
* 是否删除(0未删除 1已删除)
*/privateInteger delFlag;/**
* 备注
*/privateString remark;}
因为需要查询菜单表,所以需要定义菜单表的mapper接口分别增删查改。
@Mapper@RepositorypublicinterfaceMenuMapperextendsBaseMapper<Menu>{}
之后需要使用mapper的xml来实现多表查询
在resource下建包:
在mapper接口使用快捷方式(alt+enter)生成选择mapper文件夹的位置创建xml映射文件
在application.yml中配置mapperXML文件的位置
# 配置mapperXML文件的位置
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml
4.3.2 代码实现
我们只需要根据用户id,通过多表联查,去查询到其所对应的权限信息即可。
这里就需要使用mapper的xml来实现多表查询,
- 在menu的mapper里面定义根据用户id去查询权限的方法
@Mapper@RepositorypublicinterfaceMenuMapperextendsBaseMapper<Menu>{List<String>selectPermsByUserId(Long userid);}
- 在xml文件里面编写查询权限的sql
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hhy.springboot_demo.mapper.MenuMapper"><select id="selectPermsByUserId" resultType="java.lang.String">
select
DISTINCT m.`perms`
FROM
sys_user_role ur
LEFTJOIN `sys_role` r ON ur.`role_id` = r.`id`
LEFTJOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
LEFTJOIN `sys_menu` m ON m.`id` = rm.`menu_id`
WHERE
user_id = #{userId}AND r.`status` =0//保证角色是正常状态才查询AND m.`status` =0//保证菜单是正常状态才查询</select></mapper>
- UserDetailsServiceImpl的登录认证方法中去调用该mapper的方法查询权限信息封装到LoginUser对象中即可(也就是替换之前写死的List集合)。
- 对方法权限根据数据库设置的权限改动,然后进行测试
数据库表对应说明:
接口方法权限设置
4.3.3 测试
- 测试用户:
libai
- 该用户对应拥有
权限测试1
和权限测试2
的访问权限成功访问:满足预期效果、
- 测试用户:
test
- 该用户对应只拥有
权限测试2
的访问权限
成功访问:满足预期结果
5、自定义访问失败处理
我们希望在认证失败或者是授权失败的情况下,也能和我们的接口一样返回相同结构的json,这样可以让前端对响应进行统一的处理。要实现这个功能我们需要知道
SpringSecurity的异常处理机制
。
- 在SpringSecurity中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。在
ExceptionTranslationFilter
中会去判断是认证失败还是授权失败出现的异常。 如果是认证过程中出现的异常
会被封装成AuthenticationException,然后调用AuthenticationEntryPoint对象的方法进行异常处理。如果是授权过程中出现的异常,
会被封装成AccessDeniedException,然后调用AccessDeniedHandler对象的方法进行异常处理。- 所以,如果我们需要自定义异常处理,我们只需要
自定义AuthenticationEntryPoint和AccessDeniedHandler,然后配置给SpringSecurity即可
。
5.1、自定义实现类
AuthenticationEntryPointImpl
/**
* 处理认证异常
*/@ComponentpublicclassAuthenticationEntryPointImplimplementsAuthenticationEntryPoint{@Overridepublicvoidcommence(HttpServletRequest request,HttpServletResponse response,AuthenticationException authException)throwsIOException,ServletException{R<Object> result =R.AuthenticationEntryPointImpl("用户名认证失败请重新登录",HttpStatus.UNAUTHORIZED.value());String json =JSON.toJSONString(result);//处理移除WebUtils.renderString(response,json);}}
AccessDeniedHandlerImpl
/**
* @Desc : 授权的异常处理
*/@ComponentpublicclassAccessDeniedHandlerImplimplementsAccessDeniedHandler{@Overridepublicvoidhandle(HttpServletRequest request,HttpServletResponse response,AccessDeniedException accessDeniedException)throwsIOException,ServletException{R<Object> result =R.AuthenticationEntryPointImpl("您的权限不足",HttpStatus.FORBIDDEN.value());String json =JSON.toJSONString(result);//处理移除WebUtils.renderString(response,json);}}
其中
WebUtils.renderString
publicclassWebUtils{/**
* 在 HttpServletResponse 中渲染字符串的方法。
* 它将给定的字符串写入 HttpServletResponse 的输出流,
* 并设置相应的响应状态码、内容类型和字符编码。
*/publicstaticStringrenderString(HttpServletResponse response,String string){try{
response.getWriter().print(string);
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");}catch(IOException e){
e.printStackTrace();}returnnull;}}
5.2、配置给SpringSecurity
@AutowiredprivateAuthenticationEntryPoint authenticationEntryPoint;@AutowiredprivateAccessDeniedHandler accessDeniedHandler;//配置异常处理器
http.exceptionHandling()//认证失败处理器.authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler);
测试------未改造之前会出现的问题:
在用户名出错的时候会抛出异常,是因为在执行
loadUserByUsername
方法时查询用户查询不到
但是如果用户名没错,密码错了就不会抛出异常:
因为在
loadUserByUsername
方法执行完成是可以找到用户的,获取用户的全部信息,所以在做密码验证的时候,方法内部验证密码的时候报错了。
改造自定义异常处理之后:
- 密码错误(这里走的是用户名无误,在查密码时,)下面的委托机制抛出的异常
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
- 用户名错误(这里走的是在查不到用户的时候自定义的异常)
- 权限不足–改造之后:
没改造之前,异常信息也是拿不到的
改造之后,走授权异常处理器
6、跨域问题
- 浏览器出于安全的考虑,使用 XMLHttpRequest对象发起 HTTP请求时必须遵守同源策略,否则就是跨域的HTTP请求,默认情况下是被禁止的。 同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。
- 前后端分离项目,前端项目和后端项目一般都不是同源的,所以肯定会存在跨域请求的问题。
所以我们就要处理一下,让前端能进行跨域请求。
SpringBoot配置,运行跨域请求
CorsConfig
@ConfigurationpublicclassCorsConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddCorsMappings(CorsRegistry registry){// 设置允许跨域的路径
registry.addMapping("/**")// 设置允许跨域请求的域名.allowedOriginPatterns("*")// 是否允许cookie.allowCredentials(true)// 设置允许的请求方式.allowedMethods("GET","POST","DELETE","PUT")// 设置允许的header属性.allowedHeaders("*")// 跨域允许时间.maxAge(3600);}}
在SecurityConfig的配置类中开启开启SpringSecurity的跨域访问
由于我们的资源都会收到SpringSecurity的保护,所以想要跨域访问还要让SpringSecurity运行跨域访问。
//允许跨域
http.cors();
7、扩展
7.1、自定义权限校验方法
- 我们也可以定义自己的权限校验方法,在@PreAuthorize注解中使用我们的方法。
@Component("ex")publicclassQXExpressionRoot{//String authority 这里是后端赋给它的权限//从数据库获取登录用户的权限功能 和authority 进行对比publicbooleanhasAuthority(String authority){//获取当前用户得权限Authentication authentication =SecurityContextHolder.getContext().getAuthentication();LoginUser loginUser =(LoginUser) authentication.getPrincipal();List<String> permissions = loginUser.getPermissions();//判断用户权限集合中是否存在 authorityreturn permissions.contains(authority);}
- 在SPEL表达式中使用 @ex相当于获取容器中bean的名字为ex的对象。然后再调用这个对象的hasAuthority方法
@RequestMapping("hello")//自定义的权限功能@PreAuthorize("@ex.hasAuthority('system:dept:list')")publicStringhello(){return"hello";}
7.2、基于配置的权限控制
- 在配置类中配置
8、 demo源码
SpringBoot整合Spring Security实现权限控制----------gitee
9、特别鸣谢
作者:不易撞的网名
作者:北莽
版权归原作者 今天你写代码了吗?? 所有, 如有侵权,请联系我们删除。