新版SpringSecurityConfig
在使用
SpringBoot2.7
或者
SpringSecurity5.7
以上版本时,会提示:
在 Spring Security 5.7.0-M2 中,我们弃用了
WebSecurityConfigurerAdapter
,因为我们鼓励用户转向基于组件的安全配置。
所以之前那种通过继承
WebSecurityConfigurerAdapter
的方式的配置组件是不行的。
同时也会遇到很多问题,例如:
在向SpringSecurity过滤器链中添加过滤器时(例如:JWT支持,第三方验证),我们需要注入
AuthenticationManager
对象等问题。
故在此记录一下SpringSecurity的一些基础配置项:
1 网络安全配置,忽略部分路径(如静态文件路径)
@BeanpublicWebSecurityCustomizerwebSecurityCustomizer(){return(web)-> web.ignoring().antMatchers("/ignore1","/ignore2");}
2 设置中文配置
@BeanpublicReloadableResourceBundleMessageSourcemessageSource(){ReloadableResourceBundleMessageSource messageSource =newReloadableResourceBundleMessageSource();// 设置中文配置
messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");return messageSource;}
3 设置密码编码器
@Bean@ConditionalOnMissingBeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}
4 取消ROLE_ prefix
@Bean@ConditionalOnMissingBeanpublicGrantedAuthorityDefaultsgrantedAuthorityDefaults(){// Remove the ROLE_ prefixreturnnewGrantedAuthorityDefaults("");}
5 暴露本地认证管理器(AuthenticationManager)
/**
* 认证管理器,登录的时候参数会传给 authenticationManager
*/@Bean(name =BeanIds.AUTHENTICATION_MANAGER)publicAuthenticationManagerauthenticationManager(AuthenticationConfiguration authenticationConfiguration)throwsException{return authenticationConfiguration.getAuthenticationManager();}
6 其他配置
importcom.example.websocket.chat.security.filer.CustomUsernamePasswordAuthenticationFilter;importcom.example.websocket.chat.security.filer.JwtAuthenticationFilter;importcom.example.websocket.chat.security.handler.*;importcom.example.websocket.chat.security.service.JwtStoreService;importcom.example.websocket.chat.security.service.impl.UserDetailsServiceImpl;importorg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Lazy;importorg.springframework.context.support.ReloadableResourceBundleMessageSource;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.authentication.dao.DaoAuthenticationProvider;importorg.springframework.security.config.BeanIds;importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;importorg.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;importorg.springframework.security.config.core.GrantedAuthorityDefaults;importorg.springframework.security.config.http.SessionCreationPolicy;importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;importorg.springframework.security.crypto.password.PasswordEncoder;importorg.springframework.security.web.SecurityFilterChain;importorg.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;importorg.springframework.security.web.authentication.logout.LogoutFilter;importjavax.annotation.Resource;/**
* @author zhong
*/@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(securedEnabled =true)publicclassSpringSecurityConfig{@ResourceprivateCustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;@ResourceprivateCustomAuthenticationFailureHandler customAuthenticationFailureHandler;@ResourceprivateCustomAuthenticationEntryPoint customAuthenticationEntryPoint;@ResourceprivateCustomLogoutHandler customLogoutHandler;@ResourceprivateCustomLogoutSuccessHandler customLogoutSuccessHandler;@ResourceprivateCustomAccessDeniedHandler customAccessDeniedHandler;@ResourceprivateSecurityProperties securityProperties;@ResourceprivateJwtStoreService jwtStoreService;@ResourceprivateUserDetailsServiceImpl userDetailsService;@ResourceprivateAuthenticationConfiguration authenticationConfiguration;/**
* 静态文件放行
*/@BeanpublicWebSecurityCustomizerwebSecurityCustomizer(){return(web)-> web.ignoring().antMatchers(securityProperties.getStaticPaths());}/**
* 取消ROLE_前缀
*/@BeanpublicGrantedAuthorityDefaultsgrantedAuthorityDefaults(){// Remove the ROLE_ prefixreturnnewGrantedAuthorityDefaults("");}/**
* 设置密码编码器
*/@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}/**
* 设置中文配置
*/@BeanpublicReloadableResourceBundleMessageSourcemessageSource(){ReloadableResourceBundleMessageSource messageSource =newReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");return messageSource;}/**
* 认证管理器,登录的时候参数会传给 authenticationManager
*/@BeanpublicAuthenticationManagerauthenticationManager()throwsException{return authenticationConfiguration.getAuthenticationManager();}/**
* 设置默认认证提供
*/@BeanpublicDaoAuthenticationProviderdaoAuthenticationProvider(){finalDaoAuthenticationProvider authenticationProvider =newDaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());return authenticationProvider;}/**
* 安全配置
*/@BeanpublicSecurityFilterChainsecurityFilterChain(HttpSecurity http,AuthenticationConfiguration authenticationConfiguration)throwsException{// 表单
http.formLogin()// 登录成功处理器.successHandler(customAuthenticationSuccessHandler)// 登录错误处理器.failureHandler(customAuthenticationFailureHandler).and()//添加登录逻辑拦截器,不使用默认的UsernamePasswordAuthenticationFilter.addFilterBefore(newCustomUsernamePasswordAuthenticationFilter(authenticationManager(),
customAuthenticationSuccessHandler,
customAuthenticationFailureHandler
),UsernamePasswordAuthenticationFilter.class)//添加token验证过滤器.addFilterBefore(newJwtAuthenticationFilter(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();}}
版权归原作者 卑微小钟 所有, 如有侵权,请联系我们删除。