我将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);
}
Run Code Online (Sandbox Code Playgroud)
效果很好-它同时为我的SPA发出了Bearer令牌以调用我的API和cookie,因此我的老式MVC页面也可以登录。
但是,如果我在声明要使用CookieAuth之前注册了OAuth服务器,则不会发出Cookie。换句话说,如果我这样做,那是行不通的:
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseCookieAuthentication(cookieOptions);
app.UseOAuthBearerAuthentication(oAuthBearerOptions);
Run Code Online (Sandbox Code Playgroud)
另外,如果我取消注释此行,它也不会发出Cookie:
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么向Owin注册的顺序很重要?为什么在cookie中设置AuthenticationType "ApplicationCookie"也会使它失败?
我对中间件不熟悉UseOAuthAuthorizationServer(),但我认为它的工作原理与其他外部身份验证中间件(例如 Google 中间件)相同。
重定向到外部源进行身份验证的身份验证中间件仅在每个浏览会话开始时使用一次。然后,它将把即将到来的请求的身份验证推迟到维护会话的 cookie 身份验证。这很好,因为这意味着每个会话只需执行一次外部身份验证的开销。
想要设置 cookie 的中间件通常不会自己执行此操作。相反,它在 Owin 上下文中使用AuthenticationResponseGrant. 然后,cookie 中间件会处理该授权,提取身份并设置 cookie。
为此,请执行以下操作:
AuthenticationResponseGrant必须与 cookie 中间件的类型匹配。因此,更改注册顺序违反了 1。并且排除身份验证类型违反了 2。
如果您想了解更多详细信息,我已经写了一篇关于它的深入博客文章。
| 归档时间: |
|
| 查看次数: |
1486 次 |
| 最近记录: |