title: Access username from basic authentication
body: <p>I have a MVC project with uses Identity. This enables users to sign up to the site and create a profile.</p>
  
  <p>I have a separate WebAPI class to allow Embedded GSM devices to communicate with the server. Users are able to sign up and add many GSM units to their profile.  I've had to use a Basic Authentication filter for the embedded GSM devices as it they are unable to cache a token / cookie.</p>
  
  <p>My question is, how do i look up the username of the request within a webAPI controller?  i've tried accessing the user with RequestContext.Principal as per suggestions, but it returns null.</p>
  
  <p>Controller:</p>
  
  <pre><code> [BasicAuthentication]
   public void Post([FromBody]string value)
   {
      // Get username from request for database lookup?
   }
  </code></pre>
  
  <p>Filter:</p>
  
  <pre><code>public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
  {
  
      public override void OnAuthorization(HttpActionContext actionContext)
      {
          if (actionContext.Request.Headers.Authorization == null)
          {
              actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
          }
          else
          {
              string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
              string decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
              string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
              string username = usernamePasswordArray[0];
              string password = usernamePasswordArray[1];
  
              if (GSMSecurity.Login(username, password))
              {
                  Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);
              }
              else
              {
                  actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
              }
          }
      }
  }
  </code></pre>
  
  <p>Edit:</p>
  
  <p>I found the username using :</p>
  
  <p>System.Threading.Thread.CurrentPrincipal;</p>