所以我有一个ASP.NET MVC 6+AngularJS应用程序,它具有自定义用户身份(不使用EF),可以在没有EF等的情况下根据不同的数据库对用户进行身份验证。
我有几个用户身份工作所需的一些接口的自定义实现。
-
IUserStore<MyUser>
,IUserPasswordStore<MyUser>
-只实现了几个方法来使用我的自定义代码获得用户。没有什么有趣的。 -
IPasswordHasher<MyUser>
实现,用于使用我自己的密码解密代码验证散列密码等。 -
用于创建包含一些自定义声明的
ClaimsPrincipal
对象的IUserClaimsPrincipalFactory<MyUser>
实现。
在用于登录和注销的AccountControler
中,我使用的是:
SignInManager.PasswordSignInAsync(username, password, true, shouldLockout: false)
SignInManager.SignOut();
其中SignInManager是我的自定义管理器-SignInManager<MyUser>
。
到目前为止,一切都很顺利。
现在在Startup.cs
中,我有:
public void ConfigureServices(IServiceCollection services)
{
...
services.TryAdd(ServiceDescriptor.Scoped<IUserStore<MyUser>, ApplicationUserStore>());
services.TryAdd(ServiceDescriptor.Scoped<IUserPasswordStore<MyUser>, ApplicationUserStore>());
services.TryAdd(ServiceDescriptor.Scoped<IPasswordHasher<MyUser>, ApplicationSitePasswordHasher>());
services.TryAdd(ServiceDescriptor.Scoped<IUserClaimsPrincipalFactory<MyUser>, MyUserClaimsPrincipalFactory>());
services.AddIdentity<MyUser, MyUserRole>();
services.ConfigureIdentity(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonLetterOrDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 1;
options.User.RequireUniqueEmail = false;
options.User.UserNameValidationRegex = string.Empty;
});
services.ConfigureIdentityApplicationCookie(options =>
{
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.AuthenticationScheme = IdentityOptions.ApplicationCookieAuthenticationScheme;
options.AutomaticAuthentication = true;
options.LoginPath = PathString.Empty;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
{
...
app.UseIdentity();
...
app.UseMvc(routes => .... )
}
当用户在angular http异步调用中获得401时,我也有自定义的授权属性处理。这个想法是这样的:
public class MyAuthorize : ActionFilterAttribute
{
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
bool isAuth = bool isAuth = context.HttpContext.User.Identity.IsAuthenticated;
bool isFromClient = ...
string loginPath = ...
if (!isAuth && isFromClient)
{
...
}
else if (!isAuth && !isFromClient)
{
context.HttpContext.Response.Redirect(loginPath);
}
else
{
await next();
}
}
}
问题:即使我的cookie在30天后过期(在这种情况下),一段时间后我仍然没有经过身份验证(context.HttpContext.User.Identity.IsAuthenticated
属性为false
),并且由于我在MyAuthorize
属性中的逻辑,我被重定向到登录页面。
IIS池中的空闲超时也是0。
如何使我的自定义用户身份在很长一段时间内保持经过身份验证的用户?
"一段时间"是否约为"登录后30分钟"?:)
实现IUserSecurityStampStore<User>
接口。
详细描述是在ASP.NET 5 Identity 3中,用户在一段时间后退出