当前位置:   article > 正文

SpringBoot3.0 + SpringSecurity 分离版_springboot3.0securityfilterchain

springboot3.0securityfilterchain

1.序 

SpringBoot2.6 + SpringSecurity 分离版_securityconfig配置_一枚小蜗牛H的博客-CSDN博客

参考2.6,升级SpingBoot3.0 相对于SpringSecurity也升级到了6.0相对应配置变化。

由于升级到3.0,jdk也必须是17+。首先没有了javax包,需要的都需要改,jwt也是一样。swagger配置的也不生效了,3.0只支持openapi3,knife4j包要升级到4.0,具体看knife4j官网。

2.Security配置类修改

请看代码对比修改

  1. package com.cn.config.security;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.http.HttpMethod;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
  8. import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
  9. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  10. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  11. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  12. import org.springframework.security.web.SecurityFilterChain;
  13. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  14. import org.springframework.web.cors.CorsConfiguration;
  15. import org.springframework.web.cors.CorsConfigurationSource;
  16. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  17. import java.util.Collections;
  18. /**
  19. * @program: demo
  20. * @Description 配置
  21. * @Date 2023/3/8
  22. */
  23. @Configuration
  24. @EnableWebSecurity
  25. @EnableMethodSecurity//开启注解权限配置
  26. public class SecurityConfig {
  27. /**
  28. * 自定义授权拦截器
  29. */
  30. @Autowired
  31. private MyLoginJwtFilter myLoginJwtFilter;
  32. /**
  33. * 自定义UserDetailsService实现
  34. */
  35. @Autowired
  36. private MyUserDetailService myUserDetailService;
  37. /**
  38. * 认证失败
  39. */
  40. @Autowired
  41. private MyAuthenticationEntryPoint myAuthenticationEntryPoint;
  42. /**
  43. * 授权失败
  44. */
  45. @Autowired
  46. private MyAccessDeniedHandler myAccessDeniedHandler;
  47. /**
  48. * 注销成功
  49. */
  50. @Autowired
  51. private MyLogoutSuccessHandler myLogoutSuccessHandler;
  52. /**
  53. * 强散列哈希加密实现 没有这个会报错 There is no PasswordEncoder mapped for the id “null“
  54. */
  55. @Bean
  56. public BCryptPasswordEncoder newBCryptPasswordEncoder() {
  57. return new BCryptPasswordEncoder();
  58. }
  59. //暴露出来 解决无法直接注入 AuthenticationManager
  60. @Bean
  61. public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
  62. return authenticationConfiguration.getAuthenticationManager();
  63. }
  64. /**
  65. * 配置类
  66. *
  67. * @param httpSecurity HttpSecurity
  68. * @throws Exception Exception
  69. */
  70. @Bean
  71. SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
  72. httpSecurity
  73. //过滤请求
  74. .authorizeHttpRequests()
  75. //对于登录login 注册register 验证码captchaImage 放开
  76. .requestMatchers("/login/**").permitAll()
  77. //测试功能 放开
  78. .requestMatchers("/test/**").permitAll()
  79. //静态资源 放开
  80. .requestMatchers(HttpMethod.GET, "/", "/*.html", "/*.css", "/*.js", "/*/*.html", "/*/*.css", "/*/*.js", "/*/api-docs/**","/webjars/**","/*.ioc").permitAll()
  81. .anyRequest()
  82. //所有请求都必须认证
  83. .authenticated()
  84. .and()
  85. .formLogin()
  86. .and()
  87. .exceptionHandling()
  88. //没登录提示信息
  89. .authenticationEntryPoint(myAuthenticationEntryPoint)
  90. //授权失败
  91. .accessDeniedHandler(myAccessDeniedHandler)
  92. //退出登录提示信息
  93. .and().logout().logoutUrl("/logout")
  94. .logoutSuccessHandler(myLogoutSuccessHandler)
  95. //跨域处理方案
  96. .and().cors().configurationSource(configurationSource())
  97. //关闭csrf
  98. .and().csrf().disable()
  99. ;
  100. //替换自带的filter
  101. //at: 用来某个 filter 替换过滤器链中哪个 filter
  102. //before: 放在过滤器链中哪个 filter 之前
  103. //after: 放在过滤器链中那个 filter 之后
  104. httpSecurity.addFilterBefore(myLoginJwtFilter, UsernamePasswordAuthenticationFilter.class);
  105. return httpSecurity.build();
  106. }
  107. /**
  108. * 跨域解决方案
  109. *
  110. * @return CorsConfigurationSource
  111. */
  112. CorsConfigurationSource configurationSource() {
  113. CorsConfiguration corsConfiguration = new CorsConfiguration();
  114. corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
  115. corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
  116. corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
  117. corsConfiguration.setMaxAge(3600L);
  118. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  119. source.registerCorsConfiguration("/**", corsConfiguration);
  120. return source;
  121. }
  122. }

 2.1.不需要继承了,配置类注释

 2.2.校验类换成HttpSecurity

 2.3.过滤链过期修改与更新

 3.自定义拦截器

  1. package com.cn.config.security;
  2. import com.cn.common.Constants;
  3. import com.cn.utils.JwtUtil;
  4. import com.cn.utils.RedisCacheUtil;
  5. import jakarta.servlet.FilterChain;
  6. import jakarta.servlet.ServletException;
  7. import jakarta.servlet.http.HttpServletRequest;
  8. import jakarta.servlet.http.HttpServletResponse;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  13. import org.springframework.security.core.context.SecurityContextHolder;
  14. import org.springframework.security.core.userdetails.UserDetails;
  15. import org.springframework.security.core.userdetails.UserDetailsService;
  16. import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
  17. import org.springframework.stereotype.Component;
  18. import org.springframework.web.filter.OncePerRequestFilter;
  19. import java.io.IOException;
  20. /**
  21. * @program: SpringSecurityDemo
  22. * @Description LoginFilter
  23. * @Date 2023/3/8
  24. */
  25. @Slf4j
  26. @Component
  27. public class MyLoginJwtFilter extends OncePerRequestFilter {
  28. @Autowired
  29. private UserDetailsService userDetailsService;
  30. @Autowired
  31. private RedisCacheUtil redisCacheUtil;
  32. @Override
  33. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  34. //鉴权验证
  35. //获取token
  36. String token = JwtUtil.getHeaderToken(request);
  37. if (StringUtils.isNotBlank(token)) {
  38. //获取用户名
  39. String username = JwtUtil.parseTokenName(token);
  40. if (StringUtils.isNotBlank(username)) {
  41. //判断是否有效
  42. String redisKey = Constants.REDIS_USER + token;
  43. if (redisCacheUtil.isKey(redisKey)) {
  44. //获取资源
  45. UserDetails userDetails = userDetailsService.loadUserByUsername(username);
  46. UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities());
  47. //存入资源
  48. authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  49. SecurityContextHolder.getContext().setAuthentication(authenticationToken);
  50. }
  51. }
  52. }
  53. //放行
  54. filterChain.doFilter(request, response);
  55. }
  56. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/484601
推荐阅读
相关标签
  

闽ICP备14008679号