首页 文章

Umbraco Web API - Cookie身份验证

提问于
浏览
0

我正在使用带有OWIN启动类的Umbraco 7.5 .

尽管使用cookie auth存在缺点,但我正在尝试在MVC和Web API之间共享cookie auth .

我在我的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方法 .

1 回答

  • 0

    我找到了答案 - 它与OWIN无关,而且与我的Web API初始化代码有关 . 我将自托管Web API所需的代码与作为MVC应用程序的一部分运行Web API所需的代码混合在一起 . 而不是IAppBuilder.UseWebApi()我应该使用GlobalConfiguration.Configure()

    所以工作代码看起来像这样:

    public static void Configure(IAppBuilder app)
    {
        GlobalConfiguration.Configure(Register);
    }
    
    private static void Register(HttpConfiguration config)
    {
        ConfigureHttpRoutes(config);
    
        ConfigureFormatters(config);
    
        //etc...
    }
    

    this SO question遇到了类似的问题 .

相关问题