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