项目前台跟后台的认证和授权都是依靠的SpringSecurity。
思路分析:


登录:
①自定义一个类实现UserDetailsService
改为查询数据库,将查询到的用户信息以及权限信息封装到一个UserDatails对象(自定义一个类实现UserDetails,后面做授权的时候还需要返回用户权限信息)中。
配置passwordEncoder密码校验为BCrptPasswordEncoder
②自定义登录接口
调用ProviderManger的方法验证用户名跟密码是否正确(项目中使用它的实现类AuthenticationManager,需要在配置类继承WebSecurityConfigurerAdapter来完成注入)
验证通过的话获取userid生成token
将userid作为key,用户信息作为value存储到redis中
响应给用户一个token。
校验:
①自定义Jwt认证过滤器
获取token
解析token获取userid
根据userid去redis中查询对应用户信息
存入SecurityContextHolder
②将自定义的Jwt认证过滤器添加到过滤器链中
前台系统暂无需求,后面设计后台管理系统时再考虑授权
分别实现:
AuthenticationEntryPoint 认证失败处理器
AccessDeniedHandler 授权失败处理器
然后在Securityconfig中配置异常处理器
获取SecurityContext中的认证信息,然后删除redis中对应的数据即可
- @Override
- public ResponseResult logout() {
- //获取token 解析获取userid
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- LoginUser loginUser = (LoginUser) authentication.getPrincipal();
- //获取userid
- Long userId = loginUser.getUser().getId();
- //删除redis中的用户信息
- redisCache.deleteObject("bloglogin:"+userId);
- return ResponseResult.okResult();
- }
在Securityconfig中配置:
关闭Security自身的退出接口
注销接口需要认证才能访问
- http.logout().disable();
- //注销接口需要认证才能访问
- http.antMatchers("/logout").authenticated()