Expire user session (other than current user) - c#

I am adding a custom Disabled column to my AspNetUsers table so that an administrator can temporarily disable an account. (It looks like LockoutEndDateUtc doesn't work exactly as I need.)
But what if an administrator disables an account while the user is logged in? Rather than having to check if the current user account is disabled on every request, I am looking for a way to expire that user's session so that the next request will require them to log in.
I believe this is controlled by a cookie. Is this possible?

Actually this can be automatically done. In ASP.NET Identity in the user store there is a property called SecurityStamp. When you change this the user is forced to re-authenticate with the next request. This is because this field is used to generate the authentication token (cookie in your case). The framework has methods that are built into it for changing this either directly UpdateSecurityStampAsync as well as or indirectly. A good example of when it is changed indirectly is when the identity's password is updated through the framework (ie. calling UpdatePassword or RemovePasswordAsync), or when enabling 2 factor authentication for the identity.
The method to change the security stamp is can be found in the UserManager and is called UpdateSecurityStampAsync. From the documentation:
Generates a new security stamp for a user, used for SignOutEverywhere functionality.

Related

How to refresh roles/claims of another user in ASP.NET

Hi we're having an issue with ASP.NET Identity.
We have an admin page that allows us to affect users to roles. (Admin etc).
The issue is when we affect a role to someone it doesn't apply for him until he logs out/logs back in.
We tried putting
services.Configure<SecurityStampValidatorOptions>(options =>
{
options.ValidationInterval = TimeSpan.Zero;
});
But it causes too many issues with cookies being passed at each request etc.
Is there any way to either :
Force logout another user
Refresh his claims without relogging?
The only solution I have in mind atm is to use something like a list of users to be updated somewhere (redis for exemple) and check this list in a middleware and refreshSigninAsync() if the user is in the list.
You were close, but I'd recommend you change the configuration.
I've added additional explanation on why you want to do this, in case someone wants to understand the thought process.
The problem:
When your user signs into the app they receive a cookie, but when an account is logged out, the user still has the valid cookie, so they aren't really signed out.
How to force sign-out:
Since a cookie gets re-used for as long as it's valid, you need a way to invalidate a cookie. You invalidate a cookie through a security stamp.
Configure Identity so that it periodically re-validates the cookie. It compares the security stamp in the cookie to the database version, and, if it fails, your user needs to reauthenticate.
Add the following configuration to your services:
services.Configure<SecurityStampValidatorOptions(opts => opts.ValidationInterval = System.TimeSpan.FromMinutes(1));
Now, you simply have to use the UserManager to find the user in the userstore, update the roles (or do whatever), then call the UpdateSecurityStampAsync(user) method. For example:
public async Task<IActionResult> OnPostUpdateRolesAsync(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
// do stuff
await _userManager.UpdateSecurityStampAsync(user);
return RedirectToAction(nameof(SomePage));
}
Now that causes the user to be signed out the next time the cookie is revalidated and is forced to re-authenticate.
Notes:
This is certainly a destructive method in terms of user experience, since any HTTP request that the user does will get terminated afterwards.
Also, it's not really an immediate sign-out, only from the perspective of the application is it immediate. The user does not know when he has been signed out, that will only be apparent when he makes an http-request.

ASP.NET Core. How can I invalidate JWT-Token after password change

Sorry for my bad English. I'm writing an application in ASP.NET Core using Vue.JS for client-side. For authenticate user I'm using JWT and ASP.NET Identity. I have a method for change the password. But I can't understand: How to invalide token after password change? I want that the user authenticated in another browser will logout after that. Is there a man who haved a problem like this?
You normally don't invalidate JWT's because they are meant to be short-lived access tokens and therefore after the password change, request for new token will prompt the user to reenter credentials.
If you do absolutely need to invalidate the JWT immediatelly after password change - you need to look into Introspection where your backend api essentially has a backchannel to your token issuer and it can then re-validate token every request. This way if you invalidate token at the issuer side - it will reflect on the api side immediately.
I've been thinking about this and the inability to invalidate a JWT that's already out there may not be built into anything, but is possible.
Here's the narrative: You have an alarm system installed that can be controlled via web and your ex-S/O is logged in to your previously shared account. They are upset and they keep enabling the alarm at random times.
If the web app uses JWTs to store session, you could change your password but the JWT your ex possesses will still be usable for a period of time until the timeout is reached.
Solution 1: short timeout. but what if you want to stay logged in for longer periods (such as a password manager)
Solution 2: logout ALL users by changing the Signing Key of your Certified Authority, basically invalidating ALL JWTs across the board. This is still a less ideal route as I'm sure you can imagine.
Solution 3: track the current JWT for each user in your Users table. If the JWT they possess is different from the current one, then they aren't authenticated. If the user logs out, nullify the stored JWT-data in your Users table which would equally unauthenticate JWTs for that user and force a relogin.
I'd also recommend storing a bool of "logged in" for the user. DO NOT RELY ON THIS. This would be a value to set to true when they log in, set it to false when they log out, and validate the value is 'true' if they ever pass you a JWT. This will ensure that the moment they logout they are forced to reauthenticate.
Assuming you go with solution 3:
When storing JWT data for this solution, I'm leaning towards not storing the entire JWT because it's rather large text to begin with. Alternatively just store the JWS (JWT Signature) which will make the stored value both smaller and unusable if captured for any reason.
Next, it's a hash to begin with so we could just store the last maybe 9 values (9 because int32 max is 2147483647). We just need a bit of uniqueness, not much.
Next, we could avoid the string comparison for validating that the JWS passed is the active one if we use regex to pull the integers out of the JWS and again take maybe the first 9 numbers you encounter.
Following this method, and returning to the narrative, if you were to log out your user would be marked as logged out resulting in both yourself and your S/O being required to reauthenticate. (assuming you've changed your password you're golden, otherwise it's time to contact Customer Support)
If you were to log back in, you'd get a fresh JWT and a new signature would be stored in the Users table. If your S/O were to try to use the site, they would not be authenticated with the their old JWT and would be forced to sign back in.
Trade-off: If we only store the JWS, or a part of it as I suggested, multiple users can't be signed in to the same account at once. How you feel should feel about that really depends on your app.

How to remove cookies asp.net core authorization

If I delete a user that has cookie based authorization, the will still have access to the system until he presses the logout button. Or until the cookie expires.
How to fix the situation.
This is a general problem of claims based authentication when removing access for users. Due to how it is designed, the database is not accessed on every request to verify the access. Instead, the cryptographically signed cookie is considered to be the source of truth. So when the access is removed in the database, the cookie is still valid and it is not trivial how to update the user’s cookie in that case. Since it is a cookie that is stored on the client side, you also can’t just log out the user remotely.
But there is a mechanism in ASP.NET Core Identity that enforces the cookie authentication scheme to re-validate an identity on a certain interval. You can configure this like this in your Startup’s ConfigureServices method:
services.Configure<SecurityStampValidatorOptions>(options =>
{
options.ValidationInterval = TimeSpan.FromMinutes(10);
});
This would set the interval to 10 minutes. So every 10 minutes, a user accessing your site with an existing cookie would be validated, and a new cookie would be issued. This process is completely silent and happens behind the scenes.
Depending on how strictly you want to enforce this, you would have to lower this interval further. I would generally recommend you to still leave it at a certain duration. Otherwise you are defeating the purpose of the cached identity.
You should also consider how problematic it really is if a user still has access to your site, and how time critical a user removal would have to be. Depending on your application, it’s also not unlikely that you retrieve the user entity within your critical actions anyway, so this would automatically fail in this case, without you having to deny access by removing the cookie.

IdentityServer3 requiring a role when the user logs in (as additional credential)

I have a system where if the user logs in as Joe with the role "Readonly" then he will be granted access only to read things (fairly obviously) however if he logs in as Joe with the role "Administrator" then he will have access to do administrative functions. However I want him to have to relogin if he wishes to change from the Readonly role to the Administrator role so that he could potentially leave his account logged in as Readonly on a display screen or something without fear of someone hijacking his Administrator priviledges.
Now I also need to be able to log in a Web client via an implicit grant or another server via a code grant and have that service be able to use the same roles as well (while still requiring Joe to log in as the particular role if he isn't already authenticated.)
Now I have been trying to do this with IdentityServer3 but I cant seem to get the role information to be part of the authentication for the user, I tried adding an acr_value of role:ReadOnly to the token request (which then turns into an authentication request if the user is not logged in) but if they log in with the acr_value of ReadOnly and then come back to log in with the acr_value of Adminstrator it just lets them on in because they are already authenticated as the user.
Any tips on what I should be using instead of what I am doing or how I might be completely off base in this OAuth2/OpenID Connect world?
I finally figured it out so for others who might want to do the same thing here is what I did.
First you have build a custom UserService that looks in the acr_values for extra information. Then create a claim for that extra information in the AuthenticateResult.
Second you have to override the ClaimProvider to include your custom claim set in step one in the tokens generated.
Next you need a CustomRequestValidator in order to check if a new acr_value is being set compared to the one you have stored in token being currently used. If it has changed and you want to force the user to reauthenticate you can set 'request.PromptMode = "login";'
And that is it, using that set of steps I can now authenticate a user using 3 values (username, password, and role) and if the role requested changes I can require them to reauthenticate.
Works swimingly.

anonymous Identification enabled true not working

I need support... I set up in web.config the tag:
<anonymousIdentification enabled="true" cookieless="UseCookies" />
with profile, membership and forms authentication with all the neccesary information. If I log a User with the proper credentials I see in aspnet_Users table the logged user.
On the other hand, when I access the website - and the cookie is set up for anonymous in the browser with info .ASPXANONYMOUS - everything worked ok in the browser but not in the database.
aspnet_Users table only register logged users but not anonymous users on it. any help will be appreciated.
brgds, sebastian.
additional info: pro.asp.net4 in csharp edition 2010 says:
"aspnet_Users table Lists user names and maps them to one of the applications in
aspnet_Applications. Also records the last request date and time
(LastActivityDate) and whether the record was generated automatically for
an anonymous user (IsAnonymous). Anonymous user support is discussed
later in this chapter (in the section “Anonymous Profiles”)."
"ASP.NET provides an anonymous identification feature that fills this gap. The basic idea is that the
anonymous identification feature automatically generates a random identifier for any anonymous user.
This random identifier stores the profile information in the database, even though no user ID is
available. The user ID is tracked on the client side using a cookie (or in the URL, if you’ve enable
cookieless mode). Once this cookie disappears (for example, if the anonymous user closes and reopens
the browser), the anonymous session is lost and a new anonymous session is created.
Anonymous identification has the potential to leave a lot of abandoned profiles, which wastes space
in the database. For that reason, anonymous identification is disabled by default. However, you can
enable it using the element in the web.config file"
this is what I´m looking for...
the asp.net sql membership api only logs to that table if the user actually logs in. If it is an anonymous user that is just passing by the site, it will not log to that table. They must login by calling Memberhip.ValidateUser(...)
User won't appear in aspnet users AFAIK, but the stuff you track should be in the profiles table. My understanding is the user data gets created when the user registers and then the profile data gets migrated.

Categories

Resources