Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core 2 Validating bearer token

I am struggling to find an exact way of validating my OAuth bearer token which is passed when a request is sent to the API am working on which is a Asp.Net core project.

The purpose here is to extract the bearer token and Validate it and if all is fine then continue with the request.

So far my findings have come across the following

  • JWT bear token authorization which mostly talks about access_token

  • Asp.Net core security middleware

  • Custom Authorize attribute which handle this.

I am not really sure how I can achieve my validation? Should I extract the bearer token and then create a custom validating method?

Ideally would like the [Authorize] attribute to handle this.

Suggestions please?

like image 553
KJSR Avatar asked Apr 08 '26 21:04

KJSR


1 Answers

Well finally after more research I finally found that custom AuthorizationHandler is a more suitable solution as suppose to using custom Authorize attributes which is not suggested in Asp.Net Core.

It was simple to setup and I am able to extract my Bearer token from the header for further authorization with OAuth.

Here is a my approach:

public class CustomAuthorizationHandler: IAuthorizationHandler
{
   public Task HandleAsync(AuthorizationHandlerContext context)
   {
       var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
       string authHeader = authFilterCtx.HttpContext.Request.Headers["Authorization"];
       if (authHeader != null && authHeader.Contains("Bearer"))
       {
          var token = authHeader.Replace("Bearer", "");
          // Now token can be used for further authorization
       }

       throw new NotImplementedException();
    }
}

Lastly registering the handler in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();
}
like image 102
KJSR Avatar answered Apr 10 '26 13:04

KJSR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!