欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot集成Spring Cloud Security進行安全增強的方法

 更新時間:2024年11月25日 10:28:36   作者:wx_tangjinjinwx  
Spring Cloud Security是Spring Security的擴展,它提供了對Spring Cloud體系中的服務認證和授權的支持,包括OAuth2、JWT等,這篇文章主要介紹了Spring Boot集成Spring Cloud Security進行安全增強,需要的朋友可以參考下

Spring Boot集成Spring Cloud Security進行安全增強

大家好,我是微賺淘客返利系統3.0的小編,是個冬天不穿秋褲,天冷也要風度的程序猿!

在微服務架構中,服務的安全性是至關重要的。Spring Cloud Security提供了一套安全工具集,幫助開發(fā)者快速實現認證和授權。本文將介紹如何在Spring Boot應用中集成Spring Cloud Security來增強安全性。

一、Spring Cloud Security簡介

Spring Cloud Security是Spring Security的擴展,它提供了對Spring Cloud體系中的服務認證和授權的支持,包括OAuth2、JWT等。

二、添加依賴

在Spring Boot項目的pom.xml中添加Spring Cloud Security的依賴:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

確保項目中已經包含了Spring Cloud的依賴管理。

三、配置Security

application.propertiesapplication.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應用中啟用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進行令牌認證

配置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注解進行方法級別的安全控制:

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認證服務器

添加OAuth2.0認證服務器依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

配置OAuth2.0認證服務器

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());
    }
}

八、總結

Spring Cloud Security為Spring Boot應用提供了一套完整的安全解決方案,支持OAuth2、JWT等多種認證和授權機制。通過簡單的配置和代碼注解,可以快速實現服務的安全性增強。同時,Spring Security的測試支持也簡化了安全性集成測試的過程。

本文著作權歸聚娃科技微賺淘客系統開發(fā)者團隊,轉載請注明出處!

到此這篇關于Spring Boot集成Spring Cloud Security進行安全增強的文章就介紹到這了,更多相關Spring Boot Spring Cloud Security增強內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • IDEA2023.1.3安裝教程及下載(圖文)

    IDEA2023.1.3安裝教程及下載(圖文)

    最新變化是在IDEA?2023.1中,對新UI做出了大量改進,本文主要介紹了IDEA2023.1.3安裝教程及下載,具有一定的參考價值,感興趣的可以了解一下
    2023-10-10
  • Sharding-jdbc報錯:Missing the data source name:‘m0‘解決方案

    Sharding-jdbc報錯:Missing the data source 

    在使用MyBatis-plus進行數據操作時,新增Order實體屬性后,出現了數據源缺失的提示錯誤,原因是因為userId屬性值使用了隨機函數生成的Long值,這與sharding-jdbc的路由規(guī)則計算不匹配,導致無法找到正確的數據源,通過調整userId生成邏輯
    2024-11-11
  • java 中 poi解析Excel文件版本問題解決辦法

    java 中 poi解析Excel文件版本問題解決辦法

    這篇文章主要介紹了java 中 poi解析Excel文件版本問題解決辦法的相關資料,需要的朋友可以參考下
    2017-08-08
  • 使用maven項目pom.xml文件配置打包功能和靜態(tài)資源文件自帶版本號功能

    使用maven項目pom.xml文件配置打包功能和靜態(tài)資源文件自帶版本號功能

    在Maven項目中,通過pom.xml文件配置打包功能,可以控制構建過程,生成可部署的包,同時,為了緩存控制與版本更新,可以在打包時給靜態(tài)資源文件如JS、CSS添加版本號,這通常通過插件如maven-resources-plugin實現
    2024-09-09
  • SpringSecurity解決POST方式下CSRF問題

    SpringSecurity解決POST方式下CSRF問題

    本文主要介紹了SpringSecurity解決POST方式下CSRF問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • Java與MySQL時間不一致問題解決

    Java與MySQL時間不一致問題解決

    本文主要介紹了Java與MySQL時間不一致問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01
  • Java中抽象類和接口的區(qū)別_動力節(jié)點Java學院整理

    Java中抽象類和接口的區(qū)別_動力節(jié)點Java學院整理

    java抽象類和接口最本質的區(qū)別是接口里不能實現方法--接口中的方法全是抽象方法。抽象類中可實現方法--抽象類中的方法可以不是抽象方法,下文給大家簡單介紹下,需要的的朋友參考下
    2017-04-04
  • mybatisplus駝峰命名映射的問題解決

    mybatisplus駝峰命名映射的問題解決

    本文主要介紹了mybatisplus駝峰命名映射的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-07-07
  • Java關于JDK1.8中的Optional類

    Java關于JDK1.8中的Optional類

    本文主要介紹了Optional類的一些常用方法,以及其應用場景,其主要是為了規(guī)避空指針異常(NPE)。熟練的運用Optional類可以很大的簡化我們的代碼,使代碼簡潔明了。,需要的朋友可以參考下面文章內容
    2021-09-09
  • Tomcat+Eclipse亂碼問題解決方法與步驟

    Tomcat+Eclipse亂碼問題解決方法與步驟

    亂碼問題是大家在日常開發(fā)過程中經常會遇到的問題,由于各自環(huán)境的不同,解決起來也費時費力,本文主要介紹一般性亂碼問題的解決方法與步驟,開發(fā)工具采用Eclipse+Tomcat,統一設置項目編碼UTF-8為例,感興趣的朋友跟隨小編一起看看吧
    2023-08-08

最新評論