private static string GetSignedClientAssertionUsingWilson(
            string issuer,
            string aud,
            X509Certificate2 cert)
        {
            // no need to add exp, nbf as JsonWebTokenHandler will add them by default.
            var claims = new Dictionary <string, object>()
            {
                { "aud", aud },
                { "iss", issuer },
                { "jti", Guid.NewGuid().ToString() },
                { "sub", issuer }
            };

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Claims             = claims,
                SigningCredentials = new X509SigningCredentials(cert)
            };

            var handler = new JsonWebTokenHandler();
            var signedClientAssertion = handler.CreateToken(securityTokenDescriptor);

            return(signedClientAssertion);
        }
Esempio n. 2
0
        public static void Run()
        {
            var key = new RsaSecurityKey(RSA.Create(2048))
            {
                KeyId = Guid.NewGuid().ToString()
            };
            var jweKey = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes128CbcHmacSha256);
            var payloadRepresentation = new List <Claim>()
            {
                new("claim1", "10"),
                new("claim2", "claim2-value"),
                new ("name", "Bruno Brito"),
                new ("given_name", "Bruno"),
                new ("logins", "brunohbrito"),
                new ("logins", "bhdebrito"),
                new ("logins", "bruno_hbrito"),
            };

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;
            var jwt     = new SecurityTokenDescriptor
            {
                Issuer                = "me",
                Audience              = "you",
                IssuedAt              = now,
                NotBefore             = now,
                Expires               = now.AddMinutes(5),
                Subject               = new ClaimsIdentity(payloadRepresentation),
                EncryptingCredentials = jweKey
            };

            var jwe = handler.CreateToken(jwt);

            Console.ResetColor();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("JWE: ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(jwe);
            Console.ResetColor();


            var result = handler.ValidateToken(jwe,
                                               new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = jweKey.Key
            });
            var claims = JsonSerializer.Serialize(result.Claims, new JsonSerializerOptions()
            {
                WriteIndented = true
            });

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Claims: ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(claims);
            Console.ResetColor();
        }
        public IActionResult GetJwtForChat()
        {
            Account account = _accountService.GetAccount(Guid.Parse(HttpContext.User.Identity.Name));

            var iat = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
            var exp = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5)).ToUnixTimeSeconds();

            var payload = "{" +
                          "\"iat\":" + iat.ToString() + ", " +
                          "\"exp\":" + exp.ToString() + ", " +
                          "\"external_id\":\"" + account.Id.ToString() + "\", " +
                          "\"name\":\"" + account.FirstName + "\", " +
                          "\"email\":\"" + account.Email + "\"" +
                          "}";

            var jsonWebTokenHandler = new JsonWebTokenHandler();

            //var jsonWebToken = new JsonWebToken("{\"typ\":\"JWT\", \"alg\":\"HS256\"}", payload);

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["ZendeskSharedKey"]));

            var signingCredentials = new SigningCredentials(key, "HS256");

            var token = jsonWebTokenHandler.CreateToken(payload, signingCredentials);

            return(Ok(token));
        }
Esempio n. 4
0
        public static void Authorize()
        {
            var txtreader = new StringReader(Authorization.privateKey);
            var rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters) new PemReader(txtreader).ReadObject());

            var jwtsigner = new JsonWebTokenHandler();
            var now       = DateTime.UtcNow;

            var descriptor = new SecurityTokenDescriptor
            {
                Issuer   = Authorization.clientId,
                Audience = "https://xenqu.com",
                Expires  = now.AddMinutes(5),
                Claims   = new Dictionary <string, object> {
                    { "sub", Authorization.subscriber }
                },
                SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsaParams), "RS256")
            };

            var data = "grant_type=" + Uri.EscapeDataString("urn:ietf:params:oauth:grant-type:jwt-bearer") +
                       "&assertion=" + Uri.EscapeDataString(jwtsigner.CreateToken(descriptor));

            var provider = ServiceProvider.Instance;
            var results  = JObject.Parse(provider.PostData("/oauth2/token", "application/x-www-form-urlencoded", data));

            Authorization.tokenKey     = (string)results["token"];
            Authorization.tokenSecret  = (string)results["token_secret"];
            Authorization.tokenExpires = Convert.ToDouble((string)results["expires"]);
        }
