当前位置: 首页 > news >正文

SpringSecurity学习

b1ccdd01dd564e608c6a1334b977b52a.png

1.认证

密码校验用户

847c2bc6bc9541e5875dbd76be1ddcc9.png

密码加密存储

3323a83e8b4642fc8c25e5187e68600d.png

 

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}}
  • 我们没有这个配置,默认明文存储, {id}password;
  • 实现这个,就变成加密存储: 加盐值 + 明文随机生成一段密文
  • 将返回UserDetails对象中的密码,与输入的密码进行校验

登录接口

57032ebc36f34a6187075a9d90f763d0.png

  • 在SpringSecurity放行登录接口,
  • 定义AuthenticationManager @bean 
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http//关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}}

PS:就我们研究框架, 有些值,需要我们利用断点调试,层层拨开来进行获取。

1e66f583198b4f028d91960aa702163e.png

 

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate RedisCache redisCache;@Overridepublic ResponseResult login(UserDTO userDTO) {//  AuthenticationManager authenticationManager 进行认证UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDTO.getUsername(), userDTO.getPassword());Authentication authenticate = authenticationManager.authenticate(authenticationToken);// 如果认证通过、给出对应提示if(Objects.isNull(authenticate)){throw new RuntimeException("登录失败");}// 认证通过使用userid生成jwtLoginUser loginUser = (LoginUser) authenticate.getPrincipal();String userId = loginUser.getUser().getId().toString();String token = JwtUtil.createJWT(userId);HashMap<String, String> map = new HashMap<>();map.put("token",token);// 把完整用户信息存入redisredisCache.setCacheObject("login:"+userId,loginUser);return new ResponseResult(200,"登录成功",map);}
}

认证过滤器

1011c8d13f8d4292bca160578402202d.png

我觉得下面配置,是配合前端适用的;

  • 登录、请求等..页面,前端路由拦截器之类不需要拦截(没有token),那么页面相关请求,jwt过滤器是不需要拦截的。
  • 首页等页面,需要token,那么必须是登录之后,拥有token,才能访问吧?访问页面,会携带token发送请求,访问资源。
@Component
public class JwtFilter extends OncePerRequestFilter {@Autowiredprivate RedisCache redisCache;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {//获取tokenString token = request.getHeader("Authorization").substring(6);if(StringUtils.isEmpty(token)){filterChain.doFilter(request,response);return;}//解析tokenString userid;try {Claims claims = JwtUtil.parseJWT(token);userid = claims.getSubject();} catch (Exception e) {e.printStackTrace();throw new RuntimeException("token非法");}//从redis中获取用户信息String redisKey = "login:" + userid;LoginUser loginUser = redisCache.getCacheObject(redisKey);if(Objects.isNull(loginUser)){throw new RuntimeException("用户未登录");}//存入SecurityContextHolder//TODO 获取权限信息封装到Authentication中UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());SecurityContextHolder.getContext().setAuthentication(authenticationToken);//放行filterChain.doFilter(request, response);}
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtFilter jwtAuthenticationTokenFilter;@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http//关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();//把token校验过滤器添加到过滤器链中,就是在 UsernamePasswordAuthenticationFilter之前http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}}

 

 

http://www.lryc.cn/news/161489.html

相关文章:

  • 时序预测 | MATLAB实现ICEEMDAN-iMPA-BiLSTM时间序列预测
  • 二叉树(上)
  • Excel怎么批量生成文件夹
  • c++ 学习之 静态成员变量和静态成员函数
  • C程序需要按下回车键才能读取字符
  • x86体系结构(WinDbg学习笔记)
  • Hadoop的第二个核心组件:MapReduce框架第四节
  • 算法通关村第十九关——最少硬币数
  • Linux ifconfig只显示 lo 网卡,没有ens网卡解决方案
  • Java复习-26-枚举
  • NLP(六十八)使用Optimum进行模型量化
  • Tomcat多实例和负载均衡动静分离
  • 企业ERP和泛微OA集成场景分析
  • 31 WEB漏洞-文件操作之文件包含漏洞全解
  • qmake.exe xxx.pro -spec win32-g++ 作用
  • SpringMVC实现增删改查
  • React 配置别名 @ ( js/ts 项目中通过 webpack.config.js 配置)
  • Android 在TextView前面添加多个任意View且不影响换行
  • 字符串相加
  • uni-app直播从0到1实战
  • Python UI自动化 —— pytest常用运行参数解析、pytest执行顺序解析
  • LeetCode刷题笔记【25】:贪心算法专题-3(K次取反后最大化的数组和、加油站、分发糖果)
  • java基础面试题 第四天
  • postgresql-常用日期函数
  • 【业务场景】用户连点
  • zabbix企业微信告警
  • (高频面试1)Redis缓存穿透、缓存击穿、缓存雪崩
  • c++推箱子小游戏
  • SpringMVC:从入门到精通
  • jmeter 数据库连接配置 JDBC Connection Configuration