【问题标题】:Why does Owin Startup order affect Cookie Authentication为什么 Owin 启动顺序会影响 Cookie 身份验证
【发布时间】:2014-10-03 20:45:25
【问题描述】:

我已将 Owin 配置为在身份验证时发出令牌和 cookie:

public void Configuration(IAppBuilder app)
{
    var cookieOptions = new CookieAuthenticationOptions
    {
        AuthenticationMode = AuthenticationMode.Active,
        CookieHttpOnly = true, // JavaScript should use the Bearer
        //AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        CookieName = "MyCookie",
        LoginPath = new PathString("/app/index.html#/login"),
    };

    var oAuthServerOptions = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new MyAuthorizationServerProvider(),
    };

    var oAuthBearerOptions = new OAuthBearerAuthenticationOptions
    {
    };

    // Must be registered in this order!
    app.UseCookieAuthentication(cookieOptions);
    app.UseOAuthAuthorizationServer(oAuthServerOptions);
    app.UseOAuthBearerAuthentication(oAuthBearerOptions);
 }

这很好 - 它为我的 SPA 发出承载令牌以调用我的 API 和 cookie,因此我的旧学校 MVC 页面也可以登录。

但如果我在声明要使用 CookieAuth 之前注册 OAuth 服务器,则不会发出任何 cookie。换句话说,如果我这样做,它就不起作用:

app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseCookieAuthentication(cookieOptions);
app.UseOAuthBearerAuthentication(oAuthBearerOptions);

另外,如果我取消注释这一行,它也不会发出 cookie:

AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

我的问题是为什么在 Owin 的注册顺序很重要?还有为什么将cookie中的AuthenticationType设置为"ApplicationCookie"也会导致失败呢?

【问题讨论】:

    标签: asp.net-mvc owin


    【解决方案1】:

    我不熟悉 UseOAuthAuthorizationServer() 中间件,但我认为它与其他外部身份验证中间件(例如 Google 中间件)的工作方式相同。

    重定向到外部源进行身份验证的身份验证中间件只会在每个浏览会话开始时使用一次。然后它将对即将到来的请求的身份验证推迟到维护会话的 cookie 身份验证。这很好,因为这意味着外部身份验证的开销对于每个会话只执行一次。

    想要设置 cookie 的中间件通常不会自己设置。相反,它使用AuthenticationResponseGrant 在 Owin 上下文中设置一个属性。然后授权由 cookie 中间件处理,该中间件提取身份并设置 cookie。

    为此工作:

    1. 必须在管道中的外部身份验证中间件之前注册 cookie 处理程序。
    2. AuthenticationResponseGrant 中的身份验证类型必须与 cookie 中间件的类型匹配。

    所以更改注册顺序违反1.排除认证类型违反2.

    如果您想了解更多详细信息,我已经写了一封in depth blog post

    【讨论】:

    • Anders Abel,我阅读了您的整个 OWIN 系列,这是一个很好的介绍!我希望我在开始之前就找到了它,而不是我发现的无数令人困惑的资源。
    • 跟进,我的案例类似于 Visual Studio 内置的 SPA 模板所做的 - 它支持 MVC 页面的 cookie 授权和 API 的承载令牌。无论如何,根据您在 (1) 中的论点,OAuthBearerAuthentication 是否也应该在管道中的 OAuthAuthorizationServer 之前?
    • 不知道OAuthBearerAuthentication和OAuthAuthorizationServer如何交互以及后者是否依赖于前者的细节,所以无法回答。
    猜你喜欢
    • 2023-04-05
    • 2016-03-24
    • 2015-10-09
    • 2023-03-31
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2015-06-05
    相关资源
    最近更新 更多