SoFunction
Updated on 2025-04-05

Spring Boot integrates Spring Cloud Security for security enhancement

Spring Boot integrates Spring Cloud Security for security enhancements

Hello everyone, I am the editor of Weizhuo Taoke Rebate System 3.0. I am a programmer who doesn’t wear long pants in winter and wants to be handsome even when it’s cold!

In microservice architecture, the security of services is crucial. Spring Cloud Security provides a set of security tools to help developers quickly implement authentication and authorization. This article will explain how to integrate Spring Cloud Security in Spring Boot applications to enhance security.

1. Introduction to Spring Cloud Security

Spring Cloud Security is an extension of Spring Security, which provides support for service authentication and authorization in the Spring Cloud system, including OAuth2, JWT, etc.

2. Add dependencies

In Spring Boot ProjectAdd Spring Cloud Security dependencies to:

<dependency>
    <groupId></groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

Make sure that Spring Cloud's dependency management is already included in the project.

3. Configure Security

existorConfigure Security in:

security.=juwatech-service
security.-info-uri=http://localhost:9999/userinfo
security.-id=your-client-id
security.-secret=your-client-secret

4. Enable Security

Enable Spring Cloud Security in Spring Boot app:

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

5. Use JWT for token authentication

Configure JWT parsing and verification

package ;
import ;
import ;
import .;
import .;
@EnableWebSecurity
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        (new JwtGrantedAuthoritiesConverter());
        http
            .oauth2Login()
                .and()
                .oauth2ResourceServer()
                    .jwt()
                    .jwtAuthenticationConverter(jwtAuthenticationConverter);
    }
}

use@PreAuthorizeor@SecuredAnnotation performs method-level security control:

package ;
import ;
import ;
import ;
@RestController
public class SecuredController {
    @GetMapping("/secure-data")
    @PreAuthorize("hasAuthority('SCOPE_READ')")
    public String secureData() {
        return "Secure data";
    }
}

6. Integrate OAuth2.0 authentication server

Add OAuth2.0 authentication server dependencies

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

Configure the OAuth2.0 authentication server

package ;
import ;
import .;
import .;
import .;
import .;
@Configuration
public class OAuth2ServerConfig {
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        ("secret");
        return converter;
    }
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter converter) {
        return new JwtTokenStore(converter);
    }
    @Bean
    public DefaultAccessTokenConverter accessTokenConverter() {
        return new DefaultAccessTokenConverter();
    }
}

7. Use Spring Security Test support

Spring Security provides testing support to simplify the writing of security integration tests.

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import static ;
import static ;
@SpringBootTest
@AutoConfigureMockMvc
public class SecurityControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Test
    @WithAnonymousUser
    public void testSecureEndpointWithoutAuthentication() throws Exception {
        (get("/secure-data"))
                .andExpect(status().isUnauthorized());
    }
    @Test
    @WithMockUser(authorities = "SCOPE_READ")
    public void testSecureEndpointWithAuthentication() throws Exception {
        (get("/secure-data"))
                .andExpect(status().isOk());
    }
}

8. Summary

Spring Cloud Security provides a complete set of security solutions for Spring Boot applications, supporting various authentication and authorization mechanisms such as OAuth2 and JWT. With simple configuration and code annotations, service security enhancement can be quickly achieved. At the same time, Spring Security's test support also simplifies the process of security integration testing.

This is the end of this article about Spring Boot integrating Spring Cloud Security for security enhancement. For more content related to Spring Boot Spring Cloud Security enhancement, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!