Search code examples
c#apiaccess-token

How to add a token to my api using mvc 4?


How might I add a secure token to access the api so that not everyone can get it. I would like the format of my url to be : api.example.com/*key*/person?id=5 and when I send this request it will return if the key is valid if not valid it will return invalid login. I am using mvc 4 api and C# to make this and a link or something will be great.


Solution

  • The key phrase you are looking for most like is that you need to create and add a custom ActionFilterAttribute.

    A quick search on google turned up this blog article which talks about doing this exact thing (along with some other filters).

    Just in case there's some link rot here's the gist (excerpts from the blog article):

    1. Come up with some scheme for generating/verifying the API tokens

    2. Create you attribute that uses the verification from step 1 in an attribute

    3. Add the attribute to the global configuration

    CODE

    public class TokenValidationAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(HttpActionContext actionContext)
      {
       string token;
    
       try
       {
        token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
       }
       catch (Exception)
       {
        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
        {
         Content = new StringContent("Missing Authorization-Token")
        };
        return;
       }
    
       try
       {
        //This part is where you verify the incoming token
        AuthorizedUserRepository.GetUsers().First(x => x.Name == RSAClass.Decrypt(token));
        base.OnActionExecuting(actionContext);
       }
       catch (Exception)
       {
        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
        {
         Content = new StringContent("Unauthorized User")
        };
        return;
       }
        }
      }
    }
    

    To make these action filters global, the following code in the Global.asax Application_Start() will do the trick:

    var config = GlobalConfiguration.Configuration;
    config.Filters.Add(new TokenValidationAttribute());