public static string EncodeJWT(JWTSecurityToken jwt)
        {
            // Create JWT handler
            // This object is used to write/sign/decode/validate JWTs
            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Serialize the JWT
            // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>
            string jwtOnTheWire = jwtHandler.WriteToken(jwt);

            return jwtOnTheWire;
        }
Ejemplo n.º 2
0
        public static string EncodeJWT(JWTSecurityToken jwt)
        {
            // Create JWT handler
            // This object is used to write/sign/decode/validate JWTs
            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Serialize the JWT
            // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>
            string jwtOnTheWire = jwtHandler.WriteToken(jwt);

            return(jwtOnTheWire);
        }
Ejemplo n.º 3
0
        public static string DecodeJWT(JWTSecurityToken jwt)
        {
            // Create JWT handler
            // This object is used to write/sign/decode/validate JWTs
            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Serialize the JWT
            // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>
            string jwtOnTheWire = jwtHandler.WriteToken(jwt);

            // Parse JWT from the Base64UrlEncoded wire form (<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
            JWTSecurityToken parsedJwt = jwtHandler.ReadToken(jwtOnTheWire) as JWTSecurityToken;

            return(parsedJwt.ToString());
        }
        public static string DecodeJWT(JWTSecurityToken jwt)
        {
            // Create JWT handler
            // This object is used to write/sign/decode/validate JWTs
            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Serialize the JWT
            // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>
            string jwtOnTheWire = jwtHandler.WriteToken(jwt);

            // Parse JWT from the Base64UrlEncoded wire form (<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
            JWTSecurityToken parsedJwt = jwtHandler.ReadToken(jwtOnTheWire) as JWTSecurityToken;

            return parsedJwt.ToString();
        }
        /// <summary>
        /// Returns the OpenID token already serialized to be sent to the client
        /// </summary>
        /// <param name="tokenRequest"></param>
        /// <returns></returns>
        public static OpenIdConnectTokenRequestResponse GenerateOpenIdConnectToken(string issuer, string audience, string subject, string code, string scopes, int expiresIn=0)
        {
            if (string.IsNullOrEmpty(issuer) || string.IsNullOrEmpty(audience) || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(code) || string.IsNullOrEmpty(scopes) || expiresIn<0)
            {
                throw new ApplicationException("The parameters provided are not valid");
            }

            DateTime issuedAt = DateTime.UtcNow;
            DateTime expires = DateTime.UtcNow.AddMinutes(2);

            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Create a simple JWT claim set
            IList<Claim> claims = new List<Claim>() {
                                            new Claim("sub", subject),
                                            new Claim("iat", ToUnixTime(issuedAt).ToString()) };

            JWTSecurityToken jwt = new JWTSecurityToken(issuer, audience, claims, null, issuedAt, expires);

            OpenIdConnectTokenRequestResponse tokenResponse = new OpenIdConnectTokenRequestResponse();

            string newAccessToken = GenerateOpenIdConnectToken();
            string newRefreshToken = GenerateOpenIdConnectToken();

            string jwtReadyToBeSent = jwtHandler.WriteToken(jwt);

            tokenResponse.access_token = newAccessToken;

            tokenResponse.expires_in = expiresIn.ToString();

            if (scopes.Contains("offline_access"))
            {
                tokenResponse.refresh_token = newRefreshToken.ToString();
            }
            else
            {
                tokenResponse.refresh_token = null;
            }

            tokenResponse.id_token = jwtReadyToBeSent;
            tokenResponse.token_type = "Bearer";
            //string serializedResponse = JsonConvert.SerializeObject(tokenResponse);

            return tokenResponse;
        }
