Wednesday, March 29, 2017

One problem in configuring OAuth authentication for Web API 2

Recently I faced with the following problem when tried to configure OAuth token-based authentication for Web API 2 project. I used the following article as a general guide: Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. When you create new Web API project VS creates also default routes configuration which look like this:

   1: public static class WebApiConfig
   2: {
   3:     public static void Config(HttpConfiguration config)
   4:     {
   5:         config.MapHttpAttributeRoutes();
   6:  
   7:         config.Routes.MapHttpRoute(
   8:             name: "DefaultApi",
   9:             routeTemplate: "{controller}/{id}",
  10:             defaults: new { id = RouteParameter.Optional }
  11:         );
  12:     }
  13: }

And if we will follow the same technique as described in the article above for configuring OAuth authentication we will add the following OAuth config to the startup:

   1: public static class OAuthConfig
   2: {
   3:     public static void Config(IAppBuilder app)
   4:     {
   5:         var OAuthServerOptions = new OAuthAuthorizationServerOptions()
   6:         {
   7:             AllowInsecureHttp = true,
   8:             TokenEndpointPath = new PathString("/token"),
   9:             AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
  10:             Provider = new AuthorizationServerProvider()
  11:         };
  12:  
  13:         app.UseOAuthAuthorizationServer(OAuthServerOptions);
  14:         app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
  15:     }
  16: }

where AuthorizationServerProvider is your custom token provider. Note on TokenEndPointPath property of OAuthServerOptions which contains path to the token generation end point. Now if you will try to get token by accessing http://example.com/token (where instead of http://example.com you need to use your web api host) you will get the following error:

{
  "Message": "No HTTP resource was found that matches the request URI 'http://example.com/token'.",
  "MessageDetail": "No type was found that matches the controller named 'token'."
}

The problem is fixed by commenting out default routing configuration in WebApiConfig shown above:

   1: public static class WebApiConfig
   2: {
   3:     public static void Config(HttpConfiguration config)
   4:     {
   5:         config.MapHttpAttributeRoutes();
   6:  
   7: //            config.Routes.MapHttpRoute(
   8: //                name: "DefaultApi",
   9: //                routeTemplate: "{controller}/{id}",
  10: //                defaults: new { id = RouteParameter.Optional }
  11: //            );
  12:     }
  13: }

But please note that after that it will be mandatory to decorate your controllers and actions by RoutePrefix and Route attributes correspondently;

   1: [RoutePrefix("Account")]
   2: public class AccountController : ApiControllerBase
   3: {
   4:     [AllowAnonymous]
   5:     [HttpPost]
   6:     [Route("Register")]
   7:     public IHttpActionResult Register(UserRegistrationModel userRegistration)
   8:     {
   9:         ...
  10:     }
  11: }

After that token generation endpoint should start work.

No comments:

Post a Comment