%3CLINGO-SUB%20id%3D%22lingo-sub-2109450%22%20slang%3D%22en-US%22%3ECreating%20a%20JWT%20Validation%20Web%20App%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2109450%22%20slang%3D%22en-US%22%3E%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20image-alt%3D%22JWT.png%22%20style%3D%22width%3A%20401px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F251081i4C16DA40C0BF968F%2Fimage-dimensions%2F401x217%3Fv%3D1.0%22%20width%3D%22401%22%20height%3D%22217%22%20role%3D%22button%22%20title%3D%22JWT.png%22%20alt%3D%22JWT.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EIf%20you%20have%20been%20doing%20any%20OAuth%20and%2For%20Open%20ID%20Connect%20troubleshooting%20in%20recent%20years%20it's%20very%20likely%20you've%20run%20across%20%3CA%20href%3D%22https%3A%2F%2Fjwt.io%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noreferrer%22%3Ehttps%3A%2F%2Fjwt.io%3C%2FA%3E%2C%20or%20in%20the%20Microsoft%20world%20%3CA%20href%3D%22https%3A%2F%2Fjwt.ms%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noreferrer%22%3Ehttps%3A%2F%2Fjwt.ms%3C%2FA%3E.%20Great%20tools%2C%20but%20primarily%20JWT%20parsing%20tools%20rather%20than%20JWT%20validation%20tools.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EYes%2C%20jwt.io%20allows%20you%20to%20upload%20your%20keys%20in%20the%20UI%2C%20but%20there%20are%20a%20lot%20of%20scenarios%20that%20doesn't%20work%20for.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3ELet's%20rewind%20a%20step%20or%20two%20here%20first%20though.%20Last%20year%20I%20showed%20how%20you%20could%20create%20your%20own%20faux%20tokens.%20That%20is%3B%20the%20tokens%20were%20real%20enough%2C%20but%20they%20mimicked%20actual%20tokens%20as%20they%20would%20look%20if%20issued%20by%20Azure%20AD%20and%20Azure%20AD%20B2C%20without%20actually%20being%20signed%20by%20Microsoft's%20keys.%20If%20you%20pasted%20the%20result%20into%20jwt.ms%20it%20would%20look%20like%20a%20real%20token.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EIdentity%20is%20a%20large%20topic%2C%20but%20the%20two%20central%20concepts%20are%20%22who%20are%20you%22%20(authentication)%20and%20%22what%20are%20you%20allowed%20to%20do%22%20(authorization).%20If%20your%20approach%20in%20web%20app%20or%20api%20is%20to%20accept%20any%20old%20token%20and%20say%20%22this%20looks%20good%22%20you%20might%20run%20into%20trouble.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EWhich%20is%20why%20I%20wanted%20to%20show%20how%20to%26nbsp%3B%20build%20a%20web%20app%20that%20will%20attempt%20to%20validate%20the%20token%20in%20addition%20to%20parsing%20it.%20This%20is%20based%20on%20supplying%20a%20metadata%20url%20to%20retrieve%20signing%20keys%2C%20etc.%20If%20you%20don't%20have%20this%20the%20app%20will%20just%20parse%20the%20token%20and%20check%20against%20the%20attributes%20you%20supply%20(issuer%2C%20audience).%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EThe%20code%20for%20this%20post%20can%20be%20found%20here%3A%3C%2FP%3E%3CP%3E%3CA%20title%3D%22GitHub%22%20href%3D%22https%3A%2F%2Fgithub.com%2Fahelland%2FIdentity-CodeSamples-v2%2Ftree%2Fmaster%2Fblazor_jwt_validator_dotnet_core%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%3Ehttps%3A%2F%2Fgithub.com%2Fahelland%2FIdentity-CodeSamples-v2%2Ftree%2Fmaster%2Fblazor_jwt_validator_dotnet_core%3C%2FA%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EIn%20the%20real%20world%20i%20don't%20actually%20recommend%20you%20to%20do%20all%20these%20steps%20manually.%20There%20are%20libraries%20that%20will%20handle%20most%20of%20these%20things%20for%20you%20like%20MSAL%20on%20the%20client%20side%20of%20Identity.Web%20on%20the%20backend%20side.%20It%20is%20however%20always%20useful%20to%20dig%20a%20little%20deeper%20to%20gain%20an%20understanding%20of%20how%20it%20works%20behind%20the%20scenes.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EThere%20are%20third%20party%20libraries%20available%20for%20token%20validation%20that%20support%20a%20large%20range%20of%20algorithms%20and%20formats%2C%20but%20to%20keep%20it%20simple%20I'm%20just%20using%20components%20native%20to%20the%20.NET%20toolbox.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CSTRONG%3EStep%201%20-%20Is%20it%20a%20JWT%20that%20has%20been%20pasted%20in%3F%3C%2FSTRONG%3E%3C%2FP%3E%3CP%3EThe%20web%20app%20will%20allow%20pretty%20much%20any%20text%20to%20be%20passed%20in%20so%20we%20need%20to%20validate%20that%20it%20is%20actually%20a%20token.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3EJwtSecurityTokenHandler%20handler%20%3D%20new%20JwtSecurityTokenHandler()%3B%0A%0A%2F%2FCheck%20if%20readable%20token%20(string%20is%20in%20a%20JWT%20format)%0Avar%20readableToken%20%3D%20handler.CanReadToken(Jwt.Base64Token)%3B%0Aif%20(readableToken%20!%3D%20true)%0A%7B%0A%20%20FormatStatus%20%3D%20%22The%20token%20doesn't%20seem%20to%20be%20in%20a%20proper%20JWT%20format.%22%3B%0A%20%20return%3B%0A%7D%0Aif%20(readableToken%20%3D%3D%20true)%0A%7B%0A%20%20FormatStatus%20%3D%20%22The%20token%20seems%20to%20be%20in%20a%20proper%20JWT%20format.%22%3B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%7D%3C%2FCODE%3E%3C%2FPRE%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CSTRONG%3EStep%202%20-%20Do%20we%20have%20metadata%3F%3C%2FSTRONG%3E%3C%2FP%3E%3CP%3ETo%20be%20able%20to%20leverage%20concepts%20like%20public%2Fprivate%20key%20cryptography%20we%20need%20to%20exchange%20the%20keys%20used%2C%20and%20we%20also%20need%20to%20agree%20on%20a%20couple%20of%20other%20attributes%20the%20tokens%20contain.%20It%20is%20entirely%20possible%20to%20exchange%20this%20in%20a%20manual%20way%20whether%20that%20is%20sending%20files%20per%20email%20or%20reading%20them%20loud%20over%20the%20phone%20for%20that%20matter%2C%20but%20the%20recommended%20approach%20is%20to%20have%20the%20identity%20provider%20expose%20a%20metadata%20endpoint.%20Loading%20things%20in%20a%20more%20manual%20way%20also%20requires%20more%20code%2C%20so%20we've%20kept%20it%20simple%20here%20and%20only%20provide%20the%20option%20for%20using%20an%20endpoint.%20(If%20you%20don't%20have%20one%20the%20code%20will%20not%20break%2C%20but%20revert%20to%20just%20parsing%20the%20token.)%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EIf%20you%20followed%20my%20previous%20post%20you%20should%20be%20able%20to%20provide%20your%20own%20endpoint%20even%20if%20that's%20just%20pointing%20to%20a%20different%20port%20on%20%3CA%20href%3D%22https%3A%2F%2Flocalhost%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noreferrer%22%3Ehttps%3A%2F%2Flocalhost%3C%2FA%3E.%3C%2FP%3E%3CP%3E%3CA%20title%3D%22Generating%20Azure%20AD%20%26quot%3BLook-Alike%26quot%3B%20Tokens%22%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fazure-developer-community-blog%2Fgenerating-azure-ad-quot-look-alike-quot-tokens%2Fba-p%2F1163098%22%20target%3D%22_blank%22%3Ehttps%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fazure-developer-community-blog%2Fgenerating-azure-ad-quot-look-alike-quot-tokens%2Fba-p%2F1163098%3C%2FA%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CA%20title%3D%22GitHub%22%20href%3D%22https%3A%2F%2Fgithub.com%2Fahelland%2FIdentity-CodeSamples-v2%2Ftree%2Fmaster%2Fblazor-jwt_generator-dotnet-core%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%3Ehttps%3A%2F%2Fgithub.com%2Fahelland%2FIdentity-CodeSamples-v2%2Ftree%2Fmaster%2Fblazor-jwt_generator-dotnet-core%3C%2FA%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%2F%2FLoad%20Metadata%20if%20available%0AIConfigurationManager%3COPENIDCONNECTCONFIGURATION%3E%20configurationManager%3B%0AOpenIdConnectConfiguration%20openIdConfig%20%3D%20null%3B%0Abool%20metadataAvailable%3B%0Atry%0A%7B%0A%20%20configurationManager%20%3D%20new%20ConfigurationManager%3COPENIDCONNECTCONFIGURATION%3E(Jwt.MetadataAddress%2C%20new%20OpenIdConnectConfigurationRetriever())%3B%0A%20%20openIdConfig%20%3D%20configurationManager.GetConfigurationAsync(CancellationToken.None).Result%3B%0A%20%20metadataAvailable%20%3D%20true%3B%0A%20%20MetadataStatus%20%3D%20%24%22Successfully%20loaded%20metadata.%22%3B%0A%7D%0Acatch%20(Exception%20e)%0A%7B%0A%20%20MetadataStatus%20%3D%20%24%22Failed%20to%20load%20metadata%20(skipping%20signature%20validation)%3A%20%20%7Be.Message%7D%22%3B%0A%20%20metadataAvailable%20%3D%20false%3B%0A%7D%3C%2FOPENIDCONNECTCONFIGURATION%3E%3C%2FOPENIDCONNECTCONFIGURATION%3E%3C%2FCODE%3E%3C%2FPRE%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CSTRONG%3EStep%203%20-%20Set%20up%20token%20validation%20parameters%3C%2FSTRONG%3E%3C%2FP%3E%3CP%3EAs%20said%20already%20we%20handle%20the%20absence%20of%20metadata%20gracefully.%20We%20can%20still%20check%20things%20like%20the%20lifetime%20and%20the%20audience%2C%20but%20we%20are%20not%20able%20to%20verify%20the%20signature.%20And%20that%20is%20the%20critical%20part%20-%20what%20separates%20my%20fake%20tokens%20with%20actual%20Azure%20AD%20tokens%20is%20the%20keys%20they%20are%20signed%20with.%20Which%20is%20why%20you%20should%20never%20disable%20validation%20of%20the%20signing%20key%20like%20we%20do%20here%20%3A)%3C%2Fimg%3E%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EWhile%20there%20is%20some%20logic%20in%20locating%20the%20keys%20and%20retrieving%20them%20we%20see%20that%20this%20is%20one%20of%20the%20things%20the%20libraries%20handle%20for%20us%20in%20a%20developer%20friendly%20way.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3ETokenValidationParameters%20validationParameters%20%3D%20null%3B%0A%0A%2F%2FIf%20we%20cannot%20load%20metadata%20we%20fall%20back%0Aif%20(!metadataAvailable)%0A%7B%0A%20%20validationParameters%20%3D%0A%20%20new%20TokenValidationParameters%0A%20%20%7B%0A%20%20%20%20ValidIssuer%20%3D%20Jwt.Issuer%2C%0A%20%20%20%20ValidAudience%20%3D%20Jwt.Audience%2C%0A%20%20%20%20ValidateLifetime%20%3D%20true%2C%0A%20%20%20%20ValidateAudience%20%3D%20true%2C%0A%20%20%20%20ValidateIssuer%20%3D%20true%2C%0A%20%20%20%20%2F%2FNeeded%20to%20force%20disabling%20signature%20validation%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20SignatureValidator%20%3D%20delegate%20(string%20token%2C%20TokenValidationParameters%20parameters)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20var%20jwt%20%3D%20new%20JwtSecurityToken(token)%3B%0A%20%20%20%20%20%20return%20jwt%3B%0A%20%20%20%20%7D%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20ValidateIssuerSigningKey%20%3D%20false%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%7D%3B%0A%7D%0A%0A%2F%2FIf%20we%20succcessfully%20loaded%20metadata%20we%20do%20signature%20validation%20as%20well%0Aif%20(metadataAvailable)%0A%7B%0A%20%20validationParameters%20%3D%0A%20%20%20%20new%20TokenValidationParameters%0A%20%20%20%20%7B%0A%20%20%20%20%20%20ValidIssuer%20%3D%20openIdConfig.Issuer%2C%0A%20%20%20%20%20%20ValidAudience%20%3D%20Jwt.Audience%2C%0A%20%20%20%20%20%20ValidateLifetime%20%3D%20true%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20ValidateIssuerSigningKey%20%3D%20true%2C%20%20%20%0A%20%20%20%20%20%20ValidateAudience%20%3D%20true%2C%0A%20%20%20%20%20%20ValidateIssuer%20%3D%20true%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20IssuerSigningKeys%20%3D%20openIdConfig.SigningKeys%0A%20%20%20%20%7D%3B%0A%7D%3C%2FCODE%3E%3C%2FPRE%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CSTRONG%3EStep%204%20-%20Validate%20the%20token%3C%2FSTRONG%3E%3C%2FP%3E%3CP%3EThe%20actual%20validation%20is%20shorter%20than%20the%20setup.%20We%20read%20the%20JWT.%20(Notice%20how%20Microsoft%20also%20use%20%22token%22%20twice%20in%20the%20naming%20-%20spelling%20out%20the%20acronym%20it%20would%20be%20ReadJsonWebTokenToken.)%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3Etoken%20%3D%20handler.ReadJwtToken(Jwt.Base64Token)%3B%0Atry%0A%7B%0A%20%20var%20identity%20%3D%20handler.ValidateToken(Jwt.Base64Token%2C%20validationParameters%2C%20out%20SecurityToken%20validatedToken)%3B%0A%20%20if%20(metadataAvailable)%0A%20%20%7B%0A%20%20%20%20output%20%2B%3D%20%22Token%20is%20valid%20according%20to%20metadata!%22%3B%0A%20%20%7D%0A%20%20else%0A%20%20%7B%0A%20%20%20%20output%20%2B%3D%20%22Token%20is%20valid%20according%20to%20a%20self-evaluation!%22%3B%0A%20%20%7D%0A%0A%20%20jwtSignature%20%3D%20token.RawSignature%3B%0A%7D%0Acatch%20(Exception%20e)%0A%7B%0A%20%20%2F%2FPrint%20errors%0A%7D%3C%2FCODE%3E%3C%2FPRE%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CSTRONG%3EStep%205%20-%20Pretty%20print%20the%20contents%20and%20the%20result%3C%2FSTRONG%3E%3C%2FP%3E%3CP%3EThe%20last%20step%20is%20to%20print%20out%20the%20result%20of%20the%20validation%20test%2C%20and%20the%20contents%20of%20the%20token%20split%20into%20header%2Fpayload%2Fsignature%20with%20some%20color%20coding.%20I%20did%20not%20find%20satisfactory%20ways%20to%20do%20this%20with%20the%20built-in%20mechanisms%20as%20these%20didn't%20really%20play%20nice%20with%20Blazor%20so%20I%20did%20a%20more%20hackish%20and%20manual%20approach%20for%20this.%20Not%20including%20the%20code%20here%2C%20but%20it%20is%20of%20course%20part%20of%20the%20sample%20on%20GitHub.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20image-alt%3D%22ValidationResult.png%22%20style%3D%22width%3A%20532px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F251094i9680A5F7CA039B23%2Fimage-size%2Flarge%3Fv%3D1.0%26amp%3Bpx%3D999%22%20role%3D%22button%22%20title%3D%22ValidationResult.png%22%20alt%3D%22ValidationResult.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EIn%20an%20actual%20app%20or%20api%20you%20would%20of%20course%20not%20care%20so%20much%20about%20these%20things%20anyway.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EWhile%20I%20also%20prefer%20using%20%22proper%22%20libraries%20for%20validation%20I%20use%20tools%20like%20this%20all%20the%20time%20when%20working%20with%20things%20like%20custom%20policies%20in%20Azure%20AD%20B2C.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EI'm%20sure%20you%20are%20able%20to%20come%20up%20with%20more%20elaborate%20versions%20that%20what%20I%20did%20here%2C%20but%20I'm%20hoping%20it%20provided%20some%20of%20the%20basic%20understand%20for%20making%20sure%20you%20don't%20end%20up%20in%20the%20category%20of%20developers%20who%20skip%20token%20validation.%20(There%20are%20unfortunately%20too%20many%20that%20don't%20do%20this%20right%20and%20produce%20code%20with%20horrible%20vulnerabilities%20included.)%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-TEASER%20id%3D%22lingo-teaser-2109450%22%20slang%3D%22en-US%22%3E%3CP%3EBrief%20walkthrough%20of%20validating%20Json%20Web%20Tokens%20in%20.NET%205%20and%20pretty%20printing%20the%20result%20on%20a%20web%20page.%3C%2FP%3E%3C%2FLINGO-TEASER%3E%3CLINGO-LABS%20id%3D%22lingo-labs-2109450%22%20slang%3D%22en-US%22%3E%3CLINGO-LABEL%3EAPI%20Design%3C%2FLINGO-LABEL%3E%3CLINGO-LABEL%3EAzure%20Developer%3C%2FLINGO-LABEL%3E%3CLINGO-LABEL%3EDeveloper%3C%2FLINGO-LABEL%3E%3C%2FLINGO-LABS%3E
Senior Member

JWT.png

 

If you have been doing any OAuth and/or Open ID Connect troubleshooting in recent years it's very likely you've run across https://jwt.io, or in the Microsoft world https://jwt.ms. Great tools, but primarily JWT parsing tools rather than JWT validation tools.

 

Yes, jwt.io allows you to upload your keys in the UI, but there are a lot of scenarios that doesn't work for.

 

Let's rewind a step or two here first though. Last year I showed how you could create your own faux tokens. That is; the tokens were real enough, but they mimicked actual tokens as they would look if issued by Azure AD and Azure AD B2C without actually being signed by Microsoft's keys. If you pasted the result into jwt.ms it would look like a real token.

 

Identity is a large topic, but the two central concepts are "who are you" (authentication) and "what are you allowed to do" (authorization). If your approach in web app or api is to accept any old token and say "this looks good" you might run into trouble.

 

Which is why I wanted to show how to  build a web app that will attempt to validate the token in addition to parsing it. This is based on supplying a metadata url to retrieve signing keys, etc. If you don't have this the app will just parse the token and check against the attributes you supply (issuer, audience).

 

The code for this post can be found here:

https://github.com/ahelland/Identity-CodeSamples-v2/tree/master/blazor_jwt_validator_dotnet_core 

 

In the real world i don't actually recommend you to do all these steps manually. There are libraries that will handle most of these things for you like MSAL on the client side of Identity.Web on the backend side. It is however always useful to dig a little deeper to gain an understanding of how it works behind the scenes.

 

There are third party libraries available for token validation that support a large range of algorithms and formats, but to keep it simple I'm just using components native to the .NET toolbox.

 

Step 1 - Is it a JWT that has been pasted in?

The web app will allow pretty much any text to be passed in so we need to validate that it is actually a token.

 

 

 

 

JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

//Check if readable token (string is in a JWT format)
var readableToken = handler.CanReadToken(Jwt.Base64Token);
if (readableToken != true)
{
  FormatStatus = "The token doesn't seem to be in a proper JWT format.";
  return;
}
if (readableToken == true)
{
  FormatStatus = "The token seems to be in a proper JWT format.";                
}

 

 

 

 

Step 2 - Do we have metadata?

To be able to leverage concepts like public/private key cryptography we need to exchange the keys used, and we also need to agree on a couple of other attributes the tokens contain. It is entirely possible to exchange this in a manual way whether that is sending files per email or reading them loud over the phone for that matter, but the recommended approach is to have the identity provider expose a metadata endpoint. Loading things in a more manual way also requires more code, so we've kept it simple here and only provide the option for using an endpoint. (If you don't have one the code will not break, but revert to just parsing the token.)

 