Ejemplo n.º 6
0
        public static bool IsTokenValid(JWTSecurityToken jwt, string audience, string issuer, byte[] signature)
        {
            bool result = false;

            // Create token validation parameters for the signed JWT
            // This object will be used to verify the cryptographic signature of the received JWT
            TokenValidationParameters validationParams =
                new TokenValidationParameters()
            {
                AllowedAudience    = audience,
                ValidIssuer        = issuer,
                ValidateExpiration = true,
                ValidateNotBefore  = false,
                ValidateIssuer     = true,
                ValidateSignature  = true,
                //SigningToken = null

                SigningToken = new BinarySecretSecurityToken(signature)
            };



            // Create JWT handler
            // This object is used to write/sign/decode/validate JWTs
            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Serialize the JWT
            // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>
            string jwtOnTheWire = jwtHandler.WriteToken(jwt);

            try
            {
                // Validate the token signature (we provide the shared symmetric key in `validationParams`)
                // This will throw if the signature does not validate
                // jwtHandler.ValidateToken(jwtOnTheWire, validationParams);
                jwtHandler.ValidateToken(jwt, validationParams);
                result = true;
            }
            catch
            {
                result = false;
            }
            return(result);
        }
Ejemplo n.º 7
0
        public TokenResponse ConvertSamlToJwt(SecurityToken securityToken, string scope)
        {
            var subject = ValidateSamlToken(securityToken);

            var descriptor = new SecurityTokenDescriptor
            {
                Subject            = subject,
                AppliesToAddress   = scope,
                SigningCredentials = new X509SigningCredentials(_configuration.Keys.SigningCertificate),
                TokenIssuerName    = _configuration.Global.IssuerUri,
                Lifetime           = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(_configuration.AdfsIntegration.AuthenticationTokenLifetime))
            };

            var jwtHandler = new JWTSecurityTokenHandler();
            var jwt        = jwtHandler.CreateToken(descriptor);

            return(new TokenResponse
            {
                AccessToken = jwtHandler.WriteToken(jwt),
                ExpiresIn = _configuration.AdfsIntegration.AuthenticationTokenLifetime
            });
        }
        public static bool IsTokenValid(JWTSecurityToken jwt, string audience, string issuer, byte[] signature)
        {
            bool result = false;

            // Create token validation parameters for the signed JWT
            // This object will be used to verify the cryptographic signature of the received JWT
            TokenValidationParameters validationParams =
                new TokenValidationParameters()
                {
                    AllowedAudience = audience,
                    ValidIssuer = issuer,
                    ValidateExpiration = true,
                    ValidateNotBefore = false,
                    ValidateIssuer = true,
                    ValidateSignature = true,
                    //SigningToken = null

                    SigningToken = new BinarySecretSecurityToken(signature)
                };

            // Create JWT handler
            // This object is used to write/sign/decode/validate JWTs
            JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler();

            // Serialize the JWT
            // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>
            string jwtOnTheWire = jwtHandler.WriteToken(jwt);

            try
            {
                // Validate the token signature (we provide the shared symmetric key in `validationParams`)
                // This will throw if the signature does not validate
                // jwtHandler.ValidateToken(jwtOnTheWire, validationParams);
                jwtHandler.ValidateToken(jwt, validationParams);
                result = true;
            }
            catch
            {
                result = false;
            }
            return result;
        }
        public TokenResponse ConvertSamlToJwt(SecurityToken securityToken, string scope)
        {
            var subject = ValidateSamlToken(securityToken);

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = subject,
                AppliesToAddress = scope,
                SigningCredentials = new X509SigningCredentials(_configuration.Keys.SigningCertificate),
                TokenIssuerName = _configuration.Global.IssuerUri,
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(_configuration.AdfsIntegration.AuthenticationTokenLifetime))
            };

            var jwtHandler = new JWTSecurityTokenHandler();
            var jwt = jwtHandler.CreateToken(descriptor);

            return new TokenResponse
            {
                AccessToken = jwtHandler.WriteToken(jwt),
                ExpiresIn = _configuration.AdfsIntegration.AuthenticationTokenLifetime
            };
        }