[英]Umbraco Web API - Cookie Authentication
我正在將Ombraco 7.5與OWIN啟動類一起使用。
盡管使用cookie身份驗證存在缺點,但我仍在嘗試在MVC和Web API之間共享cookie身份驗證。
我的OWIN啟動課程中有以下內容:
private static void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
CookieSecureOption secureCookieOption = CookieSecureOption.SameAsRequest;
#if DEBUG
secureCookieOption = CookieSecureOption.Never;
#endif
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
AuthenticationMode = AuthenticationMode.Active,
LoginPath = new PathString("/Account/Login"),
CookieSecure = secureCookieOption,
CookieManager = new ChunkingCookieManager(),
Provider = new CookieAuthenticationProvider()
}, PipelineStage.Authenticate);
//configure B2C OAuth middleware
foreach (string policy in AppSettings.B2CPolicies)
{
app.UseOpenIdConnectAuthentication(CreateBearerOptionsFromPolicy(policy));
}
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
就Umbraco和自定義MVC頁面而言,此方法效果很好-當前用戶身份可用,Umbraco幫助器方法按預期工作。
但是,對於Web API控制器-無論是從UmbracoApiController還是僅從ApiController派生,HTTP上下文上的當前用戶身份始終為null。 我已經檢查了發送給API控制器的瀏覽器請求,並且包含了ASPNET身份cookie,所以我對為什么它不轉換為線程和httpcontext上的用戶身份感到困惑。 任何人都可以對此有所了解嗎?
編輯:關於此的更多信息-我嘗試創建自己的自定義cookie身份驗證中間件,並用我的自定義實現替換了標准MS CookieAuthenticationHandler,以便可以通過它跟蹤調用。 有趣的是,對於普通的MVC頁面,頁面加載時將調用AuthenticateCoreAsync方法,該方法成功讀取cookie並返回有效的身份驗證票證。 對於Web API調用,在點擊API方法之前根本不會調用AuthenticateCoreAsync方法。
我找到了答案–與OWIN無關,而與我的Web API初始化代碼有關。 我將自托管Web API所需的代碼與使Web API作為MVC應用程序的一部分運行所需的代碼混合在一起。 我應該一直在使用GlobalConfiguration.Configure()而不是IAppBuilder.UseWebApi()
因此,工作代碼如下所示:
public static void Configure(IAppBuilder app)
{
GlobalConfiguration.Configure(Register);
}
private static void Register(HttpConfiguration config)
{
ConfigureHttpRoutes(config);
ConfigureFormatters(config);
//etc...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.