Esempio n. 5
0
        /// <summary>
        /// Generate JWT
        /// </summary>
        /// <returns></returns>
        internal string GenerateToken()
        {
            try
            {
                // ... Build ClaimSet
                var claims = new ClaimsIdentity(new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Sub, AppId)
                });

                // ... Build Token Descriptor
                var securityTokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = claims,
                    Audience           = EndPoint,
                    Issuer             = AppId,
                    NotBefore          = DateTime.Now,
                    Expires            = DateTime.Now.AddMinutes(ExpiryMinutes),
                    SigningCredentials = new X509SigningCredentials(X509Cert)
                };

                // ... Build JWT Token
                var handler = new JsonWebTokenHandler();
                return(handler.CreateToken(securityTokenDescriptor));
            }
            catch (Exception ex)
            {
                throw new Exception("Failed in Generate JWT, error " + ex.Message);
            }
        }
        private void CreateTokenButton_Click(object sender, RoutedEventArgs e)
        {
            var principal = Principal.Create("InMemory",
                                             new Claim(ClaimTypes.Name, UserName.Text));
            var tokenType = GetTokenType();

            var           sts = new STS();
            SecurityToken token;

            var success = sts.TryIssueToken(
                new EndpointReference(Realm.Text),
                principal,
                tokenType,
                out token);

            if (success)
            {
                if (tokenType == TokenTypes.Saml2TokenProfile11 || tokenType == TokenTypes.Saml11TokenProfile11)
                {
                    var xml = token.ToTokenXmlString();
                    Output.Text = XElement.Parse(xml).ToString();
                }
                if (tokenType == TokenTypes.JsonWebToken)
                {
                    var tokenString = new JsonWebTokenHandler().WriteToken(token);
                    Output.Text = tokenString;
                }
            }
            else
            {
                throw new Exception("Error");
            }
        }
        public void ShouldGetCurrentToSignAndValidateJws(string algorithm, KeyType keyType)
        {
            var options = new JwksOptions()
            {
                Jws = JwsAlgorithm.Create(algorithm, keyType), KeyPrefix = $"{nameof(JsonWebKeySetServiceTests)}_"
            };

            _jwksService.GenerateSigningCredentials(options);
            var signingCredentials = _jwksService.GetCurrentSigningCredentials();
            var handler            = new JsonWebTokenHandler();
            var now        = DateTime.Now;
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jwt    = handler.CreateToken(descriptor);
            var result = handler.ValidateToken(jwt,
                                               new TokenValidationParameters
            {
                ValidIssuer      = "me",
                ValidAudience    = "you",
                IssuerSigningKey = signingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
Esempio n. 8
0
        public static async Task <IActionResult> Run([HttpTrigger(Microsoft.Azure.WebJobs.Extensions.Http.AuthorizationLevel.Anonymous)] HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            JsonWebTokenHandler handler = new JsonWebTokenHandler();
            string tokenString          = req.Headers["X-MS-TOKEN-AAD-ID-TOKEN"].ToString();

            var token = handler.ReadJsonWebToken(tokenString);


            StringBuilder sb = new StringBuilder();

            token.Claims.ToList().ForEach(a =>
            {
                sb.Append($"{a.Type} :: {a.Value}");
                sb.Append(System.Environment.NewLine);
            });

            var claimString = sb.ToString();

            var nameClaim = token.Claims.Where(c => c.Type == "given_name").FirstOrDefault();

            var name = string.Empty;

            if (nameClaim != null)
            {
                name = nameClaim.Value;
            }

            return(new OkObjectResult($"Hello, {name}.{System.Environment.NewLine}{System.Environment.NewLine}CLAIMS:{System.Environment.NewLine}{claimString}"));
        }
Esempio n. 9
0
        /// <summary>
        /// Creates the authorization token for requests made by users who have logged in.
        /// </summary>
        /// <param name="email">The email/username of the user which will be embedded in the token, and later retrieved for validation</param>
        /// <returns></returns>
        private string CreateJsonWebToken(string email)
        {
            try {
                JsonWebToken token = new JsonWebToken();
                token.Header = new Thinktecture.IdentityModel.Tokens.JwtHeader
                {
                    SignatureAlgorithm = Thinktecture.IdentityModel.Constants.JwtConstants.SignatureAlgorithms.HMACSHA256,
                    SigningCredentials = new HmacSigningCredentials("Dc9Mpi3jbooUpBQpB/4R7XtUsa3D/ALSjTVvk8IUZbg=")
                };

                token.Issuer   = "https://chatapiidsvr3/embedded";
                token.Audience = new Uri("https://chatapi");
                token.Claims   = new Dictionary <string, string>
                {
                    { ClaimTypes.NameIdentifier, email },
                    { ClaimTypes.Expiration, DateTime.UtcNow.AddDays(2).ToString() }
                };


                JsonWebTokenHandler handler = new JsonWebTokenHandler();

                string result = handler.WriteToken(token);
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void ShouldValidateJwe(string algorithm, KeyType keyType, string encryption)
        {
            var options = new JwksOptions()
            {
                KeyPrefix = $"{nameof(JsonWebKeySetServiceTests)}_",
                Jwe       = JweAlgorithm.Create(algorithm, keyType).WithEncryption(encryption)
            };

            var encryptingCredentials = _jwksService.GenerateEncryptingCredentials(options);

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;
            var jwt     = new SecurityTokenDescriptor
            {
                Issuer                = "me",
                Audience              = "you",
                IssuedAt              = now,
                NotBefore             = now,
                Expires               = now.AddMinutes(5),
                Subject               = new ClaimsIdentity(GenerateClaim().Generate(5)),
                EncryptingCredentials = encryptingCredentials
            };

            var jwe    = handler.CreateToken(jwt);
            var result = handler.ValidateToken(jwe,
                                               new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = encryptingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
        public void CanValidateES256()
        {
            const string token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q";
            var          x     = Base64Url.DeserializeBytes("f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", "ECDSA key X value");
            var          y     = Base64Url.DeserializeBytes("x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", "ECDSA key Y value");

            var key = new ECDsaSecurityKey(ECDsa.Create(new ECParameters
            {
                Q = new ECPoint
                {
                    X = x,
                    Y = y
                },
                Curve = ECCurve.NamedCurves.nistP384
            }));

            IdentityModelEventSource.ShowPII = true;

            var result = new JsonWebTokenHandler().ValidateToken(token, new TokenValidationParameters
            {
                IssuerSigningKey = key,
                ClockSkew        = TimeSpan.FromDays(4000),
                ValidIssuer      = "joe",
                ValidateAudience = false
            });

            result.IsValid.ShouldBeTrue();
        }
Esempio n. 12
0
        public static bool Validate(string jwtToValidate, string jwks, out IDictionary <string, object>?claims)
        {
            JsonWebKeySet jwksObject = new(jwks);

            var tokenValidationResult = new JsonWebTokenHandler().ValidateToken(
                jwtToValidate,
                new()
            {
                IssuerSigningKey      = jwksObject.GetSigningKeys().First(),
                CryptoProviderFactory = new() { CacheSignatureProviders = false },
                ValidateAudience      = false,
                ValidateIssuer        = false,
                ValidateLifetime      = false
            });

            if (!tokenValidationResult.IsValid)
            {
                claims = null;

                return(false);
            }

            claims = tokenValidationResult.Claims;

            return(true);
        }
Esempio n. 13
0
        public string GenerateUserToken(User user)
        {
            byte[] key           = Encoding.ASCII.GetBytes(_configuration["Auth:TokenSecret"]);
            var    tokenHandle   = new JsonWebTokenHandler();
            int    tokenDurHours = _configuration.GetValue <int>("Auth:TokenDuration");

            string[] userRoles = user.Roles.Select(u => u.Role.Name).ToArray();

            var claims = new Dictionary <string, object>
            {
                { nameof(User.Id), user.Id },
                { nameof(User.Name), user.Name },
                { nameof(User.Group), user.Group },
                { "Roles", userRoles }
            };

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Claims             = claims,
                Expires            = DateTime.UtcNow.AddHours(tokenDurHours),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            string token = tokenHandle.CreateToken(tokenDescriptor);

            Console.WriteLine(token);
            return(token);
        }
        public static void Run()
        {
            var tokenHandler = new JsonWebTokenHandler();
            var key          = new RsaSecurityKey(RSA.Create(2048))
            {
                KeyId = Guid.NewGuid().ToString()
            };

            Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSsaPssSha256);
            var lastJws = tokenHandler.CreateToken(Jwt);

            Console.WriteLine($"{lastJws}{Environment.NewLine}");

            // Store in filesystem
            // Store HMAC os Filesystem, recover and test if it's valid
            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            File.WriteAllText("current-rsa.key", JsonConvert.SerializeObject(jwk));


            var storedJwk = JsonConvert.DeserializeObject <JsonWebKey>(File.ReadAllText("current-rsa.key"));

            TokenValidationParams.IssuerSigningKey = storedJwk;
            var validationResult = tokenHandler.ValidateToken(lastJws, TokenValidationParams);

            Console.WriteLine(validationResult.IsValid);
        }
Esempio n. 15
0
        private static string GetSignedClientAssertion(string tenantId, string confidentialClientID,
                                                       string certificatePath, string certPass)
        {
            var cert = new X509Certificate2(certificatePath, certPass, X509KeyStorageFlags.EphemeralKeySet);

            // JsonWebTokenHandler will add defaults
            var claims = new Dictionary <string, object>()
            {
                { "aud", $"https://login.microsoftonline.com/{tenantId}/oauth2/token" },
                { "iss", confidentialClientID },
                { "jti", Guid.NewGuid().ToString() },
                { "sub", confidentialClientID }
            };

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Claims             = claims,
                SigningCredentials = new X509SigningCredentials(cert)
            };

            var handler = new JsonWebTokenHandler();
            var signedClientAssertion = handler.CreateToken(securityTokenDescriptor);

            return(signedClientAssertion);
        }
Esempio n. 16
0
        /// <summary>
        /// 验证 Token
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="jwtSettings"></param>
        /// <returns></returns>
        public static (bool IsValid, JsonWebToken Token) Validate(string accessToken, JWTSettingsOptions jwtSettings)
        {
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.IssuerSigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var tokenValidationParameters = CreateTokenValidationParameters(jwtSettings);

            if (tokenValidationParameters.IssuerSigningKey == null)
            {
                tokenValidationParameters.IssuerSigningKey = creds.Key;
            }

            var tokenHandler = new JsonWebTokenHandler();

            try
            {
                var tokenValidationResult = tokenHandler.ValidateToken(accessToken, tokenValidationParameters);
                if (!tokenValidationResult.IsValid)
                {
                    return(false, null);
                }

                var jsonWebToken = tokenValidationResult.SecurityToken as JsonWebToken;
                return(true, jsonWebToken);
            }
            catch
            {
                return(false, default);
Esempio n. 17
0
        public async Task <IActionResult> Post([FromBody] UserRequestModel credentials)
        {
            ApiUser apiUser = new ApiUser(credentials.UserName);
            var     result  = await _userManager.CreateAsync(apiUser, credentials.Password);

            if (!result.Succeeded)
            {
                _logger.LogError($"User creation error: {String.Join(" | ", result.Errors.Select(x => x.Description).ToArray())}");
                throw new ApplicationException("Could not create user.");
            }

            var now          = DateTime.Now;
            var key          = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_options.SecretKey));
            var tokenHandler = new JsonWebTokenHandler();
            var descriptor   = new SecurityTokenDescriptor
            {
                Issuer    = _options.Issuer,
                IssuedAt  = now,
                NotBefore = now,
                Expires   = now.AddHours(1),
                Claims    = new Dictionary <string, object> {
                    { JwtRegisteredClaimNames.Sub, apiUser.UserName }
                },
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            };

            TegetgramUserDTO user = await _userService.GetUser(apiUser.UserName, apiUser.UserName);

            return(Ok(new
            {
                access_token = tokenHandler.CreateToken(descriptor),
                user = user
            }));
        }
        public void ManualWriteNoSig()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.None
                },

                Audience       = new Uri("http://foo.com"),
                Issuer         = "dominick",
                ExpirationTime = 500000,

                Claims = new Dictionary <string, string>
                {
                    { ClaimTypes.Name, "dominick" },
                    { ClaimTypes.Email, "*****@*****.**" }
                }
            };

            var handler = new JsonWebTokenHandler();

            var token = handler.WriteToken(jwt);

            Trace.WriteLine(token);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(token));

            var parts = token.Split('.');

            Assert.IsTrue(parts.Length == 2, "JWT should have excactly 2 parts");
        }
        private static TokenValidationResult ValidateSignedToken(string serviceJwt, JsonWebKeySet jwksTrustedSigningKeys, bool includeDetails)
        {
            // Now validate the JWT using the signing keys we just discovered
            TokenValidationParameters tokenValidationParams = new TokenValidationParameters
            {
                ValidateAudience  = false,
                ValidateIssuer    = false,
                IssuerSigningKeys = jwksTrustedSigningKeys.GetSigningKeys()
            };
            var jwtHandler     = new JsonWebTokenHandler();
            var validatedToken = jwtHandler.ValidateToken(serviceJwt, tokenValidationParams);

            if (!validatedToken.IsValid)
            {
                throw new ArgumentException("JWT is not valid (signature verification failed)");
            }

            Logger.WriteLine($"JWT signature validation           : True");
            if (includeDetails)
            {
                X509SecurityKey signingKey = (X509SecurityKey)validatedToken.SecurityToken.SigningKey;
                if (signingKey.PublicKey is RSA publicKey)
                {
                    var modulus  = publicKey.ExportParameters(false).Modulus;
                    var exponent = publicKey.ExportParameters(false).Exponent;
                    Logger.WriteLine(37, 80, "    RSA signing key modulus        : ", BitConverter.ToString(modulus).Replace("-", ""));
                    Logger.WriteLine(37, 80, "    RSA signing key exponent       : ", BitConverter.ToString(exponent).Replace("-", ""));
                }
                else
                {
                    Logger.WriteLine($"Unexpected signing key type.  Signing Key Type: {signingKey.PublicKey.GetType()}");
                }
            }
            return(validatedToken);
        }
Esempio n. 20
0
        private static TlsFederationMetadata Validate(JwsBody body)
        {
            foreach (var signature in body.Signatures)
            {
                var key     = JsonWebKey.Create(File.ReadAllText("Skolverket.jwk"));
                var handler = new JsonWebTokenHandler();

                var jwsCompact = signature.Protected + "." + body.Payload + "." + signature.Signature;

                var validation = new TokenValidationParameters()
                {
                    IssuerSigningKey = key,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                    ValidateIssuer   = false
                };

                var tokenValidation = handler.ValidateToken(jwsCompact, validation);

                if (tokenValidation.IsValid)
                {
                    var base64 = body.Payload.PadRight(body.Payload.Length + (4 - body.Payload.Length % 4) % 4, '=');

                    var content = Encoding.UTF8.GetString(Convert.FromBase64String(base64));

                    return(JsonConvert.DeserializeObject <TlsFederationMetadata>(content));
                }
                else
                {
                    return(null);
                }
            }

            return(null);
        }
Esempio n. 21
0
        /// <summary>
        /// Instantiates an instance of private_key_jwt secret validator (used for testing)
        /// </summary>
        internal JwtRequestValidator(string audience, ILogger <JwtRequestValidator> logger)
        {
            _audienceUri = audience;

            Logger  = logger;
            Handler = new JsonWebTokenHandler();
        }
        public async Task <JsonWebToken> ValidateTokenAsync(string accessToken)
        {
            var tokenHandler = new JsonWebTokenHandler();
            var tokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudience         = ".Api",
                IssuerSigningKey      = SecurityKey,
                RequireExpirationTime = false,
                ValidateLifetime      = false,
                ValidateIssuer        = false
            };

            var tokenValidationResult = tokenHandler.ValidateToken(accessToken, tokenValidationParameters);

            var jwt = tokenValidationResult.SecurityToken as JsonWebToken;

            if (jwt == null)
            {
                throw new Exception("Invalid token format.");
            }

            await _tokenRepository.GetAsync(new Guid(jwt.Id));

            return(jwt);
        }
