askolotl
askolotl

Reputation: 1006

How to prove if a JWT is valid and is really from Microsoft?

A client application is acquiring a JWT from Microsoft and is sending it to my API. It works fine, but how does my API know if the token is really from Microsaft and if it is valid?

Here is how the client is acquiring the token:

string ClientID = "xxx";
string TenantID = "yyy";

IPublicClientApplication pca = PublicClientApplicationBuilder
     .Create(ClientID)
     .WithAuthority(AzureCloudInstance.AzurePublic, TenantID)
     .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
     .Build();

string[] scopes = { "user.read" };
AuthenticationResult result = await pca.AcquireTokenInteractive(scopes).ExecuteAsync();
string JWT = result.AccessToken;

Upvotes: 1

Views: 337

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24609

In the API project, you can install Microsoft.Identity.Web package. Then add the following code to Startup.cs

    services
       .AddAuthentication()
       .AddMicrosoftIdentityWebApi(options => { }, options =>
        {
            options.ClientId = "Your Azure AD ClientId";
            options.TenantId = "Your Azure AD TenantId";
            options.Instance = "https://login.microsoftonline.com/";
        });

To do it manually, try something like

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
             {
                 var clientSecret = "";
                 var clientId = "";
                 var tenantId = "";

                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidAudience = clientId,
                     ValidIssuer = $"https://sts.windows.net/{tenantId}/",
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(clientSecret)),
                     ValidateIssuer = true,
                     ValidateIssuerSigningKey = true,
                     ValidateLifetime = true,
                     ValidateAudience = true,
                     ClockSkew = TimeSpan.Zero
                 };
            });

Upvotes: 3

Related Questions