@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版本废弃,新的配置方法如上图。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