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增强内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 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的路由规则计算不匹配,导致无法找到正确的数据源,通过调整userId生成逻辑
    2024-11-11
  • java 中 poi解析Excel文件版本问题解决办法

    java 中 poi解析Excel文件版本问题解决办法

    这篇文章主要介绍了java 中 poi解析Excel文件版本问题解决办法的相关资料,需要的朋友可以参考下
    2017-08-08
  • 使用maven项目pom.xml文件配置打包功能和静态资源文件自带版本号功能

    使用maven项目pom.xml文件配置打包功能和静态资源文件自带版本号功能

    在Maven项目中,通过pom.xml文件配置打包功能,可以控制构建过程,生成可部署的包,同时,为了缓存控制与版本更新,可以在打包时给静态资源文件如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中抽象类和接口的区别_动力节点Java学院整理

    Java中抽象类和接口的区别_动力节点Java学院整理

    java抽象类和接口最本质的区别是接口里不能实现方法--接口中的方法全是抽象方法。抽象类中可实现方法--抽象类中的方法可以不是抽象方法,下文给大家简单介绍下,需要的的朋友参考下
    2017-04-04
  • mybatisplus驼峰命名映射的问题解决

    mybatisplus驼峰命名映射的问题解决

    本文主要介绍了mybatisplus驼峰命名映射的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • Java关于JDK1.8中的Optional类

    Java关于JDK1.8中的Optional类

    本文主要介绍了Optional类的一些常用方法,以及其应用场景,其主要是为了规避空指针异常(NPE)。熟练的运用Optional类可以很大的简化我们的代码,使代码简洁明了。,需要的朋友可以参考下面文章内容
    2021-09-09
  • Tomcat+Eclipse乱码问题解决方法与步骤

    Tomcat+Eclipse乱码问题解决方法与步骤

    乱码问题是大家在日常开发过程中经常会遇到的问题,由于各自环境的不同,解决起来也费时费力,本文主要介绍一般性乱码问题的解决方法与步骤,开发工具采用Eclipse+Tomcat,统一设置项目编码UTF-8为例,感兴趣的朋友跟随小编一起看看吧
    2023-08-08

最新评论