Angular5 WebApi令牌授权不起作用 [英] Angular5 WebApi token authorization not working

查看:93
本文介绍了Angular5 WebApi令牌授权不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Angular5客户端和WebApi服务器应用程序实现令牌授权.我设法创建了该项目的WebApi部分,当我尝试通过"POSTMAN"获取令牌时,得到了很好的答复: 邮递员请求和服务器答案

I'm trying to implement token authorization for Angular5 client and WebApi server application. I have managed to create WebApi part of the project in question and when I try to get the token via "POSTMAN" I get a good response: Postman request and server answer

我正在尝试使用Angular5达到相同的效果.这是我打电话给我的电话:

I'm trying to achieve the same with Angular5. This is my call from angular:

login(user: string, pass: string) {
    let params = new HttpParams()
        .append('grant_type', 'password')
        .append('username', user)
        .append('password', pass);
    let headers = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded');
 return this._http.post<boolean>('auth', params, { headers: headers });
}

运行此命令时,我会不断收到来自服务器的错误请求". Chrome响应

When I run this, I'm keep getting "bad request" from server.Chrome response

如果有人有任何想法,我将不胜感激.预先感谢.

If anyone has any idea, I would appreciate help. Thanks in advance.

推荐答案

感谢David的帮助.我尝试了您的解决方案,但是直到更改了WebAPI CORS设置,该解决方案才有用.问题与飞行前CORS要求有关.我按照

Thanks David for your help. I tried your solution but it didn't help until I changed my WebAPI CORS settings. The issue was with Pre-flight CORS request. I followed instructions in this article and that solved my issue.

简而言之:

  1. 我清除了WebAPI上有关CORS的所有设置,并安装了Microsoft.Owin.Cors程序包.
  2. 然后我用以下代码修改了App_Start\Startup.Auth.cs文件中的ConfigureAuth方法:

  1. I cleared all settings regarding CORS on my WebAPI and installed Microsoft.Owin.Cors package.
  2. Then I modified the ConfigureAuth method in the App_Start\Startup.Auth.cs file with the following code:

public void ConfigureAuth(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseOAuthBearerTokens(OAuthOptions); }

public void ConfigureAuth(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseOAuthBearerTokens(OAuthOptions); }

即使我使用问题中的Angular代码,也解决了问题.现在可以正常工作了.

That solved the issue, even with my code in Angular from the question. It now works fine.

这篇关于Angular5 WebApi令牌授权不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