Monday, January 9, 2012

AJAX requests and authentication

Been scratching my head today over this, I have a site with windowsauthentication and a few ajax wcf service methods.

One method is supposed to be used by a specific user depending on what page its located on, so naturally I just added the following piece of code to my service method:

if(HttpContext.Current.User.Identity.Name == whatever)
{
// Do my stuff
}

This worked fine in IE, and sometimes in chrome, but firefox notoriously refused to send the authentication headers causing Identity.IsAuthenticated to be false all the time, making the user be anonymous for the request.

Turns out all that is needed is to is to set the response status to 401, and the browser will retry the request sending the credentials from the session, this is all obvious, what was difficult to figure out is how you achieve that.

Well you do it like so (note the difference from a regular browser page request where you would just set httpcontext.response.statuscode):

if(!HttpContext.Current.User.Identity.IsAuthenticated)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Unauthorized;
return;
}

Now I can have both unsecured and secured ajax methods in the same service.

Also, im still not sure if this is the correct way of doing things, so if anyone know a better way to achieve the same thing (like some attribute I can decorate my methods with I don’t know about), please let me know!