新版SpringSecurity安全配置說(shuō)明
新版SpringSecurityConfig
在使用SpringBoot2.7或者SpringSecurity5.7以上版本時(shí),會(huì)提示:
在 Spring Security 5.7.0-M2 中,我們棄用了
WebSecurityConfigurerAdapter,因?yàn)槲覀児膭?lì)用戶轉(zhuǎn)向基于組件的安全配置。
所以之前那種通過(guò)繼承WebSecurityConfigurerAdapter的方式的配置組件是不行的。
同時(shí)也會(huì)遇到很多問(wèn)題,例如:
在向SpringSecurity過(guò)濾器鏈中添加過(guò)濾器時(shí)(例如:JWT支持,第三方驗(yàn)證),我們需要注入AuthenticationManager對(duì)象等問(wèn)題。
故在此記錄一下SpringSecurity的一些基礎(chǔ)配置項(xiàng):
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í)候參數(shù)會(huì)傳給 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í)候參數(shù)會(huì)傳給 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)
// 登錄錯(cuò)誤處理器
.failureHandler(customAuthenticationFailureHandler)
.and()
//添加登錄邏輯攔截器,不使用默認(rèn)的UsernamePasswordAuthenticationFilter
.addFilterBefore(
new CustomUsernamePasswordAuthenticationFilter(
authenticationManager(),
customAuthenticationSuccessHandler,
customAuthenticationFailureHandler
)
, UsernamePasswordAuthenticationFilter.class)
//添加token驗(yàn)證過(guò)濾器
.addFilterBefore(new JwtAuthenticationFilter(jwtStoreService), LogoutFilter.class);
//退出
http
.logout()
// URL
.logoutUrl("/user/logout")
// 登出處理
.addLogoutHandler(customLogoutHandler)
// 登出成功處理
.logoutSuccessHandler(customLogoutSuccessHandler);
//攔截設(shè)置
http
.authorizeRequests()
//公開以下urls
.antMatchers(securityProperties.getPublicPaths()).permitAll()
//其他路徑必須驗(yàn)證
.anyRequest().authenticated();
//異常處理
http
.exceptionHandling()
// 未登錄處理
.authenticationEntryPoint(customAuthenticationEntryPoint)
// 無(wú)權(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安全配置說(shuō)明的文章就介紹到這了,更多相關(guān)SpringSecurity安全配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatisPlus3如何向數(shù)據(jù)庫(kù)中存入List
本文主要介紹了Mybatis Plus的類型處理器的使用,通過(guò)User.java和UserMapper.xml示例進(jìn)行詳細(xì)的解析,并提供了JSON解析器的使用方法,希望通過(guò)這篇文章,可以幫助大家更好的理解和掌握Mybatis Plus的類型處理器2024-10-10
Java利用happen-before規(guī)則如何實(shí)現(xiàn)共享變量的同步操作詳解
這篇文章主要給大家介紹了關(guān)于Java利用happen-before規(guī)則實(shí)現(xiàn)共享變量的同步操作的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06
Java?導(dǎo)出Excel增加下拉框選項(xiàng)
這篇文章主要介紹了Java?導(dǎo)出Excel增加下拉框選項(xiàng),excel對(duì)于下拉框較多選項(xiàng)的,需要使用隱藏工作簿來(lái)解決,使用函數(shù)取值來(lái)做選項(xiàng),下文具體的操作詳情,需要的小伙伴可以參考一下2022-04-04
Java中System.setProperty()用法與實(shí)際應(yīng)用場(chǎng)景
System.setProperty是Java中用于設(shè)置系統(tǒng)屬性的方法,它允許我們?cè)谶\(yùn)行時(shí)為Java虛擬機(jī)(JVM)或應(yīng)用程序設(shè)置一些全局的系統(tǒng)屬性,下面這篇文章主要給大家介紹了關(guān)于Java中System.setProperty()用法與實(shí)際應(yīng)用場(chǎng)景的相關(guān)資料,需要的朋友可以參考下2024-04-04
Nacos配置文件使用經(jīng)驗(yàn)及CAP原則詳解
這篇文章主要為大家介紹了Nacos配置文件使用經(jīng)驗(yàn)及CAP規(guī)則詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02
使用kotlin編寫spring cloud微服務(wù)的過(guò)程
這篇文章主要介紹了使用kotlin編寫spring cloud微服務(wù)的相關(guān)知識(shí),本文給大家提到配置文件的操作代碼,給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09

