使用OWIN SelfHost和Facebook身份验证

时间:2013-09-16 03:46:20

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

我正在使用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&generateState=true时,我得到一个空数组。我错过了什么?

注意:如果您熟悉ExternalLogins端点,它最终会调用Request.GetOwinContext().Authentication.GetExternalAuthenticationTypes(),在我的情况下不返回任何内容。

1 个答案:

答案 0 :(得分:4)

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);
}
BTW,我刚刚写了一篇博客来解释SPA模板中的安全功能。 http://blogs.msdn.com/b/webdev/archive/2013/09/20/understanding-security-features-in-spa-template.aspx