C
C#13mo ago
chimera

❔ Validate an Azure ad token in .net 7

Hi, so i am trying to validate an Azure Ad token coming from an SPA. My thinking is that I would want to validate the token and then issue my own token. The reason I am not using the the Middleware AddMicrosoftIdentityWebApi is that it seems to break my normal username/password JWT validator, and I have some claims from our own database, that is required to be in the JWT token as a claim, and it doesn't seem to be possible to do that with a Azure Ad token. I have tried this, but it just throws an "Object reference not set to an instance of an object." even though all the parameters is not null string token = ""; string myTenant = "<>"; var myAudience = "api://<>"; var myIssuer = "https://login.microsoftonline.com/<>/wsfed"; var mySecret = "<SECRET>"; var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret)); var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{ 0 }/.well-known/openid-configuration", myTenant); var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever()); var config = configManager.GetConfigurationAsync().Result; var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { ValidAudience = myAudience, ValidIssuer = myIssuer, IssuerSigningKeys = config.SigningKeys, ValidateLifetime = false, IssuerSigningKey = mySecurityKey }; SecurityToken validatedToken; // Throws an Exception as the token is invalid (expired, invalid-formatted, etc.) try { tokenHandler.ValidateToken(token, validationParameters, out validatedToken).Dump(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
8 Replies
chimera
chimera13mo ago
I have also tried this, var token = ""; string authority = "https://login.microsoftonline.com/<>/"; string clientId = "<>"; IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{authority}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None); IdentityModelEventSource.ShowPII = true; var validationParams = new TokenValidationParameters { ValidAudience = clientId, IssuerSigningKeys = openIdConfig.SigningKeys, }; openIdConfig.SigningKeys.Dump(); var tokenHandler = new JwtSecurityTokenHandler(); tokenHandler.ValidateToken(token, validationParams, out _); but i get the error IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: '[deleted]', InternalId: '[deleted]'. , KeyId: [deleted]'. Number of keys in TokenValidationParameters: '14'. Number of keys in Configuration: '0'. Matched key was in 'TokenValidationParameters'. kid: '[deleted]'. Exceptions caught: ".
Tvde1
Tvde113mo ago
GitHub
Web Apps
Helps creating protected web apps and web APIs with Microsoft identity platform and Azure AD B2C - AzureAD/microsoft-identity-web
Tvde1
Tvde113mo ago
is that useful?
Tvde1
Tvde113mo ago
Microsoft.Identity.Web 2.11.1
This package enables ASP.NET Core web apps and web APIs to use the Microsoft identity platform (formerly Azure AD v2.0). This package is specifically used for web applications, which sign-in users, and protected web APIs, which optionally call downstream web APIs.
chimera
chimera13mo ago
I've tried that middleware but it seems to collide with the existing jwt configuration that is used for normal signin
Tvde1
Tvde113mo ago
I think get rid of that one 😁
chimera
chimera13mo ago
The exisiting JWT configuration? i need to be able to login with username/password
Accord
Accord13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
✅ Load image from resources depending on variable (string username)I am making a log in/register option which also loads picture depending on username. I also want to ❔ Formatting C# code in VSCode doesn't look rightHi everyone! I haven't written any C# code for quite a while and would like to get back to it. I set✅ How to correctly implement a lobby system with Redis?I am making a web game using SignalR and am looking to scale horizontally. Right now I'm designing a❔ IISExpress keeps failing to start siteI am running this command based on Rider's run config: ``` C:/Program Files/IIS Express/iisexpress.eStopwatch not giving accurate timeshey everyone, im using stopwatch to measure total milliseconds, but the timing is way off. for examp✅ System.NotSupportedException with EF Corequick question: ```cs public async Task<List<Order>> GetAllOrders() { return await _dbC✅ Absolutely clueless about this nullreference exceptionSo I have this piece of code in my WPF+WCF application. For some reason I get an exception as "i" j❔ How to Convert txt to exe or ther ways to copy a exe file from the code to somewhere help pls(this has to be compiled in an exe file btw) I simply want to copy an exe file to a direction but vi❔ Associate an application with an extension name (e.g., .asset, .ext, .lol, etc...)Hello, I would like to know how I can link my app with a custom extension name, in my case it's `.ri❔ C# InheritanceQuick question, is there a way to achieve this in C#? I need derived classes of the Beverage class t