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.
简而言之:
- 我清除了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);
}
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.