2016-10-11 4 views
2

私は、ASP.NET Web API 2サービスへのサービス呼び出しを行っているAngular 2アプリケーションを開発中です。このサービスではCORSがそうのようWebApiConfigで有効にされていますASP.NET Identity Tokenを使用したAngular 2ログイン

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     ... 

     var cors = new EnableCorsAttribute("*", "*", "*"); 

     config.EnableCors(cors); 

     ... 

    } 
} 

これは正常に動作してきたと私はCORSに問題がなかったしました。たとえば、/api/usersを呼び出すと、すべてのユーザーが正常に取得されます。

しかし、CORSに関連する問題を引き起こしているログイン機能に.NET IDトークンを使用しようとしています。私login.service.tsでログインを実行するために/tokenを呼び出す場合:

loginUser(username: string, password: string) { 
    let serviceURL = 'http://myurl/token'; 

    let body = 'username=' + username + '&password=' + password + '&grant_type=password'; 

    let headers: Headers = new Headers(); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 

    let options: RequestOptions = new RequestOptions({ 
     headers: headers 
    }); 

    return this.http.post(serviceURL, body, options) 
     .map(res => this.extractData(res)) 
     .catch(this.handleError); 
} 

私は次のエラーを取得する:

XMLHttpRequest cannot load http://myurl/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400.

私は二つの理由から、この混乱を見つけることだ:

  1. 上記のとおり、/apiコールでCORS問題が発生していない
  2. 正しい資格情報を入力すると、通話は「成功」(つまり、 Status Code 200しかし、上記のエラーが表示されます。

私は同様の実装でさまざまな記事を見てきましたが、私は自分の間違いを見つけることができません。

答えて

1

私はようやくこれが起こった理由を見つけました。 hereにハイライト表示されているように、WebApiConfigの前に/tokenエンドポイントが初期化されているため、ここに設定しても/tokenエンドポイントのCORSは有効になりません。

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{ 

    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 

    ... 

} 

は、同様にこのエンドポイントのため IdentityConfig.cs Create機能に追加する必要があり、以下にそれを有効にするには
関連する問題