Only validate JWT if bearer header is present

Viewed 1362

I have a few API endpoints (.net core mvc) that will use the logged-in user (JWT) if the user is logged in, but anyone is allowed to call the method. By using [AllowAnonymous] together with [Authorize] I get the functionality I'm looking for but if the sent JWT is expired, I'm not getting a 401, but instead it is treated as an anonymous request.

I need the authorization logic to treat the endpoint as it was [Authorize] only if there is a Authorization: Bearer header, meaning that if the token is expired, it should return a 401

This functionality is only needed on a few endpoints and not on a full controller

I've tried the combination of [AllowAnonymous] + [Authorize].

Also tried RequireAssertion when creating the policy, but doesn't seem to have been meant for this

The method I'm using for testing:

[HttpPost]
[Route("testToken")]
[AllowAnonymous]
[Authorize(Policy = AuthFilterConvension.POLICY_AUTHORIZE_WHEN_HAS_BEARER)]
public async Task<IActionResult> testToken()
{
    var user = await _signInManager.UserManager.GetUserAsync(HttpContext.User);
        return Ok(new {result = user});
    }

Setting up auth to support both cookies + JWT:

services.AddAuthorization(o =>
            {
                o.AddPolicy(AuthFilterConvension.POLICY_AUTHORIZE_WHEN_HAS_BEARER, b =>
                {
                    b.RequireRole("Admin");
                    b.RequireAuthenticatedUser();
                    b.AuthenticationSchemes = new List<string> {JwtBearerDefaults.AuthenticationScheme};
                    
                });
            });
            services.AddAuthentication()
                .AddCookie()
                .AddJwtBearer(cfg =>
                    {
                        var issuer = Environment.GetEnvironmentVariable("JWT_ISSUER");
                        var tokenKey = Environment.GetEnvironmentVariable("JWT_TOKEN_KEY");

                        cfg.RequireHttpsMetadata = false;
                        cfg.SaveToken = true;

                        cfg.TokenValidationParameters = new TokenValidationParameters
                        {
                            RequireExpirationTime = true,
                            RequireSignedTokens = true,
                            ValidateAudience = true,
                            ValidateIssuer = true,
                            ValidateLifetime = true,

                            ValidIssuer = issuer,
                            ValidAudience = issuer,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey))
                        };
                    }
                );

I would expect the [Authorize] header to return 401 Unauthorized when using expired tokens instead of calling the method as anonymous. Is this possible to set up?

Update I created the attribute like this:

public class AuthorizeBearerWhenPresent : ActionFilterAttribute, IAsyncAuthorizationFilter
    {
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var headers = context.HttpContext.Request;
            
            //TODO: Test header
            var httpContext = context.HttpContext;
            var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();

            var authResult = await authService.AuthorizeAsync(httpContext.User, context,
                AuthFilterConvension.POLICY_AUTHORIZE_WHEN_HAS_BEARER);
            
            if (!authResult.Succeeded)
            {
                context.Result = new UnauthorizedResult();
            }
        }
    }

However, no matter what I'm sending to the authService it returns true. Doesn't matter if I send an invalid JWT header or no header. Shouldn't this be the correct way to get executed a policy?

3 Answers

Thank you for your suggestions. While I was implementing the solution posted by Bart van der Drift, I stumbled upon the combination of a custom header together with using the IAuthorizationPolicyProvider

This way I'm using a custom policy name which I then overrides:

The constants in AuthFilterConvension:

public const string POLICY_JWT = "jwtPolicy";
public const string POLICY_AUTHORIZE_WHEN_HAS_BEARER = "authorizeWhenHasBearer";

Setting up the policies:

services.AddAuthorization(o =>
            {
                o.AddPolicy(AuthFilterConvension.POLICY_JWT, b =>
                {
                    b.RequireRole("Admin");
                    b.RequireAuthenticatedUser();
                    b.AuthenticationSchemes = new List<string> {JwtBearerDefaults.AuthenticationScheme};

                });
            }); 

Add custom attribute:

    public class AuthorizeBearerWhenPresent : AuthorizeAttribute
    {
        public AuthorizeBearerWhenPresent()
        {
            Policy = AuthFilterConvension.POLICY_AUTHORIZE_WHEN_HAS_BEARER;
        }
    }

The name POLICY_AUTHORIZE_WHEN_HAS_BEARER is not configured, but only used as a key in my CustomPolicyProvicer:

public class CustomPolicyProvider : IAuthorizationPolicyProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly DefaultAuthorizationPolicyProvider _fallbackPolicyProvider;

        public CustomPolicyProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthorizationOptions> options)
        {
            _httpContextAccessor = httpContextAccessor;
            _fallbackPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
        }

        public async Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
        {
            if (AuthFilterConvension.POLICY_AUTHORIZE_WHEN_HAS_BEARER.Equals(policyName))
            {
                if (_httpContextAccessor.HttpContext.Request.Headers.ContainsKey("Authorization"))
                {
                    return await _fallbackPolicyProvider.GetPolicyAsync(AuthFilterConvension.POLICY_JWT);    
                }

                return new AuthorizationPolicyBuilder()
                    .RequireAssertion(x=>true)
                    .Build();
            }


            return await _fallbackPolicyProvider.GetPolicyAsync(policyName);
        }

        public async Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return await _fallbackPolicyProvider.GetDefaultPolicyAsync();
        }
    }

This way I can avoid doing custom handling of the JWT tokens

The following:

return new AuthorizationPolicyBuilder()
  .RequireAssertion(x=>true)
  .Build();

Is only used as a dummy "allow all"

You can create your own authentication logic by implementing the IAuthenticationFilter interface and inherit from ActionFilterAttribute:

public class MyCustomAuthentication : ActionFilterAttribute, System.Web.Http.Filters.IAuthenticationFilter
{
    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        HttpRequestMessage request = context.Request;
        AuthenticationHeaderValue authorization = request.Headers.Authorization;
         // Handle the authorization header
    }
}

Then in your controller, you can add the attribute either to the class or to specific methods.

[MyCustomAuthentication]
public async Task<IHttpActionResult> DoSomethingAsync()
{
    // ...
}

If the token is present, you will also have to manually validate the token. The code below is based on .Net Framework, so not sure if this also works for Core.

// Build URL based on your AAD-TenantId
var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/.well-known/openid-configuration", "<Your_tenant_ID>");

// Get tenant information that's used to validate incoming jwt tokens
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);

// Get Config from AAD:
var config = await configManager.GetConfigurationAsync();

// Validate token:
var tokenHandler = new JwtSecurityTokenHandler();

var validationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
    ValidAudience = "<Client_ID>",
    ValidIssuer = "<Issuer>",
    IssuerSigningTokens = config.SigningTokens,
    CertificateValidator = X509CertificateValidator.ChainTrust
};

var parsedToken = (System.IdentityModel.Tokens.SecurityToken)new JwtSecurityToken();

try
{
    tokenHandler.ValidateToken(token, validationParameters, out parsedToken);
    result.ValidatedToken = (JwtSecurityToken)parsedToken;
}
catch (System.IdentityModel.Tokens.SecurityTokenValidationException stve)
{
    // Handle error using stve.Message
}

Some more info and examples here.

You Could write a custom middleware to do so for example:

        private readonly RequestDelegate _next;

        public MyMiddleware(RequestDelegate next)
        {

            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, IConfiguration configuration)
        {
            if (httpContext.Request.Headers.ContainsKey("Authorization"))
            {

                var authorizationToken = httpContext.Request.Headers["Authorization"].ToString();

                if (!authorizationToken.StartsWith("bearer", StringComparison.OrdinalIgnoreCase))
                {
                    await UnauthorizedResponseAsync(httpContext);
                }
                else
                {
                    var token  =authorizationToken.Substring("Bearer".Length).Trim())

                   if (httpContext.Request.Path == "Some of your path")
                   {
                   // DO your stuff
                   await _next.Invoke(httpContext);
                   }
                }
            }
            else
            {
                await UnauthorizedResponseAsync(httpContext);
            }
        }

        private static async Task UnauthorizedResponseAsync(HttpContext httpContext)
        {
            httpContext.Response.StatusCode = 401;
            await httpContext.Response.WriteAsync("Unauthorized");
            return;
        }
Related