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.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应用中启用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的测试支持也简化了安全性集成测试的过程。
本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!