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

Spring 5 OAuth2如何获取当前登录用户对象?

Hey there! Let's work through how to get your logged-in user object in Spring 5 OAuth2 when SecurityContextHolder is returning an anonymous user. This is a common gotcha, so let's break down the possible issues and fixes step by step.

First, Let's Diagnose the Root Cause

The anonymous user response usually means one of these things:

  • Your OAuth2 resource server isn't properly configured to parse and validate the incoming token
  • The request isn't carrying the valid token in the correct format
  • The token itself doesn't contain the user claims your app expects

Step 1: Fix Your Resource Server Configuration

Make sure your Spring Security config is set up to handle OAuth2 resource server logic correctly. For JWT tokens (the most common use case), here's a working example:

@Configuration
@EnableWebSecurity
public class ResourceServerConfig {

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuerUri;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated() // Secure all endpoints
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(customJwtConverter())
                )
            );
        return http.build();
    }

    // Customize this converter if your token has non-standard user claims
    private JwtAuthenticationConverter customJwtConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        // If you need to map custom authorities from the token, add your converter here
        converter.setJwtGrantedAuthoritiesConverter(new JwtGrantedAuthoritiesConverter());
        return converter;
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        // This validates the token against your authorization server
        return NimbusJwtDecoder.withIssuerLocation(issuerUri).build();
    }
}

Step 2: Ensure the Request Carries the Token Correctly

Double-check that your client is sending the token in the Authorization header with the Bearer scheme, like this:

Authorization: Bearer

If the header is missing or formatted incorrectly, Spring Security will treat the request as anonymous.

Step 3: Fetch the Logged-In User Object

Once your config is correct, you have two easy ways to get the user info:

Option 1: Use SecurityContextHolder (with proper type checking)

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof JwtAuthenticationToken jwtAuth) {
    // Get the username (usually the token's "sub" claim)
    String username = jwtAuth.getName();
    
    // Fetch custom user claims from the token attributes
    String userId = jwtAuth.getTokenAttributes().get("user_id").toString();
    String email = jwtAuth.getTokenAttributes().get("email").toString();
    
    // Map to your custom User object
    CustomUser currentUser = new CustomUser(username, email, userId);
}

Option 2: Use @AuthenticationPrincipal in Controllers

This is cleaner for controller methods—Spring will inject the JWT directly:

@GetMapping("/api/user/me")
public ResponseEntity<CustomUser> getCurrentUser(@AuthenticationPrincipal Jwt jwt) {
    CustomUser user = new CustomUser();
    user.setUsername(jwt.getSubject());
    user.setEmail(jwt.getClaim("email"));
    user.setId(jwt.getClaim("user_id"));
    
    return ResponseEntity.ok(user);
}

Quick Troubleshooting Checks

  • Validate your token on jwt.io to make sure it contains the user claims you need (like sub, user_id, etc.)
  • Confirm your Spring Security version matches Spring 5 (use Spring Security 5.x—version compatibility is key here)
  • If you're using a non-JWT token format (like opaque tokens), adjust your config to use opaqueToken() instead of jwt() in the resource server setup

内容的提问来源于stack exchange,提问作者Eniss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:18:13