2

I have an existing asp.net mvc website that uses basic forms authentication. The site has a login page that posts back to a login action, which logs the user in via FormsAuthentication.SetAuthCookie(). I am looking to add an api to the site, as an mvc2 area, where users would be authenticated based on a token passed as an http header. This area will consist of only json actions, so redirecting the user to a login page doesn't make sense. Instead, I want the users to just pass a token along with each request. That token is mapped to each user account and the user would be authenticated automatically.

I'm struggling with where to put this logic. At this point, the best choice seems to be adding the header lookup logic and authentication to the Global.asax in the Application_AuthenticateRequest method. I want to avoid needing to redirect the user after calling FormsAuthentication.SetAuthCookie(), though. I want the login action to be transparent to them.

Am I approaching this the wrong way?

As a side note: Requiring a username/password for api requests is not possible, as the site has a mix of users. Some joined using OpenID while the rest joined with a username/password.

2 Answers 2

4

Went down the road of adding header lookup to the Application_AuthenticateRequest event in Global.asax. The code looks something like:

private const string AuthorizationHeader = "Authorization";

if (!string.IsNullOrWhiteSpace(request.Headers[AuthorizationHeader]))
{
  try
  {
    // Remove Basic from beginning and then decode the string
    var token = request.Headers[AuthorizationHeader].Substring(6);
    token = new ASCIIEncoding().GetString(Convert.FromBase64String(token)).Split(':')[0];

    return UserService.FetchByApiToken(token);
  }
  catch
  {
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Don't reinvent the wheel.

3 Comments

unfortunately, I am not using WCF and to be honest... I don't want to. It looks like an over architected mess that will most likely be replaced by something else in 1-2 years... The site is not enterprise and does not require that level of complexity
Oh, I feel you 100% as I'm in the depth of one of those enterprisey projects. But the story for the WCF rest services is pretty clean. I'd look at the starter kit before I passed judgement.
Web API is out as the new way to do REST services. Looks like WCF has been surpassed as preditcted. Way over-architected for the problem domain indeed (not to say it doesn't have its very valid scenarios). :)

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.