title: Set Principal/User Context to a User Object
body: <p>My WebAPI 2 application has a custom authorization filter which checks for an access token. If the token is present, and the API has the attribute, then I check if there exists a user which maps to that token.</p>
  
  <p>Due to the nature of the API, most methods run in the context of a particular user (i.e. "POST api/profile" to update a user's profile). In order to do this, I need information on the target user which I get from the access token.</p>
  
  <p><strong>[Current Implementation, happens within attribute of type AuthorizeAttribute]</strong></p>
  
  <pre><code>if( myDBContext.MyUsers.Count( x =&gt; x.TheAccessToken == clientProvidedToken ) ){
      IPrincipal principal = new GenericPrincipal( new GenericIdentity( myAccessToken ), new string[] { "myRole" } );
      Thread.CurrentPrincipal = principal;
      HttpContext.Current.User = principal;
      return true;
  }
  </code></pre>
  
  <p>This works fine, and I'm able to then use the access token to do a second lookup in the Method. <strong>But since I already do a lookup at auth time, I don't want to waste another DB call</strong>.</p>
  
  <p><strong>[What I'd like to do (but obviously doesn't work)]</strong></p>
  
  <pre><code>MyUser user = myDBContext.MyUsers.FirstOrDefault( x =&gt; x.TheAccessToken == clientProvidedToken );
  if( user != null ){
      // Set *SOME* property to the User object, such that it can be
      // access in the body of my controller method
      // (e.g. /api/profile uses this object to load data)
      HttpContext.Current.User = user;
      return true;
  }
  </code></pre>