Esempio n. 23
0
        /// <summary>
        /// Validates token and reads the token payload.
        /// </summary>
        /// <param name="encodedToken">Raw, encoded ID Token, as received from the server.</param>
        /// <param name="verifyWithKey">RSA public key to use for verifying OpenID Connect ID token signature, if an ID token is present in the response.
        /// If <c>null</c>, no verification is done.</param>
        /// <returns>The token payload as a JSON string.</returns>
        /// <exception cref="SecurityTokenInvalidSignatureException">Thrown if token signature verification fails.</exception>
        public static string ReadPayload(string encodedToken, RSA verifyWithKey)
        {
            JsonWebToken token;

            if (verifyWithKey == null)
            {
                token = new JsonWebTokenHandler().ReadJsonWebToken(encodedToken);
            }
            else
            {
                var key = new RsaSecurityKey(verifyWithKey);
                var validationParams = new TokenValidationParameters()
                {
                    IssuerSigningKey = key,
                    ValidateAudience = false,
                    ValidateIssuer   = false,
                    ValidateLifetime = false,
                };
                var validationResult = new JsonWebTokenHandler().ValidateToken(encodedToken, validationParams);
                if (!validationResult.IsValid)
                {
                    if (validationResult.Exception != null)
                    {
                        throw validationResult.Exception;
                    }

                    throw new SecurityTokenInvalidSignatureException("Invalid ID token signature");
                }

                token = validationResult.SecurityToken as JsonWebToken;
            }

            return(Base64Url.DecodeString(token.EncodedPayload));
        }
