Get identity claims from bearer token (Web API)

asp.netasp.net-web-apibearer-tokenclaims-based-identity

I have two Web APIs with a shared machine.key. I would like to pass the bearer token generated by the first Web API to the second Web API as a parameter (i.e. token=xxxxxxxx) and extract the identity claims (i.e userId) from it.

Is this possible? I've looked all over but there doesn't seem to be much information on parsing a text bearer token to extract claims.

Thanks.

Best Answer

If you're using OWIN, you could implement your own OAuthBearerAuthenticationProvider, which takes the token from the query string and sets it to the context:

internal class MyAuthProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
        if (context.Token == null)
        {
            var value = context.Request.Query.Get("token");
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
        }

        return Task.FromResult<object>(null);
    }
}

You could use it in your Startup.cs like this:

public void Configuration(IAppBuilder app)
{
    // All the other stuff here

    var audience = "";
    var secret = "...";

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    {
        Provider = new MyAuthProvider(),
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new [] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("MyApp", TextEncodings.Base64Url.Decode(key))
        }
    });

    // All the other stuff here
}

When you've implemented your auth like this, you can access the token information in your WebApi controller via the User.Identity property. To read custom claims, you can cast it to ClaimsIdentity.

var identity = User.Identity as ClaimsIdentity;
var myClaim = identity.Claims.FirstOrDefault(c => c.Type == "myClaimKey");
Related Topic