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提供了一套安全工具集,帮助开发者快速实现认证和授权。本文将介绍如何在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的测试支持也简化了安全性集成测试的过程。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

到此这篇关于Spring Boot集成Spring Cloud Security进行安全增强的文章就介绍到这了,更多相关Spring Boot Spring Cloud Security增强内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • mybatis快速入门学习教程新手注意问题小结

    mybatis快速入门学习教程新手注意问题小结

    MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。接下来通过本文给大家介绍mybatis快速入门学习教程新手注意问题小结,需要的朋友可以参考下
    2017-02-02
  • Java mysql详细讲解双数据源配置使用

    Java mysql详细讲解双数据源配置使用

    在开发过程中我们常常会用到两个数据库,一个数据用来实现一些常规的增删改查,另外一个数据库用来实时存数据。进行数据的统计分析。可以读写分离。可以更好的优化和提高效率;或者两个数据存在业务分离的时候也需要多个数据源来实现
    2022-06-06
  • SpringBoot集成Shiro+JWT(Hutool)完整代码示例

    SpringBoot集成Shiro+JWT(Hutool)完整代码示例

    Apache Shiro是一个强大且易用的Java 安全框架,提供了认证、授权、加密和会话管理功能,在现代应用开发中,Shiro 因其简单性和灵活性而被广泛采用,下面通过本文给大家介绍SpringBoot集成Shiro+JWT(Hutool)完整代码示例,感兴趣的朋友跟随小编一起看看吧
    2025-08-08
  • Java基础之打印万年历的简单实现(案例)

    Java基础之打印万年历的简单实现(案例)

    下面小编就为大家带来一篇Java基础之打印万年历的简单实现(案例)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-07-07
  • 几种SpringBoot的属性配置方式详解

    几种SpringBoot的属性配置方式详解

    通常项目配置信息都写在.properties或者.yml文件中,但是打成jar包部署后,如果需要修改配置信息,还需要改完再重新打包部署,因此,下面介绍几种SpringBoot的属性配置方式,需要的朋友可以参考下
    2024-12-12
  • SpringBoot实现动态数据源切换的项目实践

    SpringBoot实现动态数据源切换的项目实践

    在实际开发过程中,我们经常遇到需要同时操作多个数据源的情况,本文主要介绍了SpringBoot实现动态数据源切换的项目实践,具有一定的参考价值,感兴趣的可以了解一下
    2024-04-04
  • MyBatis 中的@Param注解最佳实践

    MyBatis 中的@Param注解最佳实践

    在 MyBatis 中,@Param 注解的作用是为方法参数指定一个在 XML 映射文件或注解 SQL 中引用的名称,对于你的问题,是否可以不写,取决于MyBatis的版本和参数类型,这篇文章给大家介绍MyBatis中的@Param注解,感兴趣的朋友跟随小编一起看看吧
    2025-11-11
  • 面试必问项之Set实现类:TreeSet

    面试必问项之Set实现类:TreeSet

    这篇文章主要介绍了Java TreeSet类的简单理解和使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2021-07-07
  • Hibernate迫切连接和普通连接的区别实例详解

    Hibernate迫切连接和普通连接的区别实例详解

    这篇文章主要介绍了Hibernate迫切连接和普通连接的区别实例详解,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • JAVA如何自动下载SSL证书并导入到本地

    JAVA如何自动下载SSL证书并导入到本地

    这篇文章主要介绍了JAVA如何自动下载SSL证书并导入到本地问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07

最新评论