【问题标题】:How to Send OAuth2 POST request with Angular 6 , with the correct headers?如何使用正确的标头使用 Angular 6 发送 OAuth2 POST 请求?
【发布时间】:2019-03-12 20:02:19
【问题描述】:

我需要向 Spring Boot OAuth 2 授权服务器发送发布请求以获取 JWT 令牌?使用 Postman 我得到了令牌并且 Auth Server 工作正常。但是对于 Angular,我很难找出正确的发布请求格式?

这是我目前使用的方法。

login() {
  const url = 'http://localhost:9090/oauth/token';

  const data = {
    'grant_type': 'password',
    'username': 'username',
    'password': 'password'
  };

  const reqH = new HttpHeaders({
    'Content-Type': 'application/x-www-urlencoded',
    'Authorization': 'Basic ' + btoa('client-id' + ':' + 'secret'),
    'grant_type': 'password',
    'username': 'administrator%40divinedragon.com',
    'password': 'password'
  });

  return this.http.post('http://localhost:9090/oauth/token', data, {
    headers: reqH
  });
}

使用此方法时出现以下错误。

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "http://localhost:9090/oauth/token", ok: false, ...},

错误:{错误:“无效请求”,错误描述:“缺少授权类型”}

非常感谢您的帮助!

【问题讨论】:

  • 您解决了这个问题吗?请问你是怎么解决的。
  • 面临同样的问题。有人对此有答案吗?

标签: angular oauth oauth-2.0 jwt


【解决方案1】:
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-urlencoded');
headers = headers.append('Authorization' : 'Basic ' + btoa('client-id' + ':' + 'secret');
headers = headers.append('grant_type': 'password', 'username': 'administrator%40divinedragon.com', 'password': 'password');

【讨论】:

  • 仍然得到相同的错误伙伴:错误:{错误:“无效请求”,错误描述:“缺少授权类型”}
  • 你应该像这样发送请求:this.http.post(url,body,{headers});
【解决方案2】:
var body = "grant_type=password&username=username&password=password&client_id=clientid";
    
return this.http.post(`${this.oauth.URL}/oauth/token`, body, {
    headers: new HttpHeaders({
    Authorization: "Basic +token",
    "Content-type": "application/x-www-form-urlencoded;charset=utf-8"
    })
});

【讨论】:

    【解决方案3】:

    我认为您也将用户名和密码放在标题和正文中。 它对我有用,如下所示:

    login(username, password) {
        const headers = {
            'Authorization': 'Basic ' + btoa('devglan-client:$2a$04$e/c1/RfsWuThaWFCrcCuJeoyvwCV0URN/6Pn9ZFlrtIWaU/vj/BfG'),
            'Content-type': 'application/x-www-form-urlencoded'
        }
    
        const body = new HttpParams()
            .set('username', username)
            .set('password', password)
            .set('grant_type', 'password');
    
        this.http.post('http://localhost:8080/' + 'oauth/token', body, {headers})
            .subscribe(data => this.setToken(data),
                err => alert('invalid Creadtilas'));
    }
    

    【讨论】:

    • 您好,请问 this.setToken(data) 在 subscribe 方法中有什么作用?快速代码 sn-p 将不胜感激。谢谢。
    • 感谢您使用new HttpParams().set() 设置我的参数完美运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2018-12-30
    • 2021-08-13
    • 1970-01-01
    • 2015-12-22
    • 2019-04-11
    • 2021-10-26
    相关资源
    最近更新 更多