0

I'm using the Bearer Token Module to secure the API module.

How can I get the IHttpContext.User property set to the current user, so that I can access it in my controllers?

Here's the relevant part of the web server setup:

WebServerEmbedded
    .WithCors()
    .WithBearerToken("/api", "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF", new MyAuthorizationServerProvider())
    .WithModule(webApiModule)

and here is MyAuthorizationServerProvider:

internal sealed class MyAuthorizationServerProvider: IAuthorizationServerProvider
{
    public async Task ValidateClientAuthentication(ValidateClientAuthenticationContext context)
    {
        var data = await context.HttpContext.GetRequestFormDataAsync().ConfigureAwait(false);

        if (data?.ContainsKey("grant_type") == true && data["grant_type"] == "password")
        {
            var username = data.ContainsKey("username") ? data["username"] : string.Empty;
            var password = data.ContainsKey("password") ? data["password"] : string.Empty;

            if (ValidateCredentials(username, password))
            {
                context.Validated(username);
            }
            else
            {
                context.Rejected();
            }
        }
        else
        {
            context.Rejected();
        }
    }

    public long GetExpirationDate() => DateTime.UtcNow.AddHours(12).Ticks;

    private static bool ValidateCredentials(string username, string password)
    {
        var user = BusinessLayer.CheckUserAndPassword(username, password);
        return user != null;
    }
}

Thanks.

Paul
  • 1,224
  • 2
  • 14
  • 31

1 Answers1

0

I posted an issue in the embedio-extras repo and a pull request was created that solves it. As detailed in there, upgrading to Embedio (v3.3.3) and Embbedio.BearerToken (v3.4.0) sets the User principal from the Bearer Token Module.

In the controllers HttpContext.User can be used to access the principal. Additional claims may be included in the IAuthorizationServerProvider implementation, just before calling context.Validated(username);, for instance:

context.Identity.AddClaim(new System.Security.Claims.Claim("Role", "Admin"));
context.Validated(username);

The claims can be accessed like this in the controller:

var principal = HttpContext?.User as ClaimsPrincipal;
if (null != principal)
{
    foreach (Claim claim in principal.Claims)
    {
        Log("Claim type: " + claim.Type + "; Claim value: " + claim.Value);
    }
}
Paul
  • 1,224
  • 2
  • 14
  • 31