ARTICLE AD BOX
Asked today
Viewed 65 times
I am trying to integrate Azure AD login in my .NET 4.8 application with an Angular frontend.
But when I try to authenticate, it's returning an http 401 "Unauthorized" error.
In the controller, all the claims are missing, and the controller is returning a http 500 internal server error.
Here is my code:
app.UseJwtBearerAuthentication( new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { clientId }, TokenValidationParameters = new TokenValidationParameters { ValidAudience = clientId, ValidateAudience = true, ValidIssuer = issuer, ValidateIssuer = true, ValidateIssuerSigningKey = true, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5) }, IssuerSecurityTokenProviders = new[] { new OpenIdConnectCachingSecurityTokenProvider( $"{authority}/.well-known/openid-configuration") } }); } public OpenIdConnectCachingSecurityTokenProvider(string metadataEndpoint) { var wc = new WebClient(); var metadata = JObject.Parse(wc.DownloadString(metadataEndpoint)); Issuer = metadata["issuer"].ToString(); var jwksUri = metadata["jwks_uri"].ToString(); var keysJson = wc.DownloadString(jwksUri); var jwks = JObject.Parse(keysJson); var tokens = new List<SecurityToken>(); foreach (var key in jwks["keys"]) { var x5cArray = key["x5c"] as JArray; if (x5cArray == null || x5cArray.Count == 0) continue; var certString = x5cArray[0].ToString(); var certBytes = Convert.FromBase64String(certString); var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certBytes); var securityToken = new X509SecurityToken(cert); tokens.Add(securityToken); } SecurityTokens = tokens; }760k186 gold badges1.4k silver badges1.5k bronze badges
it seems the issue is likely that your WebClient cannot download the keys from Azure because it is using an old security protocol. Azure requires TLS 1.2, but .NET 4.8 often defaults to an older version.
When the download fails, your app cannot verify the token, which causes the 401 error.
To fix this, add this line in your Global.asax.cs file inside the Application_Start method:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;Also, take a look at your foreach loop. You are ignoring keys that do not have x5c data. Sometimes Azure sends keys using just RSA numbers (n and e) without the certificate string. If that happens, your list of tokens might be empty, which would also make the login fail.
Explore related questions
See similar questions with these tags.
