如何使用 Angular 6 发送带有正确标头的 OAuth2 POST 请求?

Rav*_*min 2 oauth oauth-2.0 jwt angular

我需要向 Spring Boot OAuth 2 授权服务器发送 post 请求以获取 JWT 令牌?使用 Postman 我得到了令牌并且 Auth 服务器工作正常。但是使用 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
  });
}
Run Code Online (Sandbox Code Playgroud)

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

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

错误:{错误:“invalid_request”,error_description:“缺少授权类型”}

非常感谢帮助!

Sha*_*ndu 5

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

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'));
}
Run Code Online (Sandbox Code Playgroud)