I'm trying to find a way to provide an administrator of the application I'm developing with an effective way to quickly lockout a user who has either left the company or has been identified as behaving in a way that would warrant an immediate lockout or use of the application.
So far it looks like I can;
//enable the account to be locked out
_userManager.SetLockoutEnabledAsync(ApplicationUser user, true);
//Set an arbitrary date way into the future to lock them out until I want to unlock them
_userManager.SetLockoutEndDateAsync(ApplicationUser user, "01/01/2060");
But the above doesn't resolve if the user has a cookie with an expiration time of 30 min. Meaning, the user can continue to use the app if they have already authenticated and are within the default time I'm using for cookies to remain valid.
Is there a user manager method that changes the 'check' that cookie is bounced against? I'm assuming the [Authorize] attribute tag is checking the cookie against something within Identity that is not exposed in the table. Wondering how I change the 'check' values so that they don't match cookie session?
You could do this with some middleware that runs against every request. First create your middleware class, something like this:
public class UserDestroyerMiddleware
{
private readonly RequestDelegate _next;
public UserDestroyerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
if (!string.IsNullOrEmpty(httpContext.User.Identity.Name))
{
var user = await userManager.FindByNameAsync(httpContext.User.Identity.Name);
if (user.LockoutEnd > DateTimeOffset.Now)
{
//Log the user out and redirect back to homepage
await signInManager.SignOutAsync();
httpContext.Response.Redirect("/");
}
}
await _next(httpContext);
}
}
And an extension to make it easy to configure:
public static class UserDestroyerMiddlewareExtensions
{
public static IApplicationBuilder UseUserDestroyer(this IApplicationBuilder builder)
{
return builder.UseMiddleware<UserDestroyerMiddleware>();
}
}
And now in your Configure
method in Startup.cs
, add this line after Identity
has been set up:
app.UseUserDestroyer();
Now this middleware should run on every request checking if the user should be logged out. You may want to streamline this process by making it not hit the database on every request and instead use some sort of cached list of recently deleted users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With