Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IdentityModel.Protocols.WSTrust;
- using System.IdentityModel.Tokens;
- using System.Security.Claims;
- using System.Security.Cryptography.X509Certificates;
- namespace JwtValidator
- {
- class Program
- {
- static void Main(string[] args)
- {
- var signingCertificate = new X509Certificate2("JWTSigningCert.pfx", "password");
- var publicCertificate = new X509Certificate2("JWTSigningCert.cer");
- var signedJwt = GenerateSignedJwt(signingCertificate);
- var validatedPrincipal = ValidateTokenWithX509SecurityToken(signedJwt, publicCertificate);
- Console.WriteLine(validatedPrincipal.Identity.Name);
- Console.ReadLine();
- }
- static string GenerateSignedJwt(X509Certificate2 signingCertificate)
- {
- var now = DateTime.UtcNow;
- var tokenHandler = new JwtSecurityTokenHandler();
- var tokenDescriptor = new SecurityTokenDescriptor
- {
- Subject = new ClaimsIdentity(new Claim[]
- {
- new Claim(ClaimTypes.Name, "John Doe"),
- }),
- TokenIssuerName = "self",
- AppliesToAddress = "http://www.contoso.com",
- Lifetime = new Lifetime(now, now.AddMinutes(10)),
- SigningCredentials = new X509SigningCredentials(
- signingCertificate)
- };
- SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
- string tokenString = tokenHandler.WriteToken(token);
- return tokenString;
- }
- static ClaimsPrincipal ValidateTokenWithX509SecurityToken(string token, X509Certificate2 validatingCertificate)
- {
- SecurityToken validatedToken;
- var tokenHandler = new JwtSecurityTokenHandler();
- var validationParameters = new TokenValidationParameters()
- {
- ValidateIssuerSigningKey = true,
- ValidateAudience = true,
- ValidateIssuer = true,
- IssuerSigningToken = new X509SecurityToken(validatingCertificate),
- ValidAudience = "http://www.contoso.com",
- ValidIssuer = "self",
- };
- ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
- return claimsPrincipal;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment