Angular5 WebApi 令牌授权不起作用 [英] Angular5 WebApi token authorization not working
问题描述
我正在尝试为 Angular5 客户端和 WebApi 服务器应用程序实现令牌授权.我设法创建了相关项目的 WebApi 部分,当我尝试通过邮递员"获取令牌时,我得到了很好的回应:邮递员请求和服务器应答
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 实现相同的目标.这是我从 angular 打来的电话:
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.
简而言之:
- 我清除了 WebAPI 上有关 CORS 的所有设置并安装了
Microsoft.Owin.Cors
包. 然后我用以下代码修改了
App_Start\Startup.Auth.cs
文件中的ConfigureAuth
方法:
- I cleared all settings regarding CORS on my WebAPI and installed
Microsoft.Owin.Cors
package. Then I modified the
ConfigureAuth
method in theApp_Start\Startup.Auth.cs
file with the following code:
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屋!