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

Spring与Angular登录功能报错401未授权问题求助

Troubleshooting 401 Unauthorized in Angular 2+ + Spring Login Flow

Hey there, sorry to hear you're stuck with this 401 error when trying to log in—let's break down what might be going on and how to fix it. The error message mentions "adding an appropriate authentication filter," which is a big clue that we need to check both your Spring security setup and how your Angular frontend is sending credentials.

Common Causes & Fixes

1. Spring Security Filter Chain Misconfiguration

First up, your Spring backend might not have the right authentication filter in place, or it's blocking your login endpoint before the filter can do its job.

  • Make sure your login endpoint is allowed for anonymous access: If your SecurityFilterChain locks down all endpoints by default, your login request will get blocked before hitting the authentication logic. Add a rule like this to your security config:
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/login").permitAll() // Allow login without pre-auth
                .anyRequest().authenticated()
            )
            // Add your authentication filter (e.g., JWT, custom login filter) in the right order
            .addFilterBefore(customAuthFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
    
  • Verify your authentication filter is properly registered: If you're using a custom filter (like for JWT or OAuth2), double-check that it's added to the filter chain in the correct order. For example, a JWT validation filter should run before the default username/password filter to validate tokens on subsequent requests.

2. Frontend Request Format Mismatch

Your Angular app might be sending login credentials in a format Spring doesn't expect, leading to failed authentication.

  • Check Content-Type and request body: If your Spring backend expects JSON, make sure your Angular request sets the correct header and sends the right payload:
    login(username: string, password: string): Observable<any> {
      const body = { username, password };
      return this.http.post('/api/login', body, {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      });
    }
    
    If your backend uses form-based login, switch to application/x-www-form-urlencoded:
    const body = new HttpParams()
      .set('username', username)
      .set('password', password);
    return this.http.post('/api/login', body.toString(), {
      headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
    });
    
  • Ensure parameter names match: Double-check that the field names in your Angular payload (e.g., username, password) exactly match what your Spring controller or authentication provider is expecting.

3. Authentication Method Mismatch

The way your frontend handles post-login authentication might not align with Spring's setup:

  • Session-based auth: If you're using session cookies, make sure Angular sends credentials with subsequent requests by setting withCredentials: true:
    this.http.get('/api/user', { withCredentials: true });
    
    Also confirm Spring is configured to allow cookie-based sessions (check sessionManagement() settings in your security config).
  • JWT auth: If your login endpoint returns a JWT token, make sure your Angular app stores it (e.g., in localStorage) and adds it to the Authorization header for future requests:
    const token = localStorage.getItem('authToken');
    return this.http.get('/api/user', {
      headers: new HttpHeaders({ 'Authorization': `Bearer ${token}` })
    });
    

4. CORS Configuration Issues

Cross-origin requests can sometimes block authentication credentials from being sent correctly:

  • Spring CORS setup: Ensure your Spring backend allows your frontend's origin and permits credentials:
    @Bean
    public CorsFilter corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);
      config.addAllowedOrigin("http://localhost:4200"); // Your Angular dev server URL
      config.addAllowedHeader("*");
      config.addAllowedMethod("*");
      source.registerCorsConfiguration("/**", config);
      return new CorsFilter(source);
    }
    
  • Angular CORS handling: If you're using HttpClient, set withCredentials: true on cross-origin requests (as mentioned in the session-based auth section).

Next Steps

If you've tried all the above and still hit the error, sharing a bit more code would help pinpoint the issue:

  • Your full Spring Security configuration class
  • Your Angular login service code
  • The exact request payload and headers (check your browser's Network tab)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:23:21