Spring boot整合security詳解
前言
在進(jìn)行框架選型時(shí)最常用的選擇就是在Spring security 和Shiro中進(jìn)行抉擇,Spring security 和 shiro 一樣,都具有認(rèn)證、授權(quán)、加密等用于權(quán)限管理的功能。但是對(duì)于Springboot而言,Spring Security比Shiro更合適一些,他們都是Spring生態(tài)里的內(nèi)容,并且在使用上Spring boot只需要引入Security就可以實(shí)現(xiàn)基礎(chǔ)的登陸驗(yàn)證。
配置依賴
spring boot的依賴版本:2.7.1
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.1</version> <relativePath/> </parent>
添加Security的依賴版本為:2.6.7
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>2.6.7</version> </dependency>
這樣就簡(jiǎn)單集成了security了,現(xiàn)在啟動(dòng)項(xiàng)目進(jìn)行訪問(wèn)會(huì)直接有了登陸頁(yè)面

這個(gè)是security進(jìn)行了簡(jiǎn)單登陸的實(shí)現(xiàn),官方提供的默認(rèn)賬號(hào)是user,密碼會(huì)在啟動(dòng)命令臺(tái)里打印,下圖中的即是密碼

這個(gè)密碼每次啟動(dòng)都會(huì)隨機(jī)生成,也可以在配置文件中進(jìn)行指定,在配置文件中加入一下代碼
spring:
security:
user:
name: admin
password: 123456
roles: admin
再重啟項(xiàng)目,此時(shí)的賬號(hào)密碼就是設(shè)置的這個(gè)了,當(dāng)然光這樣做肯定不滿足我們的權(quán)限需求,下面實(shí)現(xiàn)我們的具體權(quán)限配置
用戶配置
? 要實(shí)現(xiàn)自定義配置,首先創(chuàng)建一個(gè)繼承于WebSecurityConfigurerAdapter的配置類,并且實(shí)現(xiàn)configure方法,這個(gè)方法里就是自定義實(shí)現(xiàn)權(quán)限的邏輯
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
}@EnableWebSecurity注解,這個(gè)注解是Spring Security用于啟用web安全的注解。
? Spring Security的配置用戶存儲(chǔ)地址有四種實(shí)現(xiàn)方式
- 內(nèi)存用戶存儲(chǔ)
- 數(shù)據(jù)庫(kù)用戶存儲(chǔ)
- LDAP用戶存儲(chǔ)
- 自定義用戶存儲(chǔ)
1.內(nèi)存用戶存儲(chǔ)
這個(gè)存儲(chǔ)方式就是寫死在程序了,啟動(dòng)的時(shí)候初始化好了用戶權(quán)限的集合,優(yōu)點(diǎn)是很快,因?yàn)榛趦?nèi)存,缺點(diǎn)是不靈活、無(wú)法動(dòng)態(tài)更改權(quán)限、不可以進(jìn)行注冊(cè)操作,所以我們基本不用這種方式。
重寫configure方法后啟動(dòng)查看效果,在登陸頁(yè)面可以通過(guò)這兩個(gè)賬號(hào)進(jìn)行登陸就完成了
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
.withUser("admin").password(passwordEncoder().encode("123456")).authorities("ADMIN")
.and()
.withUser("anduoduo").password(passwordEncoder().encode("123456")).authorities("ORDINARY");
}
private PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}2.數(shù)據(jù)庫(kù)用戶存儲(chǔ)
用戶權(quán)限放在數(shù)據(jù)庫(kù)中是我們最常用的方式,這樣可以讓我們可以很方便地對(duì)用戶信息進(jìn)行增刪改查。并且還可以為用戶添加除認(rèn)證信息外的附加信息。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())
.usersByUsernameQuery(
"select username, password, status from Users where username = ?")
.authoritiesByUsernameQuery(
"select username, authority from Authority where username = ?");
}
private PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}auth調(diào)用jdbcAuthentication()來(lái)告訴Spring Security使用jdbc的方式來(lái)查詢用戶和權(quán)限,dataSource()方法指定數(shù)據(jù)庫(kù)連接信息,passwordEncoder()指定密碼加密規(guī)則,用戶的密碼數(shù)據(jù)應(yīng)該以同樣的方式進(jìn)行加密存儲(chǔ),不然,兩個(gè)加密方式不同的密碼,匹配補(bǔ)上。usersByUsernameQuery()和authoritiesByUsernameQuery()方法分別定義了查詢用戶和權(quán)限信息的sql語(yǔ)句。
3.LDAP用戶存儲(chǔ)
這種方式很少見(jiàn)應(yīng)該,LDAP是一個(gè)文件協(xié)議,這種方式就是通過(guò)獲取文件來(lái)做權(quán)限內(nèi)容,之前l(fā)og4j出現(xiàn)的被侵入bug就是因?yàn)檫@一部分,可以通過(guò)LDAP進(jìn)行代碼執(zhí)行。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> configurer = auth.ldapAuthentication()
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("member={0}");
configurer.passwordCompare()
.passwordEncoder(passwordEncoder())
.passwordAttribute("passcode");
configurer.contextSource().url("ldap://xxxxx.com:17099/dc=xxxxxx,dc=com");
}
private PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}4.自定義用戶存儲(chǔ)
? 自定義用戶存儲(chǔ),就是自行使用認(rèn)證名稱來(lái)查找對(duì)應(yīng)的用戶數(shù)據(jù),然后交給Spring Security使用。這種方式需要一個(gè)實(shí)現(xiàn)UserDetailsService的service類,
public class UserServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.getUserByUsername(username);
return user == null ? new User() : user;
}
}
這個(gè)實(shí)現(xiàn)類只需要實(shí)現(xiàn)一個(gè)方法:loadUserByUsername()。該方法需要做的是使用傳過(guò)來(lái)的username來(lái)匹配一個(gè)帶有密碼等信息的用戶實(shí)體。User的實(shí)體類需要實(shí)現(xiàn)UserDetails,因?yàn)榉祷貙?duì)象是UserDetails,也就是說(shuō),查到的信息里,必須得有Spring Security所需要的信息。
public class User implements UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
}config代碼
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
private PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}這個(gè)配置只需要告訴Spring Security的UserDetailsService實(shí)現(xiàn)類是哪個(gè)就可以了,它會(huì)去調(diào)用loadUserByUsername()來(lái)查找用戶。
攔截配置
攔截也是同樣在SecurityConfig配置類里的configure方法,只不過(guò)重載了configure方法
// 配置安全策略
@Override
protected void configure(HttpSecurity http) throws Exception {
// 設(shè)置路徑及要求的權(quán)限,支持 ant 風(fēng)格路徑寫法
http.authorizeRequests()
// 設(shè)置 OPTIONS 嘗試請(qǐng)求直接通過(guò)
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/demo/user").hasAnyRole("user", "admin")
// 注意使用 hasAnyAuthority 角色需要以 ROLE_ 開(kāi)頭
.antMatchers("/api/demo/admin").hasAnyAuthority("ROLE_admin")
.antMatchers("/api/demo/hello").permitAll()
.and()
// 開(kāi)啟表單登錄
.formLogin().permitAll()
.and()
// 開(kāi)啟注銷
.logout().permitAll();
}到此這篇關(guān)于Spring boot整合security詳解的文章就介紹到這了,更多相關(guān)Spring boot security內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot淺析安全管理之基于數(shù)據(jù)庫(kù)認(rèn)證
- SpringBoot淺析安全管理之OAuth2框架
- SpringBoot淺析安全管理之Shiro框架
- SpringBoot2.0 整合 SpringSecurity 框架實(shí)現(xiàn)用戶權(quán)限安全管理方法
- SpringBoot+SpringSecurity+jwt實(shí)現(xiàn)驗(yàn)證
- SpringBoot整合SpringSecurity實(shí)現(xiàn)JWT認(rèn)證的項(xiàng)目實(shí)踐
- Springboot詳解整合SpringSecurity實(shí)現(xiàn)全過(guò)程
- SpringBoot整合Security安全框架實(shí)現(xiàn)控制權(quán)限
- SpringBoot淺析安全管理之Spring Security配置
相關(guān)文章
jstack報(bào)錯(cuò)Unable to open socket file解決
這篇文章主要為大家介紹了jstack報(bào)錯(cuò)Unable to open socket file的解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02
java 多線程Thread與runnable的區(qū)別
這篇文章主要介紹了java 多線程Thread與runnable的區(qū)別的相關(guān)資料,java線程有兩種方法繼承thread類與實(shí)現(xiàn)runnable接口,下面就提供實(shí)例幫助大家理解,需要的朋友可以參考下2017-08-08
Java中的ScheduledThreadPoolExecutor定時(shí)任務(wù)詳解
這篇文章主要介紹了Java中的ScheduledThreadPoolExecutor詳解,??ScheduledThreadPoolExecutor?繼承自?ThreadPoolExecutor,它主要用來(lái)在給定的延遲之后運(yùn)行任務(wù),或者定期執(zhí)行任務(wù),ScheduledThreadPoolExecutor?的功能與?Timer?類似<BR>,需要的朋友可以參考下2023-12-12
java基礎(chǔ)之字符串編碼知識(shí)點(diǎn)總結(jié)
這篇文章主要介紹了java基礎(chǔ)之字符串編碼總結(jié),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有很好的幫助,要的朋友可以參考下2021-04-04
Java實(shí)現(xiàn)反轉(zhuǎn)一個(gè)鏈表的示例代碼
本文主要介紹了Java實(shí)現(xiàn)反轉(zhuǎn)一個(gè)鏈表的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
springboot打包jar中沒(méi)有主清單屬性問(wèn)題
這篇文章主要介紹了springboot打包jar中沒(méi)有主清單屬性問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Java編程實(shí)現(xiàn)非對(duì)稱加密的方法詳解
這篇文章主要介紹了Java編程實(shí)現(xiàn)非對(duì)稱加密的方法,簡(jiǎn)單講述了非對(duì)稱加密的概念、原理,并結(jié)合實(shí)例形式分析了java實(shí)現(xiàn)DH加密解密、RSA加密解密、ElGamal加密等具體操作技巧,需要的朋友可以參考下2017-08-08
springboot構(gòu)造樹(shù)形結(jié)構(gòu)數(shù)據(jù)并查詢的方法
本文主要介紹了springboot怎樣構(gòu)造樹(shù)形結(jié)構(gòu)數(shù)據(jù)并查詢,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11

