2

我正在使用 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(),在我的情况下它什么也不返回。

4

1 回答 1

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);
}

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

于 2013-09-20T18:58:02.893 回答