2016-10-11 2 views
2

ASP.NET Web API 2 서비스에 대한 서비스 호출을 수행하는 Angular 2 응용 프로그램에서 작업하고 있습니다.ASP.NET Identity Token을 사용한 Angular 2 로그인

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

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

     config.EnableCors(cors); 

     ... 

    } 
} 

이것은 잘 작동되었고 나는 CORS 어떤 문제가 없었 했어요 :이 서비스에서 CORS 그래서 같은 WebApiConfig에서 활성화되었습니다. 예를 들어 /api/users을 호출하면 모든 사용자가 성공적으로 검색됩니다.

그러나 CORS 관련 문제를 제공하는 로그인 기능에 .NET ID 토큰을 사용하려고합니다. 에 로그인을 수행 할 /token를 호출 할 때 내 login.service.ts :

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 기능에 추가되어야 다음 그것을 사용하려면