asp.netasp.net-corejwtiprincipalaspnet-contrib

Materializing Custom Principal With AspNet.Security.OpenIdConnect.Server (ASP.NET vNext)


I am using Visual Studio 2015 Enterprise and ASP.NET vNext Beta8 to build an endpoint that both issues and consumes JWT tokens as described in detail here.

I am at the phase in my project where I want to allow the JWT bearer authentication to proceed as discussed in the article mentioned above, but once the token has been authenticated I want to:

I'm sure this will involve a scoped IContosoPrincipal object and I can likely figure that part out, but I'm not sure how to intercept JWT authentication after the token is successfully authenticated but before controller/action invocation takes place.

Any advice on how to approach this would be much appreciated.


Solution

  • Custom principals/identities are not (and won't be) officially supported in ASP.NET 5. You can find more information on this topic: https://github.com/aspnet/Security/issues/323.

    Instead, you're strongly encouraged to store the data you need as individual claims, and provide extension methods around ClaimsIdentity/ClaimsPrincipal when needed (e.g if you need to format the claim value).

    FWIW, this pattern is heavily used by ASP.NET Identity 3 itself, that comes with built-in extensions (like GetUserName or GetUserId) that you can use in your own code:

    /// <summary>
    /// Returns the User ID claim value if present otherwise returns null.
    /// </summary>
    /// <param name="principal">The <see cref="ClaimsPrincipal"/> instance this method extends.</param>
    /// <returns>The User ID claim value, or null if the claim is not present.</returns>
    /// <remarks>The User ID claim is identified by <see cref="ClaimTypes.NameIdentifier"/>.</remarks>
    public static string GetUserId(this ClaimsPrincipal principal)
    {
        if (principal == null)
        {
            throw new ArgumentNullException(nameof(principal));
        }
        return principal.FindFirstValue(ClaimTypes.NameIdentifier);
    }
    

    https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNet.Identity/PrincipalExtensions.cs