简体   繁体   中英

Read and Validate JWT token per request

I have a scenario where there are many separate clients connecting via JWT token.

  1. The client (browser) first needs to login (and is given a JWT token)
  2. The client then needs to retrieve their account information, they do this by sending a request to the server (which includes the JWT token. The server (which has access to the secret) reads the JWT token (securely) and should send back the user information, how do I do this?

ps Each client has a different secret

I can do this on a per app basis

app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    },
                    Provider = new CookieOAuthBearerProvider("authCookie")
                });

But this method will not work on a per request basis....

This is a snippet from what we're currently using (connecting to AzureAD). You'll need to implement GetSigningCertificates which returns IEnumerable<X509SecurityToken> to validate the JWT is properly signed.

internal static ClaimsPrincipal GetClaimPrincipalFromToken(string jwtSecurityHeader)
{
    var jwtSecurityHandler = new JwtSecurityTokenHandler();

    var signingCertificates = GetSigningCertificates(ConfigHelper.FederationMetadataDocument);
    var tokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidAudience = ConfigHelper.AppIdURI,
        ValidIssuer = ConfigHelper.Issuer,
        LifetimeValidator =
            (before, expires, token, parameters) =>
            {
                //Don't allow not-yet-active tokens
                if (before.HasValue && before.Value > DateTime.Now)
                    return false;

                //If expiration has a date, add 2 days to it
                if (expires.HasValue)
                    return expires.Value.AddDays(2) > DateTime.Now;

                //Otherwise the token is valid
                return true;
            },
        ValidateLifetime = true,
        IssuerSigningTokens = signingCertificates,
    };

    var headerParts = jwtSecurityHeader.Split(' ');
    if (headerParts.Length != 2 || headerParts[0] != "Bearer")
        throw new AuthorizationException(HttpStatusCode.Forbidden, "Invalid token type");

    var jwtSecurityToken = headerParts[1];
    SecurityToken jwtToken;
    var claimsPrincipal = jwtSecurityHandler.ValidateToken(jwtSecurityToken, tokenValidationParameters, out jwtToken);

    return claimsPrincipal;
}

You'll need to tweak it a bit for your application, but this should get you most of the way there. Note that this code is parsing a {HeaderType} {Token} format (for example Bearer {token} ). If you're simplying parsing the {Token} , you need to remove the .Split(' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM