一、以前的用法:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭csrf
.csrf().disable()
//不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 对于登录接口 允许匿名访问
.antMatchers("/user/login").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
WebSecurityConfigurerAdapter 已经过时了,新版本已经不用这个了。
二、现在的用法
使用@EnableWebSecurity注解
@Configuration
@EnableWebSecurity
public class SecurityConfig{
//配置密码加密器
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* 安全配置
*/
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/user/login").anonymous()
.anyRequest().authenticated();
return http.build();
}
/**
* 认证管理器,登录的时候参数会传给 authenticationManager
*/
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
三、其他的一些配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig {
@Resource
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
@Resource
private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
@Resource
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
@Resource
private CustomLogoutHandler customLogoutHandler;
@Resource
private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@Resource
private CustomAccessDeniedHandler customAccessDeniedHandler;
@Resource
private SecurityProperties securityProperties;
@Resource
private JwtStoreService jwtStoreService;
@Resource
private UserDetailsServiceImpl userDetailsService;
@Resource
private AuthenticationConfiguration authenticationConfiguration;
/**
* 静态文件放行
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers(securityProperties.getStaticPaths());
}
/**
* 取消ROLE_前缀
*/
@Bean
public GrantedAuthorityDefaults grantedAuthorityDefaults() {
// Remove the ROLE_ prefix
return new GrantedAuthorityDefaults("");
}
/**
* 设置密码编码器
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 设置中文配置
*/
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
return messageSource;
}
/**
* 认证管理器,登录的时候参数会传给 authenticationManager
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
/**
* 设置默认认证提供
*/
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
/**
* 安全配置
*/
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationConfiguration authenticationConfiguration) throws Exception {
// 表单
http.formLogin()
// 登录成功处理器
.successHandler(customAuthenticationSuccessHandler)
// 登录错误处理器
.failureHandler(customAuthenticationFailureHandler)
.and()
//添加登录逻辑拦截器,不使用默认的UsernamePasswordAuthenticationFilter
.addFilterBefore(
new CustomUsernamePasswordAuthenticationFilter(
authenticationManager(),
customAuthenticationSuccessHandler,
customAuthenticationFailureHandler
)
, UsernamePasswordAuthenticationFilter.class)
//添加token验证过滤器
.addFilterBefore(new JwtAuthenticationFilter(jwtStoreService), LogoutFilter.class);
//退出
http
.logout()
// URL
.logoutUrl("/user/logout")
// 登出处理
.addLogoutHandler(customLogoutHandler)
// 登出成功处理
.logoutSuccessHandler(customLogoutSuccessHandler);
//拦截设置
http
.authorizeRequests()
//公开以下urls
.antMatchers(securityProperties.getPublicPaths()).permitAll()
//其他路径必须验证
.anyRequest().authenticated();
//异常处理
http
.exceptionHandling()
// 未登录处理
.authenticationEntryPoint(customAuthenticationEntryPoint)
// 无权限处理
.accessDeniedHandler(customAccessDeniedHandler);
//关闭session
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// 关闭cors
http.cors().disable();
// 关闭csrf
http.csrf().disable();
// 关闭headers
http.headers().frameOptions().disable();
return http.build();
}
}