SpringBoot整合新版SpringSecurity完整過程
1. 引言
Spring Security是一個用于身份驗證和授權(quán)的框架,它提供了一套全面的安全服務(wù),可輕松集成到Spring應(yīng)用程序中。新版Spring Security引入了lambda表達(dá)式的配置方式,取代了之前的繁瑣XML配置和方法調(diào)用鏈?zhǔn)脚渲茫沟门渲酶忧逦?、簡潔?/p>
2. 項目依賴配置
首先,確保你的Spring Boot項目中包含了Spring Security的依賴。在pom.xml中添加以下依賴:
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3. 使用Lambda表達(dá)式配置Spring Security
在新版Spring Security中,使用lambda表達(dá)式配置可以顯著提高配置的可讀性和可維護性。以下是一個簡單的例子,展示如何使用lambda表達(dá)式配置基本的身份驗證和授權(quán)。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
}
上述配置中,我們使用lambda表達(dá)式配置了一個簡單的身份驗證和授權(quán)。userDetailsService方法配置了一個內(nèi)存中的用戶,configure方法配置了訪問權(quán)限和登錄頁面。
4. 自定義身份驗證邏輯
在實際項目中,我們通常需要實現(xiàn)自定義的身份驗證邏輯。通過lambda表達(dá)式,我們可以更清晰地定義自己的UserDetailsService和AuthenticationProvider。
@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(customUserDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
在上述配置中,我們注入了一個自定義的UserDetailsService,并通過lambda表達(dá)式配置了AuthenticationProvider。這樣我們可以更靈活地定義用戶信息的獲取和身份驗證邏輯。
5. 認(rèn)證與授權(quán)注解
新版Spring Security還引入了一系列基于注解的認(rèn)證與授權(quán)。通過lambda表達(dá)式,我們可以更直觀地配置這些注解。
5.1 @Secured注解
@Configuration
@EnableWebSecurity
public class SecuredSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Secured("ROLE_ADMIN")
@GetMapping("/admin")
public String adminPage() {
return "admin";
}
}
在上述代碼中,通過@Secured("ROLE_ADMIN")注解配置了訪問路徑/admin需要具備ROLE_ADMIN角色。
5.2 @PreAuthorize和@PostAuthorize注解
@Configuration
@EnableWebSecurity
public class PrePostSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminPage() {
return "admin";
}
@PostAuthorize("hasRole('USER')")
@GetMapping("/user")
public String userPage() {
return "user";
}
}
在上述代碼中,通過@PreAuthorize和@PostAuthorize注解分別配置了方法的前置和后置授權(quán)規(guī)則。
6. 總結(jié)
通過本文的介紹,我們學(xué)習(xí)了如何在Spring Boot項目中整合新版Spring Security,并通過lambda表達(dá)式進行簡潔、優(yōu)雅的安全配置。新版Spring Security的引入使得配置更加直觀,開發(fā)者可以更輕松地實現(xiàn)自定義的身份驗證邏輯和授權(quán)規(guī)則。希望通過本文的學(xué)習(xí),讀者能夠更加熟練地使用Spring Security保障應(yīng)用程序的安全性。
以上就是SpringBoot整合新版SpringSecurity完整過程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合SpringSecurity的資料請關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot啟動security后如何關(guān)閉彈出的/login頁面
- Springboot整合SpringSecurity的完整案例詳解
- SpringBoot整合Spring Security構(gòu)建安全的Web應(yīng)用
- SpringBoot集成Swagger使用SpringSecurity控制訪問權(quán)限問題
- SpringBoot集成SpringSecurity安全框架方式
- SpringSecurity在SpringBoot中的自動裝配過程
- Springbootadmin與security沖突問題及解決
- SpringBoot整合Springsecurity實現(xiàn)數(shù)據(jù)庫登錄及權(quán)限控制功能
- SpringBoot配置Spring?Security的實現(xiàn)示例
相關(guān)文章
Java使用設(shè)計模式中的代理模式構(gòu)建項目的實例展示
這篇文章主要介紹了Java使用設(shè)計模式中的代理模式構(gòu)建項目的實例展示,代理模式中的代理對象可以在客戶端和目標(biāo)對象之間起到中介的作用,需要的朋友可以參考下2016-05-05
基于Java SSM實現(xiàn)在線點餐系統(tǒng)
本項目基于Java SSM框架實現(xiàn)在線點餐系統(tǒng),主要實現(xiàn)系統(tǒng)的在線點餐功能。文中的示例代碼講解詳細(xì),感興趣的可以跟隨小編一起學(xué)習(xí)一下2022-02-02
java如何將一個float型數(shù)的整數(shù)部分和小數(shù)分別輸出顯示
這篇文章主要介紹了java如何將一個float型數(shù)的整數(shù)部分和小數(shù)分別輸出顯示,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
java對象和json的來回轉(zhuǎn)換知識點總結(jié)
在本篇文章里小編給大家分享了一篇關(guān)于java對象和json的來回轉(zhuǎn)換知識點總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
mybatisplus報錯:Invalid bound statement(not fou
文章主要介紹了在使用MyBatis-Plus時遇到的`Invalid bound statement (not found)`錯誤的幾種常見原因和解決方法,包括namespace路徑不一致、函數(shù)名或標(biāo)簽id不一致、構(gòu)建未成功、掃包配置錯誤以及配置文件書寫錯誤2025-02-02
SpringBoot系列教程之dubbo和Zookeeper集成方法
這篇文章主要介紹了SpringBoot系列教程之dubbo和Zookeeper集成方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
SpringBoot+MyBatis整合ClickHouse實踐記錄
本文介紹了如何使用SpringBoot、MyBatis和ClickHouse整合,包括添加依賴、配置數(shù)據(jù)源、創(chuàng)建實體類、Mapper接口、服務(wù)層和控制器的步驟,通過這些步驟,可以使Java應(yīng)用程序高效地與ClickHouse數(shù)據(jù)庫進行交互,感興趣的朋友跟隨小編一起看看吧2024-12-12

