Spring Security 5.7.1安全过滤器链配置方法

10 篇文章 0 订阅
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration {

  @NonNull private AuthenticationSuccessHandler authenticationSuccessHandler;
  @NonNull private AuthenticationFailureHandler authenticationFailureHandler;
  @NonNull private LogoutSuccessHandler logoutSuccessHandler;
  @NonNull private AccessDeniedHandler accessDeniedHandler;
  @NonNull private AuthenticationEntryPoint authenticationEntryPoint;
  @NonNull private HttpConfiguration httpConfiguration;

  @NonNull private UserDetailsService userDetailsService;

  /**
   * 安全配置
   *
   * @param http
   * @throws Exception
   */
  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.csrf()
        .disable()
        .httpBasic()
        .disable()
        .formLogin()
        .successHandler(authenticationSuccessHandler)
        .failureHandler(authenticationFailureHandler)
        .permitAll()
        .and()
        .logout()
        .logoutSuccessHandler(logoutSuccessHandler)
        .and()
        .authorizeRequests()
        .antMatchers("/wxmp/api/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .sessionManagement()
        .disable()
        .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler)
        .authenticationEntryPoint(authenticationEntryPoint)
        .and()
        .apply(httpConfiguration)
        .and()
        .build();
  }

  @Bean
  public AuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setUserDetailsService(userDetailsService);
    // 这里要隐藏系统默认的提示信息,否则一直显示账户或密码错误
    daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
    return daoAuthenticationProvider;
  }
}
@Component
public class HttpConfiguration extends AbstractHttpConfigurer<HttpConfiguration, HttpSecurity> {

  @Override
  public void configure(HttpSecurity builder) {
    AuthenticationManager authenticationManager =
        builder.getSharedObject(AuthenticationManager.class);
    builder.addFilter(new JwtAuthenticationFilter(authenticationManager));
  }
}

SecurityConfigurerAdapter在5.7版本废弃,新的配置方法如上图。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值