@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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