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提供了一套安全工具集,幫助開(kāi)發(fā)者快速實(shí)現(xiàn)認(rèn)證和授權(quán)。本文將介紹如何在Spring Boot應(yīng)用中集成Spring Cloud Security來(lái)增強(qiáng)安全性。
一、Spring Cloud Security簡(jiǎn)介
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è)試支持,可以簡(jiǎn)化安全性集成測(cè)試的編寫(xiě)。
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ī)制。通過(guò)簡(jiǎn)單的配置和代碼注解,可以快速實(shí)現(xiàn)服務(wù)的安全性增強(qiáng)。同時(shí),Spring Security的測(cè)試支持也簡(jiǎn)化了安全性集成測(cè)試的過(guò)程。
本文著作權(quán)歸聚娃科技微賺淘客系統(tǒng)開(kāi)發(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)文章
Sharding-jdbc報(bào)錯(cuò):Missing the data source
在使用MyBatis-plus進(jìn)行數(shù)據(jù)操作時(shí),新增Order實(shí)體屬性后,出現(xiàn)了數(shù)據(jù)源缺失的提示錯(cuò)誤,原因是因?yàn)閡serId屬性值使用了隨機(jī)函數(shù)生成的Long值,這與sharding-jdbc的路由規(guī)則計(jì)算不匹配,導(dǎo)致無(wú)法找到正確的數(shù)據(jù)源,通過(guò)調(diào)整userId生成邏輯2024-11-11java 中 poi解析Excel文件版本問(wèn)題解決辦法
這篇文章主要介紹了java 中 poi解析Excel文件版本問(wèn)題解決辦法的相關(guān)資料,需要的朋友可以參考下2017-08-08使用maven項(xiàng)目pom.xml文件配置打包功能和靜態(tài)資源文件自帶版本號(hào)功能
在Maven項(xiàng)目中,通過(guò)pom.xml文件配置打包功能,可以控制構(gòu)建過(guò)程,生成可部署的包,同時(shí),為了緩存控制與版本更新,可以在打包時(shí)給靜態(tài)資源文件如JS、CSS添加版本號(hào),這通常通過(guò)插件如maven-resources-plugin實(shí)現(xiàn)2024-09-09SpringSecurity解決POST方式下CSRF問(wèn)題
本文主要介紹了SpringSecurity解決POST方式下CSRF問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Java中抽象類和接口的區(qū)別_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
java抽象類和接口最本質(zhì)的區(qū)別是接口里不能實(shí)現(xiàn)方法--接口中的方法全是抽象方法。抽象類中可實(shí)現(xiàn)方法--抽象類中的方法可以不是抽象方法,下文給大家簡(jiǎn)單介紹下,需要的的朋友參考下2017-04-04Tomcat+Eclipse亂碼問(wèn)題解決方法與步驟
亂碼問(wèn)題是大家在日常開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)遇到的問(wèn)題,由于各自環(huán)境的不同,解決起來(lái)也費(fèi)時(shí)費(fèi)力,本文主要介紹一般性亂碼問(wèn)題的解決方法與步驟,開(kāi)發(fā)工具采用Eclipse+Tomcat,統(tǒng)一設(shè)置項(xiàng)目編碼UTF-8為例,感興趣的朋友跟隨小編一起看看吧2023-08-08