Angular和Asp.net Web Api 2令牌

时间:2017-03-15 15:57:22

标签: asp.net angularjs angular asp.net-web-api2

我正在使用Angular和.Net Web API 2后端进行身份验证。我的注册路由和其他资源正在运行,但登录/令牌不是。

在邮递员中,此请求有效,我收到令牌:  

在角度我的代码如下所示:

  credentials.grant_type = "password";
  credentials.userName = "email@email.com";
  credentials.password = "asdfasdf";
  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlenconded' });
  let options = new RequestOptions({ headers: headers });
  return this.http.post('http://localhost:58352/Token', credentials, options).map((response: Response) => {
    return response.json();
  });

但是,我收到了回复:

{"error":"unsupported_grant_type"}

在Angular.js(或Angular 1)中,我使用transformRequest使其正常工作。

1 个答案:

答案 0 :(得分:0)

这就是诀窍!

  let urlSearchParams = new URLSearchParams();
  urlSearchParams.append('userName', 'email@email.com');
  urlSearchParams.append('password', 'asdfasdf');
  urlSearchParams.append('grant_type', 'password');
  let body = urlSearchParams.toString()
  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlenconded' });
  let options = new RequestOptions({ headers: headers });
  return this.http.post('http://localhost:58352/Token', body, options).map((response: Response) => {
    return response.json();
  });