If you followed my previous post you should be able to provide your own endpoint even if that's just pointing to a different port on https://localhost.

https://techcommunity.microsoft.com/t5/azure-developer-community-blog/generating-azure-ad-quot-look-... 

https://github.com/ahelland/Identity-CodeSamples-v2/tree/master/blazor-jwt_generator-dotnet-core 

 

 

 

 

//Load Metadata if available
IConfigurationManager<OpenIdConnectConfiguration> configurationManager;
OpenIdConnectConfiguration openIdConfig = null;
bool metadataAvailable;
try
{
  configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(Jwt.MetadataAddress, new OpenIdConnectConfigurationRetriever());
  openIdConfig = configurationManager.GetConfigurationAsync(CancellationToken.None).Result;
  metadataAvailable = true;
  MetadataStatus = $"Successfully loaded metadata.";
}
catch (Exception e)
{
  MetadataStatus = $"Failed to load metadata (skipping signature validation):  {e.Message}";
  metadataAvailable = false;
}

 

 

 

 

Step 3 - Set up token validation parameters

As said already we handle the absence of metadata gracefully. We can still check things like the lifetime and the audience, but we are not able to verify the signature. And that is the critical part - what separates my fake tokens with actual Azure AD tokens is the keys they are signed with. Which is why you should never disable validation of the signing key like we do here :)

 

