Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - Angular5 WebApi token authorization not working

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

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 });
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

In short:

  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_StartStartup.Auth.cs file with the following code:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...