I have a custom AuthorizeAttribute in my application which takes an input parameter bool UserIsOnline. This parameter is used to increase a table field that holds information about the time of the last user interaction, i.e. for ajax requests that are executed behind the scenes I supply a false and for regular request, or user initiated ajax requests, a true value.
This works most of the time but not always. I've read that AuthorizeAttribute is not thread safe which makes me wonder whether this UserIsOnline parameter is wrong because it gets modified by another process before being handled. How would I go about to solve this problem? Should I not use AuthorizeAttribute for this action?
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private MyMembershipProvider _provider = new MyMembershipProvider(); // this class is thread-safe
private bool _userIsOnline = true;
public bool UserIsOnline { get { return _userIsOnline; } set { _userIsOnline = value; } }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
// Check if user is authenticated
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
// Check that the user still exists in database
MyMembershipUser myUser = (MyMembershipUser)_provider.GetUser(user.Identity.Name, _userIsOnline);
if (myUser == null)
{
// User does not exist anymore, remove browser cookie
System.Web.Security.FormsAuthentication.SignOut();
return false;
}
return true;
}
}