【问题标题】:WebAPI OAuth Logout - How to drop Token Cookie?WebAPI OAuth 注销 - 如何删除令牌 Cookie?
【发布时间】:2016-10-11 02:31:36
【问题描述】:

我有一个配置如下 OAuth 登录的 WebAPI:

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = authority,
        PostLogoutRedirectUri = "https://www.microsoft.com/",
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthenticationFailed = context =>
            {
                context.HandleResponse();
                context.Response.Redirect("/Error?message=" + context.Exception.Message);
                return Task.FromResult(0);
            }
        }
    });

并使用

对所有控制器强制登录
config.Filters.Add(new System.Web.Http.AuthorizeAttribute());

我现在想添加一个名为 LogoutController 的 ApiController(猜猜它的作用)。

I have found that I can logout from MVC 使用

System.Web.Security.FormsAuthentication.SignOut();

但我没有以这种方式从 WebAPI 注销。我还没有找到任何关于如何从 WebAPI 注销的信息。但是我发现there may be a bug in logout procedure, the cookie is kept and has to be removed manually,但是代码又是MVC,似乎我无法将HttpCookie 放入我的HttpResponseMessage 对象中:

    [HttpGet]
    public HttpResponseMessage Logout()
    {
        FormsAuthentication.SignOut();

        // clear authentication cookie
        HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
        cookie1.Expires = DateTime.Now.AddYears(-1);

        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent("<html><title>Logout successful</title><body style=\"font-family:sans-serif\"><div style=\"display:table; width:100%; height:100%; margin:0; padding:0; \"><div style=\"display:table-cell; vertical-align:middle; text-align:center;\">You have been successfully logged out.<br>You can close this window/tab now.</div></div></body></html>");
        response.Headers.AddCookies(cookie1); // Types don't match
        return response;
    }

如何实现我的 WebAPI 已注销并且在我登录之前是否需要再次完成 OAuth?

【问题讨论】:

    标签: c# cookies asp.net-web-api oauth-2.0


    【解决方案1】:

    最简单的方法是客户端自己“忘记”令牌 - 无需告诉服务器它(这就是清除身份验证 cookie 的真正作用 - 使浏览器删除 cookie)。

    如果您希望令牌本身不再有效,则需要维护已撤销令牌的列表。出于各种原因,您可能希望您的访问令牌始终有效但短暂,并改为撤销刷新令牌。

    【讨论】:

      【解决方案2】:

      您无法退出 API,因为您没有登录!

      例如,假设您的 API 使用 Facebook 作为其 OpenID 身份验证提供程序。 您的用户必须登录 facebook 才能使用您的 API。您的 API 会将他们重定向到 facebook 身份验证服务器,如果他们没有登录 - facebook 会要求他们登录。

      如果用户决定保持登录到 facebook,那么每次他们使用您的 API 时,他们将不需要再次登录到 facebook,并且您的中间件代码将获得一个有效的令牌,以便他们访问您的 API。

      您的 API 无法删除 facebook 和用户浏览器之间的浏览器 cookie,因此您无法将他们从 facebook 注销,因此您无法阻止他们在需要时获取新令牌。

      我不知道您使用的是哪个 OpenID 提供程序,但我认为以上内容适用于任何一个。

      您可以退出 MVC 应用程序,因为它会在您登录时在您(用户代理)和 MVC 应用程序之间创建一个 cookie。它可以删除自己的 cookie!

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 2021-03-07
        • 1970-01-01
        • 2020-04-21
        • 2014-04-28
        • 2016-11-15
        • 2014-01-01
        • 1970-01-01
        • 2012-10-01
        相关资源
        最近更新 更多