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

Spring Security环境下Postman请求登录接口返回403 Forbidden错误排查求助

Troubleshooting 403 Forbidden on Login API

Hey there! Let's figure out why you're hitting a 403 Forbidden when logging in, even though user registration and account verification appear to complete successfully. After reviewing your code, here are the most likely culprits and fixes:

1. Wrong Class Cast Prevents User Activation (Top Cause)

Looking at the fetchUserAndEnable method in your AuthService, there's a critical class cast error that's stopping your user from being marked as enabled:

private void fetchUserAndEnable(VerificationToken verificationToken){
    String username = verificationToken.getUser().getUsername();
    UserDetails user = userRepository.findByUsername(username).orElseThrow(() -> new SpringRedditException("User not found with name - " + username));
    User s = (User) user; // This cast is broken!
    s.setEnabled(true);
    userRepository.save(s);
}

Your UserDetailsServiceImpl returns a org.springframework.security.core.userdetails.User object (the built-in Spring Security user type), not your custom User entity. That cast will throw a ClassCastException silently (unless you're catching it elsewhere), which means the user's enabled status never gets updated from false (the value you set on registration).

Spring Security blocks logins for disabled users, which is exactly why you're seeing the 403.

Fix:

Skip the unnecessary cast and use the user directly from the verification token, or ensure you're fetching your custom User entity:

private void fetchUserAndEnable(VerificationToken verificationToken){
    // Use the user already linked to the verification token
    User user = verificationToken.getUser();
    user.setEnabled(true);
    userRepository.save(user);
}

Alternatively, if you need to re-fetch the user, make sure your repository returns your custom entity:

private void fetchUserAndEnable(VerificationToken verificationToken){
    String username = verificationToken.getUser().getUsername();
    // Fetch your custom User entity, not Spring's UserDetails
    User user = userRepository.findByUsername(username).orElseThrow(() -> new SpringRedditException("User not found with name - " + username));
    user.setEnabled(true);
    userRepository.save(user);
}

2. Login Endpoint Response Doesn't Match Your DTO (Minor Issue)

Your login endpoint currently returns a raw JWT string, but you have an AuthenticationResponse DTO designed to return both the token and username. Update your AuthController to use this DTO for consistency:

@PostMapping("/login") // Renamed from "/" for clarity
public ResponseEntity<AuthenticationResponse> login(@RequestBody LoginRequest loginRequest){
    String token = authService.login(loginRequest);
    return ResponseEntity.ok(new AuthenticationResponse(token, loginRequest.getUsername()));
}

3. JWT Token Missing Expiration (Security Improvement)

Your JwtProvider generates tokens without an expiration date, which is risky for production. Add an expiration time to make tokens more secure:

public String generatedToken(Authentication authentication){
    org.springframework.security.core.userdetails.User principal = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
    return Jwts.builder()
            .setSubject(principal.getUsername())
            .setIssuedAt(Instant.now())
            .setExpiration(Instant.now().plusMillis(3600000)) // 1-hour expiration
            .signWith(key)
            .compact();
}

4. Check Spring Security Debug Logs

Since you enabled logging.level.org.springframework.security=DEBUG, look for log lines like User is disabled—this will confirm that the disabled user status is indeed the cause of the 403.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:22:43