我将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的Bearer令牌来调用我的API和cookie,这样我的旧学校MVC页面也可以登录 .
但是,如果我在声明我想使用CookieAuth之前注册OAuth服务器,则不会发出cookie . 换句话说,如果我这样做,它不起作用:
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseCookieAuthentication(cookieOptions);
app.UseOAuthBearerAuthentication(oAuthBearerOptions);
此外,如果我取消注释此行,它也不会发出cookie:
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
我的问题是为什么与Owin的注册顺序很重要?为什么将cookie中的AuthenticationType设置为 "ApplicationCookie"
也会使其失败?
1 回答
我不熟悉
UseOAuthAuthorizationServer()
中间件,但我认为它与其他外部认证中间件(例如Google中间件)的工作方式相同 .重定向到外部源进行身份验证的身份验证中间件仅在每个浏览会话的开始时使用一次 . 然后,它会将即将到来的请求的身份验证推迟到维护会话的cookie身份验证 . 这很好,因为这意味着外部身份验证的开销仅对每个会话执行一次 .
想要设置cookie的中间件通常不会自行完成 . 相反,它使用
AuthenticationResponseGrant
在Owin上下文中设置属性 . 然后,cookie中间件处理授权,提取身份并设置cookie .为此工作:
必须在管道中的外部认证中间件之前注册cookie处理程序 .
AuthenticationResponseGrant
中的身份验证类型必须与cookie中间件的类型匹配 .因此,更改注册的顺序违反1.并且不包括身份验证类型违反2 .
如果你想了解更多细节,我已经写了一篇关于它的文章 .