c# - 使用 Asp.Net 5 Identity 3.0 注销后未删除 Cookie

标签 c# asp.net asp.net-mvc cookies asp.net-identity

我有一个带有自定义角色和用户存储的 Asp.Net MVC 应用程序(版本 6.0.0-rc1-final)。经过一番struggling我终于可以创建一个有效的登录机制。但是,我现在确实无法创建干净的注销。我在 Controller 中的注销代码目前是什么样子的:

public async Task<ActionResult> Logout()
{
    if (User.Identity.IsAuthenticated)
    {
    await SignInManager.SignOutAsync();

    }

    return RedirectToAction("Index", "App");
}

这段代码的问题是,一个 cookie 没有被删除:.AspNet.Microsoft.AspNet.Identity.Application

只要我不手动删除 cookie,应用程序就会处于脏状态并抛出空指针异常,因为 User.Identity 为空。

我找到了 question on stackoverflow描述一个类似的场景。但是那里的解决方案不适合我,因为我正在使用不再具有 System.Web 的 MVC 6。

我还有一个示例解决方案,效果很好。在此解决方案中,永远不会创建提到的 cookie。也许正确的解决方案不是在注销后删除 cookie,而是以某种方式阻止创建 cookie。

最佳答案

问题是您的 RedirectToAction 覆盖了 SignOutAsync 发出的到 Identity Server endsession URL 的重定向。

(微软的HaoK对同样的问题给出了同样的解释here)

编辑:解决方案是在带有最终SignOutAsyncAuthenticationProperties 对象中发送重定向URL:

// 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 IHttpContextAccessor 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);
}

关于c# - 使用 Asp.Net 5 Identity 3.0 注销后未删除 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920297/

相关文章:

c# - 使用自定义类 c# 反序列化来自 API 的响应

c# - 网络摄像头:打开和关闭或或保持打开

javascript - 获取请求您的 js 文件的网站的引用者

c# - 更新亚马逊商城中的商家订单 ID

c# - 如何在 LINQ to Entities Join 中使用 Convert.Int32() 方法?

c# - SqlCommand 返回 1 但数据库未更新。我做错了什么?

asp.net - 单页 ASP.NET 中不允许的结构和类

javascript - 在 javascript 函数中使用 @Html.Raw

javascript - MVC jquery.dataTables 无法获取未定义或空引用的属性 'className'

xml - MVC4 REST API 始终以 JSON 格式返回响应