Esempio n. 24
0
        public static string GetToken(IEnumerable <string>?roles = null, IEnumerable <string>?scopes = null)
        {
            roles ??= Array.Empty <string>();
            scopes = new[] { "user_impersonation" }.Concat(scopes ?? Array.Empty <string>());

            var tokenHandler = new JsonWebTokenHandler();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience = "tests",
                Issuer   = "tests",
                Claims   = new Dictionary <string, object>
                {
                    ["name"]        = "Testy McTesterson",
                    ["given_name"]  = "Testy",
                    ["family_name"] = "McTesterson",
                    ["unique_name"] = "*****@*****.**",
                    ["upn"]         = "*****@*****.**",
                    ["acr"]         = "1",
                    ["amr"]         = new[] { "pwd", "mfa" },
                    ["roles"]       = roles.ToArray(),
                    ["oid"]         = PrincipalId.ToString(),
                    ["appid"]       = Guid.NewGuid().ToString(),
                    ["deviceid"]    = Guid.NewGuid().ToString(),
                    ["sub"]         = "Xwq2sQJEYUbxkwV_0V9Gg_nIAW2mWX9tJnt_Gqrkdbm",
                    ["tid"]         = Guid.NewGuid().ToString(),
                    ["scp"]         = string.Join(" ", scopes),
                    ["ver"]         = "1.0",
                },
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SigningKey)), SecurityAlgorithms.HmacSha256Signature),
            };

            return(tokenHandler.CreateToken(tokenDescriptor));
        }
