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

Spring Boot OAuth2(JWT)+Angular5登录后获角色遇认证问题求助

Hey there, let's work through your issues step by step—both the browser redirect problem and the SoapUI 403 error have clear fixes once we break down what's happening.

Problem 1: Browser returns login page HTML instead of JSON for /AuthUser

This happens because your frontend request isn't properly authenticating with the JWT token, so Spring Security falls back to its default behavior: redirecting unauthenticated requests to the login page. Here's how to fix it:

  • Ensure your Angular app sends the JWT token in requests
    After logging in, store the JWT token (e.g., in localStorage), then use an HTTP interceptor to automatically attach it to all backend requests. Example interceptor code:

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('authToken');
        if (token) {
          request = request.clone({
            setHeaders: {
              Authorization: `Bearer ${token}`
            }
          });
        }
        return next.handle(request);
      }
    }
    

    Don't forget to register this interceptor in your app.module.ts so it applies to all requests.

  • Fix your Spring Security configuration
    Make sure your /AuthUser endpoint is configured to accept JWT authentication instead of falling back to form login. Update your security config class to prioritize OAuth2 JWT validation:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
    
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .csrf(csrf -> csrf.disable()) // We'll address CSRF later for SoapUI
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/AuthUser").authenticated()
                    .anyRequest().permitAll()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(jwt -> jwt
                        .jwtAuthenticationConverter(customJwtConverter())
                    )
                );
            return http.build();
        }
    
        // Custom converter to map JWT claims to Spring Security authorities
        private JwtAuthenticationConverter customJwtConverter() {
            JwtGrantedAuthoritiesConverter authorityConverter = new JwtGrantedAuthoritiesConverter();
            authorityConverter.setAuthorityPrefix("ROLE_");
            authorityConverter.setAuthoritiesClaimName("roles");
    
            JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
            converter.setJwtGrantedAuthoritiesConverter(authorityConverter);
            return converter;
        }
    }
    

    Remove any leftover form login configuration (like formLogin()) if you're only using JWT authentication.

Problem 2: SoapUI returns 403 CSRF error

The error "Could not verify the provided CSRF token because your session was not found." happens because:

  1. Spring Security enables CSRF protection by default (to guard against session hijacking for form-based auth)
  2. JWT is stateless—there's no server-side session to tie a CSRF token to, so this protection is unnecessary here

Here's how to fix it:

  • Disable CSRF for stateless JWT endpoints
    If your app uses only JWT authentication (no form login), add this to your Spring Security config to turn off CSRF entirely:

    http.csrf(csrf -> csrf.disable());
    

    If you still need form login for other parts of the app, you can restrict CSRF protection to only those paths instead:

    http.csrf(csrf -> csrf
        .ignoringRequestMatchers("/AuthUser", "/oauth2/**")
    );
    
  • Add the JWT token to your SoapUI request
    Even with CSRF disabled, you still need to authenticate the request. In SoapUI:

    1. Open your request
    2. Go to the Headers tab
    3. Add a new header: Authorization with value Bearer <your-jwt-token> (replace <your-jwt-token> with the actual token from your login response)

Bonus: CORS Configuration

Since your frontend runs on localhost:4200 and backend on localhost:3032, you need to enable CORS to allow cross-origin requests with authentication headers. Add this bean to your Spring Boot app:

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:4200");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Walk through these steps one by one, and you should resolve both issues. Start with verifying the JWT token is being sent correctly—this is the most common root cause for the browser redirect problem.

内容的提问来源于stack exchange,提问作者phani-rama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:33:30