4
我正在編寫ASP.NET和Identity 2.0的Web API。如果用戶「成功登錄」,API應該只能訪問。登錄工作很好,但註銷(註銷)似乎不起作用。下面是一些代碼我使用:ASP.NET身份2.0退出不起作用
身份配置:
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<IdentityDbContext<IdentityUser>>(HLAccountManager.CreateDbContext);
app.CreatePerOwinContext<UserManager<IdentityUser>>(HLAccountManager.CreateUserManager);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
GlobalConfiguration.Configuration.SuppressDefaultHostAuthentication();
GlobalConfiguration.Configuration.Filters.Add(new HostAuthenticationFilter("Bearer"));
}
認證控制器:
[HttpPost]
[ActionName("Authenticate")]
[AllowAnonymous]
public String Authenticate(JObject data)
{
dynamic json = data;
string user = json.user;
string password = json.password;
if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password))
return "failed";
var userIdentity = UserManager.FindAsync(user, password).Result;
if (userIdentity != null)
{
var identity = new ClaimsIdentity(IdentityConfig.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = IdentityConfig.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
}
return "failed";
}
[HttpGet]
[Authorize]
[ActionName("Logout")]
public String Logout()
{
var owinContext = HttpContext.Current.GetOwinContext();
owinContext.Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalBearer);
return "OK";
}
的身份驗證,方法,效果很好。我的webapp從請求中獲取一個令牌,我可以將其設置爲授權標頭(例如,在$ http for angular應用程序中)。隨後調用[Authorize] -annotated函數將正確返回。 但是,如果我調用Logout,它將正確返回「OK」字符串,但不會使令牌失效。如果我在調用Logout之後調用Authorize方法,我仍然會得到正確的值,而不是預期的401 - 未授權。
- 我看到這篇文章:ASP.Net Identity Logout並嘗試登出沒有參數。那也行不通。
- HttpContext沒有GetOwinContext。在我的情況下,它在HttpContext.Current中。難道我做錯了什麼?
- 爲什麼我的註銷方法不起作用?