saille
saille

Reputation: 9191

ASP.NET Problem Caching Roles In Cookie

I'm using ASP.NET Roles with a special role "Must Change Password". If a user has not changed their password for more than 90 days, they are automatically added to this role. This happens during the user login process. Authorization rules then deny that role access to all of the application except the "change password" page.

Generally this works great, but there is a problem when the role cache cookie is used to cache roles. What happens is during the login process, the password last changed date is checked, and if > 90 days, the user is added to the "Must Change Password" role. In the same page request, I subsequently call Roles.IsUserInRole("Must Change Password") to decide whether to redirect the user to the Change Password page or not. This is where it falls down - it seems that with the role cache cookie enabled, Roles.IsUserInRole("Must Change Password") doesn't realise that I have changed role mappings for this user, and returns false. However, on the next page request, Roles.IsUserInRole("Must Change Password") returns true.

This behaviour is fixed by setting cacheRolesInCookie="false", but that seems a high price to pay. Is there another way to fix this problem?

Upvotes: 0

Views: 1457

Answers (3)

Andrej Golcov
Andrej Golcov

Reputation: 648

Another , IMHO more elegant, solution is to cast HttpContext.User to RolePrincipal and call SetDirty method after adding a new role to the user (read more on RolePrincipal.SetDirty).

The next call of IsInRole or GetRolesForUser methods should trigger request to your default RoleProvider.

Upvotes: 1

saille
saille

Reputation: 9191

Actually, I've found the problem - it is not a problem with caching roles in cookies, but rather a problem with Roles.IsUserInRole(). If I use the overload Roles.IsUserInRole(username, role) then it works fine, with or without roles cached in a cookie.

Upvotes: 0

slolife
slolife

Reputation: 19870

Since you said that the problem exists in the same request, how about also setting an item in the HttpContext.Current.Items collection to indicate that the user must change their password, and check both the cookie and the HttpContext.Current.Items collection later on in the code?

Upvotes: 0

Related Questions