HttpContext.Authentication.SignOutAsync不会删除身份验证cookie

Ale*_*tov 16 authentication cookies asp.net-core-1.0

根据ASP.NET Core 文档,该方法也 HttpContext.Authentication.SignOutAsync()必须删除身份验证cookie.

退出

要注销当前用户,并删除他们的cookie(斜体我的 - AC),请在控制器内调用以下内容

await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");

但事实并非如此!其他一切似乎都没问题,尤其是 auth scheme,因为用户正确登录了cookie .AspNetCore.被建造.

任何想法为什么cookie在用户唱出后仍然存在?

McG*_*V10 12

你没有发布足够的代码来告诉我,但我怀疑你打电话后SignOutAsync你有某种类型的重定向(例如RedirectToAction),它会将重定向覆盖到SignOutAsync试图发布的OIDC endsession URL .

(微软的HaoK 在这里给出了重定向覆盖问题的相同解释.)

编辑:如果我上面的推测是正确的,解决方案是AuthenticationProperties在最终的对象中发送重定向URL SignOutAsync:

// in some controller/handler, notice the "bare" Task return value
public async Task LogoutAction()
{
    // SomeOtherPage is where we redirect to after signout
    await MyCustomSignOut("/SomeOtherPage");
}

// probably in some utility service
public async Task MyCustomSignOut(string redirectUri)
{
    // inject the HttpContextAccessor to get "context"
    await context.SignOutAsync("Cookies");
    var prop = new AuthenticationProperties()
    {
        RedirectUri = redirectUri
    });
    // after signout this will redirect to your provided target
    await context.SignOutAsync("oidc", prop);
}
Run Code Online (Sandbox Code Playgroud)

  • 似乎对我不起作用,它重定向到“/SomeOtherPage”,但 cookie 仍然存在 (2认同)

小智 6

我最近遇到了同样的问题。就我而言,浏览器创建了多个 cookie。一个名称类似于“.AspNetCore.Antiforgery”,另一个名称是我在 startup.cs 中为我的 cookie 设置的自定义名称。

对我来说解决错误的是JTvermose 答案的第一部分,并了一些更改。我将下面的代码添加到我的注销方法中。像魅力一样工作。

    if (HttpContext.Request.Cookies.Count> 0) 
        {
            var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.Contains(".AspNetCore.") || c.Key.Contains("Microsoft.Authentication"));
            foreach (var cookie in siteCookies)
            {
                Response.Cookies.Delete(cookie.Key);
            }
        }

                await HttpContext.SignOutAsync(
    CookieAuthenticationDefaults.AuthenticationScheme);
        HttpContext.Session.Clear();
        return RedirectToPage("/Index");
Run Code Online (Sandbox Code Playgroud)


Ale*_*tov 2

这是删除 cookie 的代码(如果没有其他帮助,请使用暴力):

await this.HttpContext.Authentication.SignOutAsync(<AuthenticationScheme>);

// ...

var cookie = this.Request.Cookies[<CookieName>];
if (cookie != null)
{
    var options = new CookieOptions { Expires = DateTime.Now.AddDays(-1) };
    this.Response.Cookies.Append(cookieName, cookie, options);
}
Run Code Online (Sandbox Code Playgroud)

不好、不好、不好!看起来是一个非常丑陋的补丁!但有效...:(

还有其他解决方案吗?