0
votes

How to secure WEB API with security token without using any login. We want to use this WEB API in windows service to get data from other db server. can't use user login or roles We try [Authorize] attribute, but all in vain. I try this

 [MyAuthorize]
    public class MasterDataController : ApiController
    {
        [HttpGet]
        public string myMethod(string Name)
        {
            return Name;
        }
    }

MyAuthorize is

 public class MyAuthorizeAttribute : AuthorizeAttribute
    {
public override void OnAuthorization(AuthorizationContext Context)
  {
   //Some logic to validate token...
  }
}

WebApiConfig.cs is

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new AuthorizeAttribute());
            config.Routes.MapHttpRoute(
               name: "ActionGetPatientAndAppointmentInfo",
               routeTemplate: "TestAPI/{controller}/{action}",
               defaults: new 
               {
                   controller = "MasterData",
                   action = "myMethod"
               }
           );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional}
            );


        }
    }

When we test method in REST Client with Authorization header

enter image description here

But OnAuthorization method itself is not executing. Response always show Unauthorized request.

1

1 Answers

0
votes

this is the perfect scenario for OAuth2. You need to be able to generate a token and then to secure the API endpoints so only calls with this token in the authorization header will be fulfilled.

I suggest looking into using something like Owin which will give you everything you need.

This is application level authorization so you will have two keys, a ClientID and a ClientSecret which will be used to generate the token. This way you can even build multiple applications using the same API each identified through their own set of keys.

Here is a detailed article, albeit a bit older showing how to do it from scratch:

https://eidand.com/2015/03/28/authorization-system-with-owin-web-api-json-web-tokens/