Spring Boot集成Spring Cloud Security進(jìn)行安全增強(qiáng)的方法
Spring Boot集成Spring Cloud Security進(jìn)行安全增強(qiáng)
大家好,我是微賺淘客返利系統(tǒng)3.0的小編,是個冬天不穿秋褲,天冷也要風(fēng)度的程序猿!
在微服務(wù)架構(gòu)中,服務(wù)的安全性是至關(guān)重要的。Spring Cloud Security提供了一套安全工具集,幫助開發(fā)者快速實現(xiàn)認(rèn)證和授權(quán)。本文將介紹如何在Spring Boot應(yīng)用中集成Spring Cloud Security來增強(qiáng)安全性。
一、Spring Cloud Security簡介
Spring Cloud Security是Spring Security的擴(kuò)展,它提供了對Spring Cloud體系中的服務(wù)認(rèn)證和授權(quán)的支持,包括OAuth2、JWT等。
二、添加依賴
在Spring Boot項目的pom.xml
中添加Spring Cloud Security的依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency>
確保項目中已經(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的解析和驗證:
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)行方法級別的安全控制:
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提供了測試支持,可以簡化安全性集成測試的編寫。
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ī)制。通過簡單的配置和代碼注解,可以快速實現(xiàn)服務(wù)的安全性增強(qiáng)。同時,Spring Security的測試支持也簡化了安全性集成測試的過程。
本文著作權(quán)歸聚娃科技微賺淘客系統(tǒng)開發(fā)者團(tuán)隊,轉(zhuǎn)載請注明出處!
到此這篇關(guān)于Spring Boot集成Spring Cloud Security進(jìn)行安全增強(qiáng)的文章就介紹到這了,更多相關(guān)Spring Boot Spring Cloud Security增強(qiáng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Sharding-jdbc報錯:Missing the data source
在使用MyBatis-plus進(jìn)行數(shù)據(jù)操作時,新增Order實體屬性后,出現(xiàn)了數(shù)據(jù)源缺失的提示錯誤,原因是因為userId屬性值使用了隨機(jī)函數(shù)生成的Long值,這與sharding-jdbc的路由規(guī)則計算不匹配,導(dǎo)致無法找到正確的數(shù)據(jù)源,通過調(diào)整userId生成邏輯2024-11-11使用maven項目pom.xml文件配置打包功能和靜態(tài)資源文件自帶版本號功能
在Maven項目中,通過pom.xml文件配置打包功能,可以控制構(gòu)建過程,生成可部署的包,同時,為了緩存控制與版本更新,可以在打包時給靜態(tài)資源文件如JS、CSS添加版本號,這通常通過插件如maven-resources-plugin實現(xiàn)2024-09-09Java中抽象類和接口的區(qū)別_動力節(jié)點Java學(xué)院整理
java抽象類和接口最本質(zhì)的區(qū)別是接口里不能實現(xiàn)方法--接口中的方法全是抽象方法。抽象類中可實現(xiàn)方法--抽象類中的方法可以不是抽象方法,下文給大家簡單介紹下,需要的的朋友參考下2017-04-04