While there is some logic in locating the keys and retrieving them we see that this is one of the things the libraries handle for us in a developer friendly way.

 

 

 

 

TokenValidationParameters validationParameters = null;

//If we cannot load metadata we fall back
if (!metadataAvailable)
{
  validationParameters =
  new TokenValidationParameters
  {
    ValidIssuer = Jwt.Issuer,
    ValidAudience = Jwt.Audience,
    ValidateLifetime = true,
    ValidateAudience = true,
    ValidateIssuer = true,
    //Needed to force disabling signature validation                        
    SignatureValidator = delegate (string token, TokenValidationParameters parameters)
    {
      var jwt = new JwtSecurityToken(token);
      return jwt;
    },                        
    ValidateIssuerSigningKey = false,                   
  };
}

//If we succcessfully loaded metadata we do signature validation as well
if (metadataAvailable)
{
  validationParameters =
    new TokenValidationParameters
    {
      ValidIssuer = openIdConfig.Issuer,
      ValidAudience = Jwt.Audience,
      ValidateLifetime = true,                        
      ValidateIssuerSigningKey = true,   
      ValidateAudience = true,
      ValidateIssuer = true,                        
      IssuerSigningKeys = openIdConfig.SigningKeys
    };
}

 

 

 

 

Step 4 - Validate the token

