2

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;
  }
}

1 Answer 1

1

You can skip the parameter altogether and use httpContext.Request.IsAjaxRequest

public class MyAuthorizeAttribute : AuthorizeAttribute
{
  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;
    }

    if (!httpContext.Request.IsAjaxRequest()) 
    {
         // do your thing in the DB
    }
Sign up to request clarification or add additional context in comments.

1 Comment

What I need is to distinguish between user initiated and not user initiated requests, your solution presumes that all ajax requests are done without the user's knowledge, which isn't the case for me. Will update my question to be more precise about this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.