Spring Boot集成Spring Cloud Security進(jìn)行安全增強(qiáng)的方法
Spring Boot集成Spring Cloud Security進(jìn)行安全增強(qiáng)
大家好,我是微賺淘客返利系統(tǒng)3.0的小編,是個(gè)冬天不穿秋褲,天冷也要風(fēng)度的程序猿!
在微服務(wù)架構(gòu)中,服務(wù)的安全性是至關(guān)重要的。Spring Cloud Security提供了一套安全工具集,幫助開發(fā)者快速實(shí)現(xiàn)認(rèn)證和授權(quán)。本文將介紹如何在Spring Boot應(yīng)用中集成Spring Cloud Security來增強(qiáng)安全性。
一、Spring Cloud Security簡介
Spring Cloud Security是Spring Security的擴(kuò)展,它提供了對(duì)Spring Cloud體系中的服務(wù)認(rèn)證和授權(quán)的支持,包括OAuth2、JWT等。
二、添加依賴
在Spring Boot項(xiàng)目的pom.xml中添加Spring Cloud Security的依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>確保項(xiàng)目中已經(jīng)包含了Spring Cloud的依賴管理。
三、配置Security
在application.properties或application.yml中配置Security:
security.oauth2.resource.id=juwatech-service security.oauth2.resource.user-info-uri=http://localhost:9999/userinfo security.oauth2.client.client-id=your-client-id security.oauth2.client.client-secret=your-client-secret
四、啟用Security
在Spring Boot應(yīng)用中啟用Spring Cloud Security:
package cn.juwatech.config;
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.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt();
}
}五、使用JWT進(jìn)行令牌認(rèn)證
配置JWT的解析和驗(yàn)證:
package cn.juwatech.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
@EnableWebSecurity
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new JwtGrantedAuthoritiesConverter());
http
.oauth2Login()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter);
}
}使用@PreAuthorize或@Secured注解進(jìn)行方法級(jí)別的安全控制:
package cn.juwatech.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SecuredController {
@GetMapping("/secure-data")
@PreAuthorize("hasAuthority('SCOPE_READ')")
public String secureData() {
return "Secure data";
}
}六、集成OAuth2.0認(rèn)證服務(wù)器
添加OAuth2.0認(rèn)證服務(wù)器依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>配置OAuth2.0認(rèn)證服務(wù)器:
package cn.juwatech.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
public class OAuth2ServerConfig {
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("secret");
return converter;
}
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter converter) {
return new JwtTokenStore(converter);
}
@Bean
public DefaultAccessTokenConverter accessTokenConverter() {
return new DefaultAccessTokenConverter();
}
}七、使用Spring Security Test支持
Spring Security提供了測(cè)試支持,可以簡化安全性集成測(cè)試的編寫。
package cn.juwatech.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class SecurityControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithAnonymousUser
public void testSecureEndpointWithoutAuthentication() throws Exception {
mockMvc.perform(get("/secure-data"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(authorities = "SCOPE_READ")
public void testSecureEndpointWithAuthentication() throws Exception {
mockMvc.perform(get("/secure-data"))
.andExpect(status().isOk());
}
}八、總結(jié)
Spring Cloud Security為Spring Boot應(yīng)用提供了一套完整的安全解決方案,支持OAuth2、JWT等多種認(rèn)證和授權(quán)機(jī)制。通過簡單的配置和代碼注解,可以快速實(shí)現(xiàn)服務(wù)的安全性增強(qiáng)。同時(shí),Spring Security的測(cè)試支持也簡化了安全性集成測(cè)試的過程。
本文著作權(quán)歸聚娃科技微賺淘客系統(tǒng)開發(fā)者團(tuán)隊(duì),轉(zhuǎn)載請(qǐng)注明出處!
到此這篇關(guān)于Spring Boot集成Spring Cloud Security進(jìn)行安全增強(qiáng)的文章就介紹到這了,更多相關(guān)Spring Boot Spring Cloud Security增強(qiáng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis快速入門學(xué)習(xí)教程新手注意問題小結(jié)
MyBatis 是支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射的優(yōu)秀的持久層框架。接下來通過本文給大家介紹mybatis快速入門學(xué)習(xí)教程新手注意問題小結(jié),需要的朋友可以參考下2017-02-02
Java mysql詳細(xì)講解雙數(shù)據(jù)源配置使用
在開發(fā)過程中我們常常會(huì)用到兩個(gè)數(shù)據(jù)庫,一個(gè)數(shù)據(jù)用來實(shí)現(xiàn)一些常規(guī)的增刪改查,另外一個(gè)數(shù)據(jù)庫用來實(shí)時(shí)存數(shù)據(jù)。進(jìn)行數(shù)據(jù)的統(tǒng)計(jì)分析。可以讀寫分離。可以更好的優(yōu)化和提高效率;或者兩個(gè)數(shù)據(jù)存在業(yè)務(wù)分離的時(shí)候也需要多個(gè)數(shù)據(jù)源來實(shí)現(xiàn)2022-06-06
SpringBoot集成Shiro+JWT(Hutool)完整代碼示例
Apache Shiro是一個(gè)強(qiáng)大且易用的Java 安全框架,提供了認(rèn)證、授權(quán)、加密和會(huì)話管理功能,在現(xiàn)代應(yīng)用開發(fā)中,Shiro 因其簡單性和靈活性而被廣泛采用,下面通過本文給大家介紹SpringBoot集成Shiro+JWT(Hutool)完整代碼示例,感興趣的朋友跟隨小編一起看看吧2025-08-08
Java基礎(chǔ)之打印萬年歷的簡單實(shí)現(xiàn)(案例)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)之打印萬年歷的簡單實(shí)現(xiàn)(案例)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-07-07
SpringBoot實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的項(xiàng)目實(shí)踐
在實(shí)際開發(fā)過程中,我們經(jīng)常遇到需要同時(shí)操作多個(gè)數(shù)據(jù)源的情況,本文主要介紹了SpringBoot實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04
面試必問項(xiàng)之Set實(shí)現(xiàn)類:TreeSet
這篇文章主要介紹了Java TreeSet類的簡單理解和使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-07-07
Hibernate迫切連接和普通連接的區(qū)別實(shí)例詳解
這篇文章主要介紹了Hibernate迫切連接和普通連接的區(qū)別實(shí)例詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
JAVA如何自動(dòng)下載SSL證書并導(dǎo)入到本地
這篇文章主要介紹了JAVA如何自動(dòng)下載SSL證書并導(dǎo)入到本地問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07