The actual validation is shorter than the setup. We read the JWT. (Notice how Microsoft also use "token" twice in the naming - spelling out the acronym it would be ReadJsonWebTokenToken.)

 

 

 

 

token = handler.ReadJwtToken(Jwt.Base64Token);
try
{
  var identity = handler.ValidateToken(Jwt.Base64Token, validationParameters, out SecurityToken validatedToken);
  if (metadataAvailable)
  {
    output += "Token is valid according to metadata!";
  }
  else
  {
    output += "Token is valid according to a self-evaluation!";
  }

  jwtSignature = token.RawSignature;
}
catch (Exception e)
{
  //Print errors
}

 

 

 

 

Step 5 - Pretty print the contents and the result

The last step is to print out the result of the validation test, and the contents of the token split into header/payload/signature with some color coding. I did not find satisfactory ways to do this with the built-in mechanisms as these didn't really play nice with Blazor so I did a more hackish and manual approach for this. Not including the code here, but it is of course part of the sample on GitHub.

 

ValidationResult.png

 

In an actual app or api you would of course not care so much about these things anyway.

 

While I also prefer using "proper" libraries for validation I use tools like this all the time when working with things like custom policies in Azure AD B2C.

 

I'm sure you are able to come up with more elaborate versions that what I did here, but I'm hoping it provided some of the basic understand for making sure you don't end up in the category of developers who skip token validation. (There are unfortunately too many that don't do this right and produce code with horrible vulnerabilities included.)