【问题标题】:Angular HttpPost to Oauth2 return 401Angular HttpPost 到 Oauth2 返回 401
【发布时间】:2018-01-26 03:00:39
【问题描述】:

我想在我的 ionic 应用程序中使用 oauth2,但出现错误:

加载资源失败:服务器响应状态为401()

错误:http://localhost:8080/oauth/token 的 Http 失败响应:401 OK

回复:

{"timestamp":1502983544253,"status":401,"error":"Unauthorized","message":"访问此资源需要完全身份验证","path":"/oauth/token"}

角函数:

login(username, password) : Observable<any> {

 let params: HttpParams = new HttpParams();
 params.set('username', username);
 params.set('password', password);
 params.set('client_id', this.clientId);
 params.set('client_secret', this.clientSecret);
 params.set('grant_type', 'password');


 let headers = new HttpHeaders();
 headers.set('Content-Type', 'application/x-www-form-urlencoded');

 return this.http.post(this.EndPointUrl, {
   params:params
 }, { headers:headers}).map(this.handleData).
   catch(this.handleError);  }

所有参数都正确。

curl -X POST --user 'U:P' -d 'grant_type=password&username=USER&password=PASS' localhost:8080/oauth/toke

返回

{"access_token":"d88c1c5e-d2c0-4c96-9e69-a62816d0a5e8","token_type":"bearer","refresh_token":"8f82f0b0-38a3-4c05-9590-43d3ec2f36b9","expires_in":3599,"scope":"read write"}

我可以使用 PostMan 和 curl 获取令牌,我的服务器中的 CORS 已为此端点启用,因此我认为身份验证服务器工作正常。

有谁知道我做错了什么?

【问题讨论】:

标签: angular ionic-framework oauth-2.0


【解决方案1】:

尝试添加这个 headers.set('Authentication', 'Basic client_id:client_secret');(在 Base 64 中)

【讨论】:

  • 你的角度要求怎么样?
  • 也许你可以改成 headers.set('Content-Type', 'application/json');
  • 范围也是正确的,如果我设置了不正确的范围,那么我会得到错误“invalid_scope”。
  • 当我将 Content-type 更改为 aplication/json 时,我得到了同样的错误。
  • 我添加了 headers.set('Authentication','Basi c'+btoa(this.clientId+":"+this.clientSecret));" 但错误依旧。
【解决方案2】:

问题在于依赖关系。很可能来自 Angular 4.3.4 的 HTTPClient((@angular/common/http) 暂时不适用于 ionic。使用来自 Angular 4.1.3 的 Http (@angular/http) 上面的代码可以正常工作。

【讨论】:

    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2018-09-07
    • 2016-10-02
    • 1970-01-01
    相关资源
    最近更新 更多