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

Spring Boot 2 JWT OAuth2集成Angular5无法获取JWT令牌问题

问题分析与解决方案

你遇到的核心问题是Angular请求的参数格式和传递方式不符合OAuth2密码模式的要求——Postman/curl能成功是因为它们正确发送了application/x-www-form-urlencoded格式的表单数据,而你的Angular代码存在几个关键错误:

1. HttpParams的使用错误

HttpParams是不可变对象,调用set()方法不会修改原对象,而是返回一个新的HttpParams实例,你当前的写法没有保存这些修改,导致实际发送的参数为空。

2. 请求结构与头信息错误

Angular5的HttpClient.post方法中,第二个参数是请求体,第三个是配置对象。但OAuth2密码模式要求把参数放在请求体中(而非URL参数),且Content-Type必须为application/x-www-form-urlencoded。另外Angular5中应该使用HttpHeaders而非旧的HeadersAPI。

3. 订阅逻辑的小疏漏

你在subscribe中直接写this.setSession,没有传递响应参数,无法正确保存会话信息。


修正后的Angular登录代码

import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

// ...

login(username: string, password: string) {
  // 构建表单参数:注意保存每次set后的新实例
  const params = new HttpParams()
    .set('username', username)
    .set('password', password)
    .set('client_id', 'ADMIN')
    .set('client_secret', 'ADMIN')
    .set('grant_type', 'password')
    .set('scope', '*');

  // 设置请求头
  const headers = new HttpHeaders()
    .set('Content-Type', 'application/x-www-form-urlencoded');

  // 关键:把HttpParams转为urlencoded字符串作为请求体传递
  return this.http.post(
    Constante.BACKEND_TOKEN_REQUEST,
    params.toString(),
    { headers: headers }
  ).subscribe(res => this.setSession(res)); // 传递响应参数到setSession方法
}

额外检查点

  1. 跨域问题:如果前后端不在同一域名下,需要在Spring Boot中配置CORS,允许前端域名的请求:
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/oauth/token")
                        .allowedOrigins("http://你的Angular域名:端口")
                        .allowedMethods("POST")
                        .allowedHeaders("Content-Type")
                        .allowCredentials(true);
            }
        };
    }
}
  1. CSRF保护:OAuth2的密码模式不需要CSRF令牌,建议在WebSecurityConfig中关闭该端点的CSRF检查:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/oauth/token");
    // 其他原有配置...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:41:39