【问题标题】:Using OWIN SelfHost with Facebook Authentication使用 OWIN SelfHost 和 Facebook 身份验证
【发布时间】:2013-09-20 03:17:36
【问题描述】:

我正在使用 OWIN 来自行托管 WebApi,并且我一直在查看 VS 2013 RC 中包含的最新 SPA 模板作为指南。我有一个 Startup.Configure 方法,看起来像这样(尽可能从 SPA 复制):

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));

    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    config.MapHttpAttributeRoutes();

    app.UseWebApi(config);

    app.UseCookieAuthentication(CookieOptions);

    app.UseExternalSignInCookie(ExternalCookieAuthenticationType);

    app.UseOAuthBearerTokens(OAuthOptions, ExternalOAuthAuthenticationType);

    app.UseFacebookAuthentication(
        appId: "123456",           // obviously changed for this post
        appSecret: "deadbeef");    // obviously changed for this post
}

在我的命令行应用程序中调用如下:

static void Main(string[] args)
{
    using (WebApp.Start<Startup>(port: 1234)) { /* ... */ }
}

我也有一个直接来自 SPA 模板的 AccountController,但是当我手动“卷曲”网址 http://localhost:1234/api/Account/ExternalLogins?returnUrl=%2F&amp;generateState=true 时,我得到一个空数组。我错过了什么?

注意:如果您熟悉 ExternalLogins 端点,它最终会调用 Request.GetOwinContext().Authentication.GetExternalAuthenticationTypes(),在我的例子中它什么也不返回。

【问题讨论】:

    标签: c# facebook-authentication self-hosting owin


    【解决方案1】:

    OWIN 中间件注册顺序在这里很重要。正确的顺序是在所有身份验证中间件之后注册 web api。以下代码应该可以工作:

    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));
    
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    
        config.MapHttpAttributeRoutes();
    
        app.UseCookieAuthentication(CookieOptions);
    
        app.UseExternalSignInCookie(ExternalCookieAuthenticationType);
    
        app.UseOAuthBearerTokens(OAuthOptions, ExternalOAuthAuthenticationType);
    
        app.UseFacebookAuthentication(
            appId: "123456",           // obviously changed for this post
            appSecret: "deadbeef");    // obviously changed for this post
    
    
        app.UseWebApi(config);
    }
    

    顺便说一句,我刚刚写了一篇博客来解释 SPA 模板中的安全功能。 http://blogs.msdn.com/b/webdev/archive/2013/09/20/understanding-security-features-in-spa-template.aspx

    【讨论】:

    • 非常精明,就是这样。我必须说,这是一个相当出乎意料的约束(顺序很重要)。这是一个可能需要解决的设计缺陷吗?如果你这么认为,我很乐意在 CodePlex 项目中提出一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 2018-02-24
    • 2015-09-23
    • 2023-04-05
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多