我有一个带有 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);
}
}
});
并为所有使用
的 Controller 强制登录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?
最佳答案
您无法退出 API,因为您尚未登录!
例如,假设您的 API 使用 Facebook 作为其 OpenID 身份验证提供程序。 您的用户必须登录 facebook 才能使用您的 API。您的 API 会将他们重定向到 facebook 身份验证服务器,如果他们未登录 - facebook 将要求他们登录。
如果用户决定保持登录到 facebook,那么每次他们使用您的 API 时,他们将不需要再次登录到 facebook,您的中间件代码将为他们获取一个有效的 token 来访问您的 API。
您的 API 无法删除 facebook 和您用户浏览器之间的浏览器 cookie,因此您无法将他们从 facebook 中注销,因此您无法阻止他们在需要时获取新 token 。
我不知道您使用的是什么 OpenID 提供商,但我认为以上内容适用于任何提供商。
您可以注销 MVC 应用程序,因为它会在您登录时在您(用户代理)和 MVC 应用程序之间创建一个 cookie。它可以删除自己的 cookie!
关于c# - WebAPI OAuth 注销 - 如何删除 token Cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37742880/