2
votes

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?

2
Have you identified which flow you want to use? - Austin T French
@AustinTFrench as mentioned would ideally like to go the attribute way. However, even creating custom auth attribute in asp.net core is somewhat limited? - KJSR
attribute key? So specific grants in your JWT? I'd consider the Authorization grant, and get the additional grants via the API. And .NET core isn't limited, as much as it has changed a lot. Core 2 uses different libraries and methods (even in start up configuration) than 1.0, and 2.3 changed it again. Who knows what Core 3 will do... - Austin T French
@AustinTFrench can you explain more about the Authorization grant? - KJSR
There's a ton out there (check the spec or start at oauth.net/2/grant-types/authorization-code ), and we would go way into the weeds in comments - Austin T French

2 Answers

4
votes

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>();
}
0
votes

I think to put the following code snippet inside ConfigureServices() should be able to validate your access_token after installing Microsoft.AspNetCore.Authentication.JwtBearer NuGet package:

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                //options.SaveToken = true;
                options.MetadataAddress = ValidationEndPoint;
                options.RequireHttpsMetadata = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,

                    ValidIssuer = tokenIssuer,
                    ValidAudiences = new[] { clientId },
                    ValidAudience = null
                };
            });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("MyPolicy", policy =>
            {
                policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                policy.RequireAuthenticatedUser();
            });
        });

remember to put app.UseAuthentication() and app.UseAuthorization() in the Configure() method. And add [authorize] to your controller API.