You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于另一Spring Boot项目配置实现REST服务安全的技术问询

Hey there! Let's walk through how to secure your TicketingServiceApi using your existing JWT-based auth service (Project A) — I’ve set up this exact flow multiple times, so here’s a practical, step-by-step guide to get you sorted.

1. Align JWT Validation Setup in TicketingServiceApi

Your Ticketing service needs to trust and validate the JWT tokens issued by Project A. Here's how to set that up:

Add Required Dependencies

Make sure your TicketingServiceApi's build file includes these Spring Security dependencies (for Maven pom.xml):

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

Configure JWT Validation Settings

In your application.properties (or application.yml), add settings to point to your auth service and validate tokens:

  • If you're using symmetric encryption (same secret key for signing/verifying):
    # Match the issuer URI from Project A's JWT configuration
    spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/auth
    # Use the SAME secret key that Project A uses to sign JWTs
    spring.security.oauth2.resourceserver.jwt.secret-key=your-shared-secure-secret-from-project-a
    
  • For asymmetric encryption (recommended for production, uses public/private keys):
    spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/auth
    # Path to Project A's public key (used to verify token signatures)
    spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:8080/auth/.well-known/jwks.json
    
    Note: Project A should expose its public key via a JWKS endpoint (most JWT libraries like JJWT or Spring Security OAuth2 can handle this out of the box).

2. Configure Spring Security to Protect Your API Endpoints

Next, set up the security filter chain to enforce authentication on your Ticketing API endpoints. Here's a modern Spring Boot 3+ compatible configuration:

@Configuration
@EnableWebSecurity
public class TicketingSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // Disable CSRF if your API is only used by Angular (stateless client)
            .csrf(csrf -> csrf.disable())
            // Define access rules for your endpoints
            .authorizeHttpRequests(auth -> auth
                // Allow public access to open endpoints (e.g., ticket status lookup without login)
                .requestMatchers("/api/tickets/public/**").permitAll()
                // Require authentication for all other endpoints
                .anyRequest().authenticated()
            )
            // Enable JWT-based resource server support
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    // Optional: Convert JWT claims to Spring Security authorities (roles/permissions)
                    .jwtAuthenticationConverter(customJwtAuthConverter())
                )
            );
        return http.build();
    }

    // Optional: Customize how JWT claims map to Spring Security roles
    private JwtAuthenticationConverter customJwtAuthConverter() {
        JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();
        // Match the claim name Project A uses to store roles (e.g., "roles" or "permissions")
        authoritiesConverter.setAuthoritiesClaimName("roles");
        // Add a prefix if Project A doesn't include it (e.g., "ROLE_" for Spring's role naming convention)
        authoritiesConverter.setAuthorityPrefix("ROLE_");

        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter);
        return converter;
    }
}

3. Ensure Project A's JWT Includes Necessary Claims

Double-check that Project A includes all the data your Ticketing service needs in the JWT payload. At minimum, this should include:

  • sub (subject): Unique user ID
  • exp (expiration): Token expiry time
  • Custom claims like roles or permissions if you need role-based access control (RBAC) in TicketingServiceApi.

For example, in Project A's JWT generation code, you might add claims like this (using JJWT):

String jwt = Jwts.builder()
    .setSubject(user.getId().toString())
    .claim("roles", user.getRoles().stream().map(Role::getName).toList())
    .setIssuedAt(new Date())
    .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day expiry
    .signWith(SignatureAlgorithm.HS512, secretKey)
    .compact();

4. Test the Flow

Now verify everything works end-to-end:

  1. Call Project A's login endpoint to get a valid JWT token.
  2. When calling TicketingServiceApi endpoints, include the token in the request header:
    Authorization: Bearer <your-jwt-token-from-project-a>
    
  3. Test:
    • Requests to public endpoints should succeed without a token.
    • Requests to protected endpoints should fail without a token, or with an invalid/expired token.
    • Requests with a valid token should succeed, and you can access the authenticated user's details in your controllers via @AuthenticationPrincipal Jwt jwt.

Key Things to Keep in Mind

  • Clock Sync: Ensure Project A and TicketingServiceApi servers have synchronized clocks — JWT expiry checks will fail if there's a significant time drift.
  • Secret Management: Never hardcode your JWT secret key in code. Use environment variables, a configuration server (like Spring Cloud Config), or a secrets manager.
  • Error Handling: Add a global exception handler to catch JWT-related errors (expired token, invalid signature, missing claims) and return user-friendly JSON responses instead of default HTML error pages.

内容的提问来源于stack exchange,提问作者svijay.aug12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:13:28