Gra*_*ant 1 authentication cookies asp.net-mvc owin asp.net-identity
在之前使用表单身份验证的MVC项目中,我能够使用具有以下覆盖的动作过滤器从响应中剥离身份验证cookie.
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
}
Run Code Online (Sandbox Code Playgroud)
我现在已经切换到使用基于OWIN的asp.net身份2.0,并且我想以同样的方式删除他们的身份验证cookie版本.
我修改了过滤器(下面)以使用新的cookie名称,但不再删除cookie.
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
const string authenticationCookie = CookieAuthenticationDefaults.CookiePrefix + DefaultAuthenticationTypes.ApplicationCookie;
filterContext.HttpContext.Response.Cookies.Remove(authenticationCookie);
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么?
原因是身份验证发生在具有自己的环境字典的OWIN管道中,而您之前的FormsAuthentication使用的是System.Web.HttpContext.
如果您设置断点:
filterContext.HttpContext.Response.Cookies
Run Code Online (Sandbox Code Playgroud)
并查看您将看到的变量甚至没有命名的cookie,.AspNet.ApplicationCookie因此您不会删除任何内容.
我不确定你想要通过删除cookie而不是仅仅记录用户来实现,但是一种类似的方法是创建一个动作过滤器,如下所示:
public class CookieStripperAttribute : ActionFilterAttribute {
public override void OnResultExecuted(ResultExecutedContext filterContext) {
filterContext.HttpContext.GetOwinContext().Environment.Add("StripAspCookie", true);
}
}
Run Code Online (Sandbox Code Playgroud)
根据需要应用它,然后在OWIN通过创建一些OWIN中间件写出消息头之前检查操作
public class AuthenticationMiddleware : OwinMiddleware
{
const string _authenticationCookie = CookieAuthenticationDefaults.CookiePrefix + DefaultAuthenticationTypes.ApplicationCookie;
public AuthenticationMiddleware(OwinMiddleware next) :
base(next) { }
public override async Task Invoke(IOwinContext context)
{
var response = context.Response;
response.OnSendingHeaders(state =>
{
var resp = (OwinResponse)state;
if (resp.Environment.ContainsKey("StripAspCookie"))
{
resp.Cookies.Delete(_authenticationCookie);
}
}, response);
await Next.Invoke(context);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在启动类中附加该中间件:
app.Use(typeof(AuthenticationMiddleware));
Run Code Online (Sandbox Code Playgroud)
请注意虽然这会吃掉它会让用户忘记它,但正如我所说,我不确定这是不是你的意图.
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |