.net core 2.2 Azure Ad Jwt Token

686 Views Asked by At

I'm trying to validate my Azure Ad Token, obtained from the library react-aad-msal, in my .net core 2.2 middleware. The token seems to be valid, but from the backend I receive this error

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'System.String'. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
   at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()

This is my middleware

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(x =>
             {
                 x.RequireHttpsMetadata = false;
                 x.SaveToken = true;
                 x.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(key),
                     ValidateIssuer = false,
                     ValidateAudience = false,
                     ValidIssuer = appSettings.Issuer,
                     ValidAudience = appSettings.Audience
                 };
             })
            .AddJwtBearer("AzureAd", opt =>
             {
                 //opt.Authority = "https://login.microsoftonline.com/organizations";
                 opt.Authority = "https://login.microsoftonline.com/organizations";
                 opt.Audience = "api://xxxxxxxxxxxxxxxxxxxxxxxx"; // Set this to the App ID URL for the web API, which you created when you registered the web API with Azure AD.
URL for the web API, which you created when you registered the web API with Azure AD.
                 opt.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuer = true,
                     ValidateAudience = true,
                     ValidAudiences = new List<string>{
                    // you could add a list of valid audiences
                    "yyyyyyyyyyyyyyyyyy"
                    },
                     ValidIssuers = new List<string>
                     {
                        // Add tenant id after https://sts.windows.net/
                        //"https://sts.windows.net/{YourTenantId}" //Questa è per la versione 1 del token
                        "https://login.microsoftonline.com/xxxxxxxxxxxxx"
                     }
                 };
                 opt.Events = new JwtBearerEvents()
                 {
                     OnAuthenticationFailed = AuthenticationFailed
                 };
             });
            services.AddAuthorization(options =>
            {
                var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
                    JwtBearerDefaults.AuthenticationScheme,
                    "AzureAd");
                defaultAuthorizationPolicyBuilder =
                    defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
                options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
            });

The token has been issued correctly from azure ad, because If i decode that token in the reactjs file, seems to have the correct information. But when I try to access to my protected WEB API with the [Authorize] attribute, the error appear. Thank you for your help!

1

There are 1 best solutions below

0
On

Replace

opt.Authority = "https://login.microsoftonline.com/organizations";

with

opt.Authority = "https://login.microsoftonline.com/{tenant id or name}";