Last active
February 20, 2019 18:12
-
-
Save rbrayb/3c11db03f4f72a82e7a3b4d298b7965a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.IdentityModel.Tokens.Jwt; | |
| using System.Security.Claims; | |
| using System.Text; | |
| using Microsoft.IdentityModel.Tokens; | |
| namespace B2CPoCConsoleApp | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| TimeSpan policyTokenLifetime; | |
| var clientSecret = "zg3*Tl#zlt5SV-l}]b%UqIjm"; | |
| var issuer = "tenant.onmicrosoft.com"; | |
| var redirectUri = "https://localhost:57478/"; | |
| // ... Or set it to a default time of 20 minutes. | |
| policyTokenLifetime = new TimeSpan(0, 0, 20, 0); | |
| //ICollection<Claim> policyClaims = null; | |
| var policyClaims = new List<Claim>(); | |
| var emailClaim = new Claim("email", "[email protected]"); | |
| policyClaims.Add(emailClaim); | |
| // Create the JWT containing the list of claims and signed by the client secret. | |
| var selfIssuedToken = CreateSelfIssuedToken( | |
| issuer, | |
| redirectUri, | |
| policyTokenLifetime, | |
| clientSecret, | |
| policyClaims); | |
| Console.WriteLine(selfIssuedToken); | |
| Console.ReadLine(); | |
| } | |
| public static string CreateSelfIssuedToken( | |
| string issuer, | |
| string audience, | |
| TimeSpan expiration, | |
| string signingSecret, | |
| ICollection<Claim> claims) | |
| { | |
| var tokenHandler = new JwtSecurityTokenHandler(); | |
| var nowUtc = DateTime.UtcNow; | |
| var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingSecret)); | |
| var signingCredentials = new SigningCredentials(key, "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"); | |
| var tokenDescriptor = new SecurityTokenDescriptor | |
| { | |
| Audience = audience, | |
| Expires = nowUtc.Add(expiration), | |
| IssuedAt = nowUtc, | |
| Issuer = issuer, | |
| NotBefore = nowUtc, | |
| SigningCredentials = signingCredentials, | |
| Subject = new ClaimsIdentity(claims) | |
| }; | |
| var token = tokenHandler.CreateToken(tokenDescriptor); | |
| return tokenHandler.WriteToken(token); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment