Ali
Ali

Reputation: 55

validate JWT without public key (RSA) .net core webapi

I am new JWT in DOTNet core web Api. In our application, we are getting access_token from the Microsoft site. https://login.microsoftonline.com/

We would like to validate the token (RS256 algo) in the .net core (Api) but we don't have the PUBLIC KEY.

Note: I already have a token. How can we validate JWT with our public key and any other thing? I only have an access token.

Upvotes: 2

Views: 1381

Answers (1)

Maxim Zabolotskikh
Maxim Zabolotskikh

Reputation: 3367

With JWT you basically have two scenarios:

  • you created your JWT yourself and you know the keys used for it. Than you can write the validation, or pass the parameters to .net core pipeline.
  • you got the JWT from external authority. In this case the authority (in your particular case - Microsoft) knows how to validate the JWT.

Authority will implement the JWT protocol and expose it via a URL. Normally you need to know two things: authority and audience (recipient of the token).

Now good news is that .net core handles the protocol details for you, all you need to do is to set up the authentication pipeline. This is what it boils down to:

 services.AddAuthentication()
        .AddJwtBearer("schemeName", options =>
        {
            options.Audience = "your audience";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = "your domain",
                ValidateAudience = true,
                ValidAudience = "your audience",
                ValidateIssuerSigningKey = true,
                IssuerSigningKeys = jwks, // use "Keys" as JsonWebKeySet or "Key" (below), just one of them
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), // your encoding etc may differ
                RequireSignedTokens = true,
                RequireExpirationTime = true,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                ValidAlgorithms = new[] { SecurityAlgorithms.EcdsaSha256, }, // your algorithm may differ
            };
        })

For details, do some reading on JWT authentication in .net core, e.g. JWT Validation and Authorization in ASP.NET Core. There are a lot of articles on the topic.

Upvotes: 1

Related Questions