Custom Bearer Token Authorization for ASP.Net Core

Anton Swanevelder

Is this an acceptable implementation of a custom bearer token authorization mechanism?

Authorization Attribute

public class AuthorizeAttribute : TypeFilterAttribute
{
    public AuthorizeAttribute(): base(typeof(AuthorizeActionFilter)){}
}

public class AuthorizeActionFilter : IAsyncActionFilter
{
    private readonly IValidateBearerToken _authToken;
    public AuthorizeActionFilter(IValidateBearerToken authToken)
    {
        _authToken = authToken;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        const string AUTHKEY = "authorization";
        var headers = context.HttpContext.Request.Headers;
        if (headers.ContainsKey(AUTHKEY))
        {
            bool isAuthorized = _authToken.Validate(headers[AUTHKEY]);
            if (!isAuthorized)
                context.Result = new UnauthorizedResult();
            else
                await next();
        }
        else
            context.Result = new UnauthorizedResult();
    }
}

Validation Service. APISettings class is used in appSettings, but validation can be extended to use a database ... obviously :)

public class APISettings
{
    public string Key { get; set; }
}

public class ValidateBearerToken : IValidateBearerToken
{
    private readonly APISettings _bearer;

    public ValidateBearerToken(IOptions<APISettings> bearer)
    {
        _bearer = bearer.Value;
    }

    public bool Validate(string bearer)
    {
        return (bearer.Equals($"Bearer {_bearer.Key}"));
    }
}

Implementation

[Produces("application/json")]
[Route("api/my")]
[Authorize]
public class MyController : Controller

appSettings

"APISettings": {
"Key": "372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046"

}

Request Header

Authorization: Bearer 372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046
andrecarlucci

That would work, but it's kind of reinventing the wheel.

I good approach these days is to use JWTs, you can find more info about it here: http://www.jwt.io/

Some advantages are that it integrates quite nicely with asp.net core and you can also add some information to the token (username, role, etc). That way, you don't even need to access the database for validation (if you want to).

Also, storing keys in appsettings file could lead to accidentally adding them to your source-code manager (security). You could use user secrets for local development (or disable the key when environment = dev) and environment variables for production.

Here is one good example of how to use jwt with asp.net: https://jonhilton.net/2017/10/11/secure-your-asp.net-core-2.0-api-part-1-issuing-a-jwt/

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ASP.NET Core 2.0 combining Cookies and Bearer Authorization for the same endpoint

Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core

Bearer Token Authentication in ASP.NET Core

Asp.net core token based claims authentication with OpenIdConnect and angularjs: Bearer was forbidden

ASP.NET Core JWT Bearer Token Custom Validation

ASP.NET Core Custom Policy Based Authorization - unclear

Asp.Net Core custom authorization always ends with 401 Unauthorized

ASP.net Core 2.0 AzureAd Bearer JWT-Token Auth not fail on validate signature

Authorization for JWT bearer in Swashbuckle .NET Core 2

.NET Core Authorization - Constant 403 on JWT Bearer

Authorization token not binding in ASP.NET Core

setting asp.net CORE 2 authentication cookie while using bearer token authentication

Custom Authorization in Asp.net core 2.1 web api

Asp.Net Core 2 Validating bearer token

Set Bearer Token with nswag in ASP.NET Core 2.2

.NET STANDARD 4.7.2 Azure Bearer Token Authorization

Asp Net Core 3.1 Authorization by Custom Roles

JWT bearer token Authorization not working asp net core web api

Authorization Bearer token not being sent in request using Swagger in Asp.Net Core

401 error with bearer token - asp.net core 3.1

How to get the bearer token in the Asp .Net Core SignalR Hub?

HttpClient not sending authorization Bearer token in .Net Core 3.1

Custom authorization filter not working in ASP.NET Core 3

Authorization failing for custom authentication handler for ASP.NET Core 3.1?

Sending Authorization Token Bearer through JQuery Ajax - Back end is .NET Core Web Api

custom authorization in asp.net core mvc

Custom Authorization attribute asp.net core

ASP.NET Core Custom Authorization & Memory Cache

Custom authorization in ASP.NET Core with enum roles