Jer*_*emy 5 c# asp.net asp.net-mvc angularjs asp.net-identity-2
我正在编写一个使用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"));
}
Run Code Online (Sandbox Code Playgroud)
认证控制器:
[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";
}
Run Code Online (Sandbox Code Playgroud)
Authenticate方法效果很好.我的webapp从请求中获取一个令牌,我可以将其设置为Authorization-header(例如,在$ http for angular apps中).对[授权]注释函数的后续调用将正确返回.但是,如果我调用Logout,它将正确返回"OK"字符串,但不会使令牌无效.如果我在调用Logout后调用Authorize-method,我仍然会得到正确的值而不是预期的401 - Unauthorized.
似乎我得到了(持票人)令牌的基本概念错误,这就是为什么它不起作用.我把它留在这里以防有人绊倒同样的问题:
令牌不能被撤销或无效 - 至少不能使用ASP.NET Identity 2.0.SignOut不适用于那些类型的身份验证.
对此的解决方案是所谓的刷新令牌.Identity 2.0或OWIN目前没有默认实现.但我找到了两篇博文,其中包含一个解决方案
| 归档时间: |
|
| 查看次数: |
4791 次 |
| 最近记录: |