Esempio n. 25
0
        public void ShouldValidateJwe(string algorithm, string encryption)
        {
            var key = new CryptographicKey(Algorithm.Create(algorithm).WithContentEncryption(encryption));
            var encryptingCredentials = new EncryptingCredentials(key, algorithm, encryption);

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;
            var jwt     = new SecurityTokenDescriptor
            {
                Issuer                = "me",
                Audience              = "you",
                IssuedAt              = now,
                NotBefore             = now,
                Expires               = now.AddMinutes(5),
                Subject               = new ClaimsIdentity(GenerateClaim().Generate(5)),
                EncryptingCredentials = encryptingCredentials
            };

            var jwe    = handler.CreateToken(jwt);
            var result = handler.ValidateToken(jwe,
                                               new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = encryptingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
        public void AddJsonWebToken(string issuer, string audience, string signingKey, AuthenticationOptions options)
        {
            var config   = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();

            registry.AddTrustedIssuer(issuer, issuer);
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();

            issuerResolver.AddSigningKey(issuer, signingKey);
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience));

            var handler = new JsonWebTokenHandler();

            handler.Configuration = config;

            AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection {
                    handler
                },
                Options = options
            });
        }
Esempio n. 27
0
        public void ShouldValidateJws(string algorithm)
        {
            var signingCredentials = new SigningCredentials(new CryptographicKey(algorithm), algorithm);
            var handler            = new JsonWebTokenHandler();
            var now = DateTime.Now;
            var jwt = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jws    = handler.CreateToken(jwt);
            var result = handler.ValidateToken(jws,
                                               new TokenValidationParameters
            {
                ValidIssuer      = "me",
                ValidAudience    = "you",
                IssuerSigningKey = signingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
Esempio n. 28
0
        public T GetClaim <T>(string jwt, JwtClaim claim)
        {
            if (jwt == null)
            {
                throw new UnprocessableException();
            }

            string       key      = Enum.GetName(typeof(JwtClaim), claim);
            var          handler  = new JsonWebTokenHandler();
            JsonWebToken jwtToken = handler.ReadJsonWebToken(jwt);

            string foundClaim = jwtToken.Claims?
                                .FirstOrDefault(c => c.Type.Equals(key, StringComparison.OrdinalIgnoreCase))?
                                .Value;

            if (typeof(T) == typeof(Guid))
            {
                return((T)Convert.ChangeType(Guid.Parse(foundClaim), typeof(T), CultureInfo.InvariantCulture));
            }
            if (typeof(T) == typeof(AccountRole))
            {
                return((T)Convert.ChangeType(Enum.Parse <AccountRole>(foundClaim), typeof(T), CultureInfo.InvariantCulture));
            }

            return(default);
Esempio n. 29
0
        private void ValidateAttestationClaims(EnclaveType enclaveType, string attestationToken, EnclavePublicKey enclavePublicKey, byte[] nonce)
        {
            // Read the json token
            JsonWebToken token = null;

            try
            {
                JsonWebTokenHandler tokenHandler = new JsonWebTokenHandler();
                token = tokenHandler.ReadJsonWebToken(attestationToken);
            }
            catch (ArgumentException argumentException)
            {
                throw new AlwaysEncryptedAttestationException(String.Format(Strings.FailToParseAttestationToken, argumentException.Message));
            }

            // Get all the claims from the token
            Dictionary <string, string> claims = new Dictionary <string, string>();

            foreach (Claim claim in token.Claims.ToList())
            {
                claims.Add(claim.Type, claim.Value);
            }

            // Get Enclave held data claim and validate it with the Base64UrlEncode(enclave public key)
            ValidateClaim(claims, "aas-ehd", enclavePublicKey.PublicKey);

            if (enclaveType == EnclaveType.Vbs)
            {
                // Get rp_data claim and validate it with the Base64UrlEncode(nonce)
                ValidateClaim(claims, "rp_data", nonce);
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Create a new client secret (per request).
        /// </summary>
        /// <param name="issuer">Your account's team ID found in the dev portal.</param>
        /// <param name="audience">Apple authority.</param>
        /// <param name="subject">The service id (client_id).</param>
        /// <param name="privateKey">Base64 encoded private key.</param>
        /// <param name="privateKeyId">The key id.</param>
        /// <param name="duration">Expiry can be a maximum of 6 months - generate one per request or re-use until expiration. Defaults to 5 minutes.</param>
        public static string CreateNewToken(string issuer, string audience, string subject, string privateKey, string privateKeyId, TimeSpan?duration = null)
        {
            duration ??= TimeSpan.FromMinutes(5);
            var now   = DateTime.UtcNow;
            var ecdsa = ECDsa.Create();

            if (privateKey.StartsWith('-'))
            {
                var lines = privateKey.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                privateKey = string.Join("", lines.Skip(1).Take(lines.Length - 2));
            }
//#if NETCOREAPP3_1
            ecdsa?.ImportPkcs8PrivateKey(Convert.FromBase64String(privateKey), out _);
//#else
            //ecdsa?.ImportFromPem(privateKey);
//#endif
            var handler = new JsonWebTokenHandler();
            var key     = new ECDsaSecurityKey(ecdsa)
            {
                KeyId = privateKeyId
            };

            return(handler.CreateToken(new SecurityTokenDescriptor {
                Issuer = issuer,
                Audience = audience,
                Claims = new Dictionary <string, object> {
                    { "sub", subject }
                },
                Expires = now.Add(duration.Value),
                IssuedAt = now,
                NotBefore = now,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256)
            }));
        }
        public static void AddJsonWebToken(this AuthenticationConfiguration configuration, string issuer, string audience, string signingKey, AuthenticationOptions options)
        {
            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer(issuer, issuer);
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey(issuer, signingKey);
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience));

            var handler = new JsonWebTokenHandler();
            handler.Configuration = config;

            configuration.AddMapping(new AuthenticationOptionMapping
            {
                TokenHandler = new SecurityTokenHandlerCollection { handler },
                Options = options
            });
        }