I have a MVC project with uses Identity. This enables users to sign up to the site and create a profile.
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.
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.
Controller:
[BasicAuthentication]
public void Post([FromBody]string value)
{
// Get username from request for database lookup?
}
Filter:
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);
}
}
}
}
Edit:
I found the username using :
System.Threading.Thread.CurrentPrincipal;