新版本Spring Security 2.7 + 用法,直接旧正版粘贴
一、以前的用法:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected 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@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}
WebSecurityConfigurerAdapter 已经过时了,新版本已经不用这个了。
二、现在的用法
使用@EnableWebSecurity注解
@Configuration
@EnableWebSecurity
public class SecurityConfig{//配置密码加密器@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}/*** 安全配置*/@BeanSecurityFilterChain 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 {@Resourceprivate CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;@Resourceprivate CustomAuthenticationFailureHandler customAuthenticationFailureHandler;@Resourceprivate CustomAuthenticationEntryPoint customAuthenticationEntryPoint;@Resourceprivate CustomLogoutHandler customLogoutHandler;@Resourceprivate CustomLogoutSuccessHandler customLogoutSuccessHandler;@Resourceprivate CustomAccessDeniedHandler customAccessDeniedHandler;@Resourceprivate SecurityProperties securityProperties;@Resourceprivate JwtStoreService jwtStoreService;@Resourceprivate UserDetailsServiceImpl userDetailsService;@Resourceprivate AuthenticationConfiguration authenticationConfiguration;/*** 静态文件放行*/@Beanpublic WebSecurityCustomizer webSecurityCustomizer() {return (web) -> web.ignoring().antMatchers(securityProperties.getStaticPaths());}/*** 取消ROLE_前缀*/@Beanpublic GrantedAuthorityDefaults grantedAuthorityDefaults() {// Remove the ROLE_ prefixreturn new GrantedAuthorityDefaults("");}/*** 设置密码编码器*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}/*** 设置中文配置*/@Beanpublic ReloadableResourceBundleMessageSource messageSource() {ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");return messageSource;}/*** 认证管理器,登录的时候参数会传给 authenticationManager*/@Beanpublic AuthenticationManager authenticationManager() throws Exception {return authenticationConfiguration.getAuthenticationManager();}/*** 设置默认认证提供*/@Beanpublic DaoAuthenticationProvider daoAuthenticationProvider() {final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();authenticationProvider.setUserDetailsService(userDetailsService);authenticationProvider.setPasswordEncoder(passwordEncoder());return authenticationProvider;}/*** 安全配置*/@Beanpublic 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);//关闭sessionhttp.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);// 关闭corshttp.cors().disable();// 关闭csrfhttp.csrf().disable();// 关闭headershttp.headers().frameOptions().disable();return http.build();}
}