|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using Microsoft.DevProxy.ApiControllers; |
| 5 | +using Microsoft.IdentityModel.Tokens; |
| 6 | +using System.Globalization; |
| 7 | +using System.IdentityModel.Tokens.Jwt; |
| 8 | +using System.Security.Claims; |
| 9 | +using System.Security.Cryptography; |
| 10 | +using System.Security.Principal; |
| 11 | + |
| 12 | +namespace Microsoft.DevProxy.CommandHandlers; |
| 13 | + |
| 14 | +internal static class JwtCommandHandler |
| 15 | +{ |
| 16 | + internal static void GetToken(JwtOptions jwtOptions) |
| 17 | + { |
| 18 | + var token = JwtTokenGenerator.CreateToken(jwtOptions); |
| 19 | + |
| 20 | + Console.WriteLine(token); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +internal static class JwtTokenGenerator |
| 25 | +{ |
| 26 | + internal static string CreateToken(JwtOptions jwtOptions) |
| 27 | + { |
| 28 | + var options = JwtCreatorOptions.Create(jwtOptions); |
| 29 | + |
| 30 | + var jwtIssuer = new JwtIssuer( |
| 31 | + options.Issuer, |
| 32 | + RandomNumberGenerator.GetBytes(32) |
| 33 | + ); |
| 34 | + |
| 35 | + var jwtToken = jwtIssuer.Create(options); |
| 36 | + |
| 37 | + var jwt = Jwt.Create( |
| 38 | + options.Scheme, |
| 39 | + jwtToken, |
| 40 | + new JwtSecurityTokenHandler().WriteToken(jwtToken), |
| 41 | + options.Scopes, |
| 42 | + options.Roles, |
| 43 | + options.Claims |
| 44 | + ); |
| 45 | + |
| 46 | + return jwt.Token; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +internal sealed class JwtIssuer(string issuer, byte[] signingKeyMaterial) |
| 51 | +{ |
| 52 | + private readonly SymmetricSecurityKey _signingKey = new(signingKeyMaterial); |
| 53 | + |
| 54 | + public string Issuer { get; } = issuer; |
| 55 | + |
| 56 | + public JwtSecurityToken Create(JwtCreatorOptions options) |
| 57 | + { |
| 58 | + var identity = new GenericIdentity(options.Name); |
| 59 | + |
| 60 | + identity.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, options.Name)); |
| 61 | + |
| 62 | + var id = Guid.NewGuid().ToString().GetHashCode().ToString("x", CultureInfo.InvariantCulture); |
| 63 | + identity.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, id)); |
| 64 | + |
| 65 | + if (options.Scopes is { } scopesToAdd) |
| 66 | + { |
| 67 | + identity.AddClaims(scopesToAdd.Select(s => new Claim("scp", s))); |
| 68 | + } |
| 69 | + |
| 70 | + if (options.Roles is { } rolesToAdd) |
| 71 | + { |
| 72 | + identity.AddClaims(rolesToAdd.Select(r => new Claim("roles", r))); |
| 73 | + } |
| 74 | + |
| 75 | + if (options.Claims is { Count: > 0 } claimsToAdd) |
| 76 | + { |
| 77 | + // filter out registered claims |
| 78 | + // https://www.rfc-editor.org/rfc/rfc7519#section-4.1 |
| 79 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Iss); |
| 80 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Sub); |
| 81 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Aud); |
| 82 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Exp); |
| 83 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Nbf); |
| 84 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Iat); |
| 85 | + claimsToAdd.Remove(JwtRegisteredClaimNames.Jti); |
| 86 | + claimsToAdd.Remove("scp"); |
| 87 | + claimsToAdd.Remove("roles"); |
| 88 | + |
| 89 | + identity.AddClaims(claimsToAdd.Select(kvp => new Claim(kvp.Key, kvp.Value))); |
| 90 | + } |
| 91 | + |
| 92 | + // Although the JwtPayload supports having multiple audiences registered, the |
| 93 | + // creator methods and constructors don't provide a way of setting multiple |
| 94 | + // audiences. Instead, we have to register an `aud` claim for each audience |
| 95 | + // we want to add so that the multiple audiences are populated correctly. |
| 96 | + |
| 97 | + if (options.Audiences.ToList() is { Count: > 0 } audiences) |
| 98 | + { |
| 99 | + identity.AddClaims(audiences.Select(aud => new Claim(JwtRegisteredClaimNames.Aud, aud))); |
| 100 | + } |
| 101 | + |
| 102 | + var handler = new JwtSecurityTokenHandler(); |
| 103 | + var jwtSigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256Signature); |
| 104 | + var jwtToken = handler.CreateJwtSecurityToken(Issuer, audience: null, identity, options.NotBefore, options.ExpiresOn, issuedAt: DateTime.UtcNow, jwtSigningCredentials); |
| 105 | + return jwtToken; |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +internal record Jwt(string Id, string Scheme, string Name, string Audience, DateTimeOffset NotBefore, DateTimeOffset Expires, DateTimeOffset Issued, string Token) |
| 110 | +{ |
| 111 | + public IEnumerable<string> Scopes { get; set; } = []; |
| 112 | + |
| 113 | + public IEnumerable<string> Roles { get; set; } = []; |
| 114 | + |
| 115 | + public IDictionary<string, string> CustomClaims { get; set; } = new Dictionary<string, string>(); |
| 116 | + |
| 117 | + public static Jwt Create( |
| 118 | + string scheme, |
| 119 | + JwtSecurityToken token, |
| 120 | + string encodedToken, |
| 121 | + IEnumerable<string> scopes, |
| 122 | + IEnumerable<string> roles, |
| 123 | + IDictionary<string, string> customClaims) |
| 124 | + { |
| 125 | + return new Jwt(token.Id, scheme, token.Subject, string.Join(", ", token.Audiences), token.ValidFrom, token.ValidTo, token.IssuedAt, encodedToken) |
| 126 | + { |
| 127 | + Scopes = scopes, |
| 128 | + Roles = roles, |
| 129 | + CustomClaims = customClaims |
| 130 | + }; |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +internal sealed record JwtCreatorOptions |
| 135 | +{ |
| 136 | + public required string Scheme { get; init; } |
| 137 | + public required string Name { get; init; } |
| 138 | + public required IEnumerable<string> Audiences { get; init; } |
| 139 | + public required string Issuer { get; init; } |
| 140 | + public DateTime NotBefore { get; init; } |
| 141 | + public DateTime ExpiresOn { get; init; } |
| 142 | + public required IEnumerable<string> Roles { get; init; } |
| 143 | + public required IEnumerable<string> Scopes { get; init; } |
| 144 | + public required Dictionary<string, string> Claims { get; init; } |
| 145 | + |
| 146 | + public static JwtCreatorOptions Create(JwtOptions options) |
| 147 | + { |
| 148 | + return new JwtCreatorOptions |
| 149 | + { |
| 150 | + Scheme = "Bearer", |
| 151 | + Name = options.Name ?? "Dev Proxy", |
| 152 | + Audiences = options.Audiences ?? ["https://myserver.com"], |
| 153 | + Issuer = options.Issuer ?? "dev-proxy", |
| 154 | + Roles = options.Roles ?? [], |
| 155 | + Scopes = options.Scopes ?? [], |
| 156 | + Claims = options.Claims ?? [], |
| 157 | + NotBefore = DateTime.UtcNow, |
| 158 | + ExpiresOn = DateTime.UtcNow.AddMinutes(options.ValidFor == 0 ? 60 : options.ValidFor) |
| 159 | + }; |
| 160 | + } |
| 161 | +} |
| 162 | + |
0 commit comments