簡體   English   中英

CORS不適用於使用Thinktecture.IdentityModel.45的/ token

[英]CORS not working for /token with Thinktecture.IdentityModel.45

(我很抱歉在這里和github都發布了這個問題,但我真的需要幫助...)

在使用Thinktecture.IdentityModel.45進行身份驗證時,我無法啟用CORS(System.Web.Http.Cors)。

我的令牌端點有問題,我使用的是默認的“/ token”。

發生的事情是,當調用/ token(來自javascript客戶端)時,瀏覽器發出2個調用,“OPTION”調用和“/ token”資源的“GET”調用。 我正在使用一個簡單的PolicyProviderFactory,以便能夠檢查請求是否獲得正確的CORS策略,它只是返回

        new EnableCorsAttribute("*", "*", "*");

第一個OPTION調用有效,GetCorsPolicyProvider被命中。 另一個調用有效,但GetCorsPolicyProvider沒有被命中,結果是服務器返回200 OK,包含所有正確的標題等,但內容響應為空。

我需要在路由配置中為令牌資源添加以下內容,否則我會得到“未找到”。

        config.Routes.MapHttpRoute(
            name: "SecurityToken",
            routeTemplate: "api/token");

在所有其他請求中,OPTIONS和GET都會調用CORS策略提供程序,一切正常。 我調試了thinktecture.identitymodel和相應的響應,返回正確的令牌。

/ token資源的GET方法不會調用CORS策略提供程序..但為什么呢? CorsMessageHandler已加載但從未被調用。 如何判斷請求是否會觸發CORS / CorsMessageHandler?

診斷跟蹤:

w3wp.exe Information: 0 : Request, Method=OPTIONS, Url=https://localhost/myapp/api/token, Message='https://localhost/myapp/api/token'
w3wp.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=MyPolicyProviderFactory.GetCorsPolicyProvider
w3wp.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: True, PreflightMaxAge: null, SupportsCredentials: True, Origins: {}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
w3wp.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: True, PreflightMaxAge: null, AllowOrigin: https://localhost:4433, AllowExposedHeaders: {}, AllowHeaders: {access-key,authorization}, AllowMethods: {GET}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
w3wp.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=200 (OK)
w3wp.exe Information: 0 : Operation=AuthenticationHandler.SendAsync, Status=200 (OK)
w3wp.exe Information: 0 : Response, Status=200 (OK), Method=OPTIONS, Url=https://localhost/myapp/api/token, Message='Content-type='none', content-length=unknown'
w3wp.exe Information: 0 : Request, Method=GET, Url=https://localhost/myapp/api/token, Message='https://localhost/myapp/api/token'
w3wp.exe Information: 0 : Operation=AuthenticationHandler.SendAsync, Status=200 (OK)
w3wp.exe Information: 0 : Response, Status=200 (OK), Method=GET, Url=https://localhost/myapp/api/token, Message='Content-type='application/json; charset=utf-8', content-length=851'

身份驗證配置如下所示:

var authentication = new AuthenticationConfiguration
    {
         ClaimsAuthenticationManager = new ClaimsTransformer(),
         RequireSsl = false, 
         EnableSessionToken = true,
         SendWwwAuthenticateResponseHeaders = true
     };

     var accessKeyHandler = new SimpleSecurityTokenHandler(
            "accessKey", 
            AccessKey.Validate);

        authentication.AddAccessKey(
            accessKeyHandler,
            AuthenticationOptions.ForHeader("access-key"));

        authentication.AddBasicAuthentication(UserCredentials.Validate, retainPassword: true);
        PassiveSessionConfiguration.ConfigureMackineKeyProtectionForSessionTokens();

為了讓CORS與OWIN Token端點很好地配合,我必須安裝Microsoft.Owin.Cors Nuget包,然后添加以下代碼行:

Startup.Auth.cs

using Microsoft.Owin.Cors;
// ...

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        // ...
        app.UseCors(CorsOptions.AllowAll);

添加軟件包並在代碼中配置CORS后,它工作得很好。

問題是需要在AuthenticationHandler之前添加CorsHandler。 但我這樣做了:

config.EnableCors();
// ...
config.MessageHandlers.Add(new AuthenticationHandler(authentication));

但這將使CorsHandler在config.MessageHandlers中的AuthenticationHandler之后。 因為.EnableCors通過LazyInitializer添加處理程序。

為了解決這個問題我做了:

config.EnableCors();
config.EnsureInitialized(); // this will add the handler to the .MessageHandlers
config.MessageHandlers.Add(new AuthenticationHandler(authentication));

事實證明這是不穩定的。穩定的解決方案是“手動”添加CorsMessageHandler:

AttributeBasedPolicyProviderFactory corsPolicyProviderFactory = new AttributeBasedPolicyProviderFactory
{
     DefaultPolicyProvider = corsAttribute
};
config.SetCorsPolicyProviderFactory(corsPolicyProviderFactory);
config.MessageHandlers.Add(new CorsMessageHandler(config));

以上並沒有解決我的問題,/ token沒有設置Allow headers。 我找到了解決這個問題的方法:

ASP.NET WEB API 2 OWIN身份驗證unfported grant_Type

Aparently Token在Owin Request上下文中運行,與其余部分分開...

一個合適的答案已經被接受但是當我遇到這個問題時,我發現我必須在Providers> ApplicaitonOAuthProvider類中添加一行。 當我試圖從Azure中的遠程網站訪問WebApi時。

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM