新版SpringSecurity安全配置說明
新版SpringSecurityConfig
在使用SpringBoot2.7
或者SpringSecurity5.7
以上版本時,會提示:
在 Spring Security 5.7.0-M2 中,我們棄用了
WebSecurityConfigurerAdapter
,因為我們鼓勵用戶轉(zhuǎn)向基于組件的安全配置。
所以之前那種通過繼承WebSecurityConfigurerAdapter
的方式的配置組件是不行的。
同時也會遇到很多問題,例如:
在向SpringSecurity過濾器鏈中添加過濾器時(例如:JWT支持,第三方驗證),我們需要注入AuthenticationManager
對象等問題。
故在此記錄一下SpringSecurity的一些基礎(chǔ)配置項:
1 網(wǎng)絡(luò)安全配置,忽略部分路徑(如靜態(tài)文件路徑)
@Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2"); }
2 設(shè)置中文配置
@Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); // 設(shè)置中文配置 messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN"); return messageSource; }
3 設(shè)置密碼編碼器
@Bean @ConditionalOnMissingBean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
4 取消ROLE_ prefix
@Bean @ConditionalOnMissingBean public GrantedAuthorityDefaults grantedAuthorityDefaults() { // Remove the ROLE_ prefix return new GrantedAuthorityDefaults(""); }
5 暴露本地認(rèn)證管理器(AuthenticationManager)
/** * 認(rèn)證管理器,登錄的時候參數(shù)會傳給 authenticationManager */ @Bean(name = BeanIds.AUTHENTICATION_MANAGER) public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); }
6 其他配置
import com.example.websocket.chat.security.filer.CustomUsernamePasswordAuthenticationFilter; import com.example.websocket.chat.security.filer.JwtAuthenticationFilter; import com.example.websocket.chat.security.handler.*; import com.example.websocket.chat.security.service.JwtStoreService; import com.example.websocket.chat.security.service.impl.UserDetailsServiceImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.core.GrantedAuthorityDefaults; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; import javax.annotation.Resource; /** * @author zhong */ @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; /** * 靜態(tài)文件放行 */ @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().antMatchers(securityProperties.getStaticPaths()); } /** * 取消ROLE_前綴 */ @Bean public GrantedAuthorityDefaults grantedAuthorityDefaults() { // Remove the ROLE_ prefix return new GrantedAuthorityDefaults(""); } /** * 設(shè)置密碼編碼器 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * 設(shè)置中文配置 */ @Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN"); return messageSource; } /** * 認(rèn)證管理器,登錄的時候參數(shù)會傳給 authenticationManager */ @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } /** * 設(shè)置默認(rèn)認(rèn)證提供 */ @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() //添加登錄邏輯攔截器,不使用默認(rèn)的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); //攔截設(shè)置 http .authorizeRequests() //公開以下urls .antMatchers(securityProperties.getPublicPaths()).permitAll() //其他路徑必須驗證 .anyRequest().authenticated(); //異常處理 http .exceptionHandling() // 未登錄處理 .authenticationEntryPoint(customAuthenticationEntryPoint) // 無權(quán)限處理 .accessDeniedHandler(customAccessDeniedHandler); //關(guān)閉session http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 關(guān)閉cors http.cors().disable(); // 關(guān)閉csrf http.csrf().disable(); // 關(guān)閉headers http.headers().frameOptions().disable(); return http.build(); } }
到此這篇關(guān)于新版SpringSecurity安全配置說明的文章就介紹到這了,更多相關(guān)SpringSecurity安全配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Cloud之服務(wù)監(jiān)控turbine的示例
這篇文章主要介紹了Spring Cloud之服務(wù)監(jiān)控turbine的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05Java實現(xiàn)數(shù)據(jù)脫敏的方法詳細(xì)講解
這篇文章主要給大家介紹了關(guān)于Java實現(xiàn)數(shù)據(jù)脫敏的相關(guān)資料,數(shù)據(jù)脫敏是指對某些敏感信息通過脫敏規(guī)則進(jìn)行數(shù)據(jù)的變形,實現(xiàn)敏感隱私數(shù)據(jù)的可靠保護(hù),需要的朋友可以參考下2023-06-06Java JVM原理與調(diào)優(yōu)_動力節(jié)點(diǎn)Java學(xué)院整理
JVM是Java Virtual Machine(Java虛擬機(jī))的縮寫,JVM是一種用于計算設(shè)備的規(guī)范,它是一個虛構(gòu)出來的計算機(jī),是通過在實際的計算機(jī)上仿真模擬各種計算機(jī)功能來實現(xiàn)的。下面通過本文給大家介紹jvm原理與調(diào)優(yōu)相關(guān)知識,感興趣的朋友一起學(xué)習(xí)吧2017-04-04SpringMVC Mybatis配置多個數(shù)據(jù)源并切換代碼詳解
這篇文章主要介紹了SpringMVC Mybatis配置多個數(shù)據(jù)源并切換代碼詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11SpringBoot使用AES對JSON數(shù)據(jù)加密和解密的實現(xiàn)方法
這篇文章主要介紹了SpringBoot使用AES對JSON數(shù)據(jù)加密和解密的實現(xiàn)方法,文章通過代碼示例介紹的非常詳細(xì),對我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-08-08JFinal使用ajaxfileupload實現(xiàn)圖片上傳及預(yù)覽
這篇文章主要為大家詳細(xì)介紹了JFinal使用ajaxfileupload實現(xiàn)圖片上傳及預(yù)覽,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09