我正在使用ASP.NET和Identity 2.0编写Web API。只有在用户登录后才能访问API。'成功。登录工作很棒,但注销(注销)似乎不起作用。以下是我使用的一些代码:
身份配置:
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";
}
Authenticate方法效果很好。我的webapp从请求中获取一个令牌,我可以将其设置为Authorization-header(例如,在$ http for angular apps中)。对[授权]注释函数的后续调用将正确返回。 但是,如果我调用Logout,它将返回&#34; OK&#34;字符串正确,但不会使令牌无效。如果我在调用Logout后调用Authorize-method,我仍然得到一个正确的值而不是预期的401 - Unauthorized。
答案 0 :(得分:8)
似乎我得到了(持票人)令牌的基本概念错误,这就是为什么它不起作用。我把它留在这里以防有人绊倒同样的问题:
令牌无法撤销或失效 - 至少不能使用ASP.NET Identity 2.0。 SignOut没有 为这些认证工作。
对此的解决方案是所谓的刷新令牌。目前在Identity 2.0或OWIN中没有默认实现。但我找到了两篇博文,其中包含一个解决方案: