public async Task<string> GenerateAccessToken(SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters)
 {
     if (tokenCache.ContainsKey(tokenDescriptor) && tokenDescriptor.Lifetime.Expires > DateTime.UtcNow.AddMinutes(-1))
     {
         return tokenCache[tokenDescriptor];
     }
     tokenDescriptor.Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10));
     var accessToken = await this.innerTokenProvider.GenerateAccessToken(tokenDescriptor, validationParameters);
     return tokenCache.AddOrUpdate(tokenDescriptor, accessToken, (d, t) => accessToken);
 }
Exemple #2
1
        public ActionResult Index(string token)
        {
            try
            {
                var validationParameters = new TokenValidationParameters
                {
                    IssuerSigningToken = new BinarySecretSecurityToken(
                            TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"])),
                    ValidIssuer = ConfigurationManager.AppSettings["auth0:Domain"],
                    ValidAudience = ConfigurationManager.AppSettings["auth0:ClientId"]
                };

                var handler = new JwtSecurityTokenHandler();
                SecurityToken securityToken;
                ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out securityToken);
                ClaimsIdentity identity = principal.Identity as ClaimsIdentity;
                identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0"));
                identity.AddClaim(new Claim(ClaimTypes.Name, identity.FindFirst(ClaimTypes.Email).Value));

                var sessionToken = new SessionSecurityToken(principal, TimeSpan.FromMinutes(15));
                FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken);

                return RedirectToAction("Change");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Unauthorized");
            }
        }
Exemple #3
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string tokenRaw = string.Empty;

            try
            {
                if (!TryRetrieveToken(request, out tokenRaw)) { return base.SendAsync(request, cancellationToken); }

                var validationParameters = new TokenValidationParameters()
                {

                    ValidIssuer = SecurityHelper.CertificateValidIssuer,
                    ValidAudience = SecurityHelper.CertificateValidAudience,
                    IssuerSigningToken = new X509SecurityToken(SecurityHelper.GetCertificate()),
                    ValidateLifetime = false,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    //ClockSkew = new TimeSpan(40, 0, 0)
                };

                SecurityToken token = new JwtSecurityToken();
                ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(tokenRaw, validationParameters, out token);

                Thread.CurrentPrincipal = principal;
                if (HttpContext.Current != null) { HttpContext.Current.User = Thread.CurrentPrincipal; }

            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }

            return base.SendAsync(request, cancellationToken);
        }
        private static bool ClaimFromValidIssuer(Claim claim, TokenValidationParameters tokenValidationParameters)
        {
            if (null == claim)
            {
                return false;
            }

            if (null == tokenValidationParameters)
            {
                return false;
            }

            if (null == tokenValidationParameters.ValidIssuers)
            {
                return false;
            }

            if (string.IsNullOrWhiteSpace(claim.Issuer) && string.IsNullOrWhiteSpace(claim.OriginalIssuer))
            {
                return false;
            }

            bool result =
                tokenValidationParameters
                .ValidIssuers
                .Any(
                    (string item) =>
                            string.Equals(item, claim.Issuer, StringComparison.OrdinalIgnoreCase)
                        || string.Equals(item, claim.OriginalIssuer, StringComparison.OrdinalIgnoreCase));
            return result;
        }
        public void should_create_valid_token()
        {
            var tokenString = _factory.CreateAssertionToken();

            var validationParameters = new TokenValidationParameters()
            {
                ValidIssuer = _clientId,
                ValidateIssuer = true,

                ValidAudience = _tokenEndpointUrl,
                ValidateAudience = true,

                IssuerSigningKey = new X509AsymmetricSecurityKey(_certificate),
                ValidateIssuerSigningKey = true,

                RequireSignedTokens = true,
                RequireExpirationTime = true
            };

            SecurityToken token;
            new JwtSecurityTokenHandler().ValidateToken(tokenString, validationParameters, out token);

            var jwt = (JwtSecurityToken) token;

            Assert.Equal(jwt.Header.Alg, JwtAlgorithms.RSA_SHA256);
            Assert.Equal(jwt.Subject, _clientId);
            Assert.Single(jwt.Claims, c => c.Type == JwtClaimTypes.JwtId);
        }
        public void JwtSecurityTokenHandler_Extensibility()
        {
            DerivedJwtSecurityTokenHandler handler = new DerivedJwtSecurityTokenHandler()
            {
                DerivedTokenType = typeof(DerivedJwtSecurityToken)
            };

            JwtSecurityToken jwt =
                new JwtSecurityToken
                (
                    issuer: Issuers.GotJwt,
                    audience: Audiences.AuthFactors,
                    claims: ClaimSets.Simple(Issuers.GotJwt, Issuers.GotJwt),
                    signingCredentials: KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2,
                    expires: DateTime.UtcNow + TimeSpan.FromHours(10),
                    notBefore: DateTime.UtcNow
                );

            string encodedJwt = handler.WriteToken(jwt);
            TokenValidationParameters tvp = new TokenValidationParameters()
            {
                IssuerSigningKey = KeyingMaterial.DefaultSymmetricSecurityKey_256,
                ValidateAudience = false,
                ValidIssuer = Issuers.GotJwt,
            };

            ValidateDerived(encodedJwt, handler, tvp, ExpectedException.NoExceptionExpected);
        }
        public Result<List<Claim>> ParseToken(string token)
        {
            var result = new Result<List<Claim>>();

            if (String.IsNullOrEmpty(token))
                return result;

            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = new TokenValidationParameters()
            {
                ValidAudience = "https://api.knowthyshelf.com",
                IssuerSigningToken = new BinarySecretSecurityToken(TOKEN_SECURITY_KEY),
                ValidIssuer = "self"
            };

            SecurityToken securityToken;
            var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
            var isValidClaim = principal.Claims.FirstOrDefault();
            if (isValidClaim?.Value == "IsValid" && securityToken.ValidFrom <= DateTime.UtcNow && securityToken.ValidTo >= DateTime.UtcNow)
            {
                result.ResultCode = Enums.ResultCode.Ok;
                result.Data = principal.Claims.ToList();
            }
            return result;
        }
Exemple #8
0
        public static ClaimsIdentity CreateIdentityFromToken(this string token, X509Certificate2 certificate = null)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            var tokenHandler = new JwtSecurityTokenHandler();

            if (certificate != null)
            {
                var x509SecurityToken    = new X509SecurityToken(certificate);
                var validationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidAudience      = Audience,
                    IssuerSigningToken = x509SecurityToken,
                    ValidIssuer        = Issuer,
                };

                System.IdentityModel.Tokens.SecurityToken validatedToken;
                var claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
                return(claimsPrincipal.Identity as ClaimsIdentity);
            }
            var jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token);

            return(new ClaimsIdentity(jwtToken.Claims, Issuer, JwtRegisteredClaimNames.UniqueName, CustomClaimTypes.Task));
        }
Exemple #9
0
        public IHttpActionResult DecodeToken(string access_token)
        {
            var tokenReceived = new JwtSecurityToken(access_token);

            var publicOnly = new RSACryptoServiceProvider();
            publicOnly.FromXmlString(_configuration.PublicKey.FromBase64String());
            var validationParameters = new TokenValidationParameters
            {
                ValidIssuer = _configuration.Issuer
               ,ValidAudience = "http://mysite.com"
               ,IssuerSigningToken = new RsaSecurityToken(publicOnly)
               ,ValidateLifetime = true
            };

            var recipientTokenHandler = new JwtSecurityTokenHandler();
            SecurityToken securityToken;
            var claimsPrincipal = recipientTokenHandler.ValidateToken(access_token, validationParameters, out securityToken);

            var currentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

            if (tokenReceived.Payload.Exp < currentTime)
            {
                throw new SecurityTokenValidationException(string.Format("Lifetime validation failed. The token is expired. ValidTo: '{0}' Current time: '{1}'.", tokenReceived.ValidTo, DateTime.UtcNow));
            }
          
            return Ok(new
            {
                header = tokenReceived.Header,
                payload = tokenReceived.Payload,
                current = currentTime
            });
        }
        protected virtual Task<TokenValidationResult> ValidateJwtAccessTokenAsync(string jwt)
        {
            var handler = new JwtSecurityTokenHandler();
            handler.Configuration = new SecurityTokenHandlerConfiguration();
            handler.Configuration.CertificateValidationMode = X509CertificateValidationMode.None;
            handler.Configuration.CertificateValidator = X509CertificateValidator.None;
            
            var parameters = new TokenValidationParameters
            {
                ValidIssuer = _settings.GetIssuerUri(),
                SigningToken = new X509SecurityToken(_settings.GetSigningCertificate()),
                AllowedAudience = string.Format(Constants.AccessTokenAudience, _settings.GetIssuerUri())
            };

            try
            {
                var id = handler.ValidateToken(jwt, parameters);

                return Task.FromResult(new TokenValidationResult
                {
                    Claims = id.Claims
                });
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("JWT token validation error: {0}", ex.ToString());

                return Task.FromResult(new TokenValidationResult
                {
                    IsError = true,
                    Error = Constants.ProtectedResourceErrors.InvalidToken
                });                
            }
        }
        public ClaimsPrincipal Validate(string jwtTokenAsBase64, JwtOptions options)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            string keyAsUtf8 = options.JwtSigningKeyAsUtf8;

            byte[] keyAsBytes = Encoding.UTF8.GetBytes(keyAsUtf8);

            SecurityToken signingToken = new BinarySecretSecurityToken(keyAsBytes);
            var tokenValidationParameters = new TokenValidationParameters
                                            {
                                                IssuerSigningToken = signingToken,
                                                ValidAudience = options.Audience,
                                                ValidIssuer = options.Issuer
                                            };
            ClaimsPrincipal principal;
            try
            {
                SecurityToken validatedToken;
                principal = tokenHandler.ValidateToken(jwtTokenAsBase64, tokenValidationParameters,
                    out validatedToken);
            }
            catch (Exception ex)
            {
                Debug.Write(ex, "error");
                principal = new ClaimsPrincipal(new ClaimsIdentity(authenticationType:""));
            }

            return principal;
        }
        private static bool ClaimsAuthorizedClient(Claim claim, TokenValidationParameters tokenValidationParameters)
        {
            if (null == claim)
            {
                return false;
            }

            if (!TokenHandler.ClaimFromValidIssuer(claim, tokenValidationParameters))
            {
                return false;
            }

            if (!TokenHandler.ClaimsApplicationIdentifier(claim))
            {
                return false;
            }

            if (string.IsNullOrWhiteSpace(claim.Value))
            {
                return false;
            }

            bool result =
                TokenHandler
                .AuthorizedClientApplicationIdentifiers
                .Value
                .Any(
                    (string item) =>
                        string.Equals(item, claim.Value, StringComparison.OrdinalIgnoreCase));
            return result;
        }
        public static ClaimsPrincipal AuthenticateIdToken(HttpApplication application, string id_token)
        {
            var config = OpenIdConfiguration.Current;
            var handler = new JwtSecurityTokenHandler();
            handler.CertificateValidator = X509CertificateValidator.None;
            if (!handler.CanReadToken(id_token))
            {
                throw new InvalidOperationException("No SecurityTokenHandler can authenticate this id_token!");
            }

            var parameters = new TokenValidationParameters();
            parameters.AllowedAudience = AADClientId;
            // this is just for Saml
            // paramaters.AudienceUriMode = AudienceUriMode.Always;
            parameters.ValidateIssuer = false;

            var tokens = new List<SecurityToken>();
            foreach (var key in config.IssuerKeys.Keys)
            {
                tokens.AddRange(key.GetSecurityTokens());
            }
            parameters.SigningTokens = tokens;

            // validate
            var principal = (ClaimsPrincipal)handler.ValidateToken(id_token, parameters);

            // verify nonce
            VerifyNonce(principal.FindFirst(NonceClaimType).Value);

            return principal;
        }
        public void End2End_OpenIdConnect()
        {
            SigningCredentials rsaSigningCredentials = 
                new SigningCredentials(
                    KeyingMaterial.RsaSecurityKey_Private2048, 
                    SecurityAlgorithms.RsaSha1Signature, 
                    SecurityAlgorithms.Sha256Digest, 
                    new SecurityKeyIdentifier(new NamedKeySecurityKeyIdentifierClause("kid", "NGTFvdK-fythEuLwjpwAJOM9n-A"))
                    );

            //"<RSAKeyValue><Modulus>rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
            RSA rsa = KeyingMaterial.RsaSecurityKey_2048.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha1Signature, false) as RSA;
            OpenIdConnectConfiguration configuration = OpenIdConnectConfigurationRetriever.GetAsync(OpenIdConfigData.OpenIdConnectMetadataFile, CancellationToken.None).Result;            
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwt = tokenHandler.CreateToken(
                configuration.Issuer,
                IdentityUtilities.DefaultAudience,
                IdentityUtilities.DefaultClaimsIdentity,
                DateTime.UtcNow,
                DateTime.UtcNow + TimeSpan.FromHours(1),
                rsaSigningCredentials );

            TokenValidationParameters validationParameters =
                new TokenValidationParameters
                {
                    IssuerSigningTokens = configuration.SigningTokens,
                    ValidAudience = IdentityUtilities.DefaultAudience,
                    ValidIssuer = configuration.Issuer,
                };

            SecurityToken securityToken = null;
            tokenHandler.ValidateToken(jwt.RawData, validationParameters, out securityToken);
        }
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {

            //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6Ikphc29uIExlZSIsInN1YiI6Ikphc29uIExlZSIsInJvbGUiOlsiTWFuYWdlciIsIlN1cGVydmlzb3IiXSwiaXNzIjoiaHR0cDovL2p3dGF1dGh6c3J2LmF6dXJld2Vic2l0ZXMubmV0IiwiYXVkIjoiUm9ja2V0IiwiZXhwIjoxNDQxOTgwMjE5LCJuYmYiOjE0NDE5NzY2MTl9.yegylhGkz5uasu5E--aEbCAHfi5aE9Z17_pZAE63Bog

            validatedToken = null;


            var key = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw";
            
            try
            {
                var raw = JsonWebToken.Decode(securityToken, key);

                var payLoad = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(raw);

                var claims = new List<Claim>();

                foreach (var row in payLoad)
                {
                    var claim = new Claim(row.Key, row.Value);
                    claims.Add(claim);
                }

                var claimsIdentity = new ClaimsIdentity(claims, "jwt");

                return new ClaimsPrincipal(claimsIdentity);
            }
            catch (Exception ex)
            {
                return null;

            }
            
        }
Exemple #16
0
        /// Using the same key used for signing token, user payload is generated back
        public JwtSecurityToken GenerateUserClaimFromJWT(string authToken)
        {
            var tokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
            {
                ValidAudiences = new string[]
                {
                    "http://www.example.com",
                },

                ValidIssuers = new string[]
                {
                    "self",
                },

                IssuerSigningKey = signingKey
            };
            var tokenHandler = new JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.SecurityToken validatedToken;

            try
            {
                tokenHandler.ValidateToken(authToken, tokenValidationParameters, out validatedToken);
            }
            catch (Exception ex)
            {
                return(null);
            }

            return(validatedToken as JwtSecurityToken);
        }
 protected override ClaimsIdentity CreateClaimsIdentity(JwtSecurityToken jwt, string issuer, TokenValidationParameters validationParameters)
 {
     OrganisationIdentity result = null;
     ClaimsIdentity claimsIdentity = base.CreateClaimsIdentity(jwt, issuer, validationParameters);
     if (claimsIdentity != null)
         result = new OrganisationIdentity(claimsIdentity);
     Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(result);
     return result;
 }
 /// <summary>
 ///   Creates a new instance of the <see cref="TrustManager"/> class with the
 ///   default values.
 /// </summary>
 public TrustManager()
 {
     Issuers = new List<IConfigurationManager<OpenIdConnectConfiguration>>();
     TokenValidationParameters = new TokenValidationParameters
     {
         IssuerSigningKeyResolver = SigningKeyResolver,
         ValidIssuers = ValidIssuers()
     };
 }
 protected override SecurityKey ResolveIssuerSigningKey(string token, SecurityToken securityToken, SecurityKeyIdentifier keyIdentifier, TokenValidationParameters validationParameters)
 {
     var certificate = ((JwtSecurityToken)securityToken).GetCertificateFromToken();
     if (certificate != null)
     {
         keyIdentifier.Add(new X509RawDataKeyIdentifierClause(certificate));
     }
     return base.ResolveIssuerSigningKey(token, securityToken, keyIdentifier, validationParameters);
 }
Exemple #20
0
        public override System.Security.Claims.ClaimsPrincipal ValidateToken(string jwtEncodedString, TokenValidationParameters validationParameters)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(jwtEncodedString);

            string decoded = DecodeUtil.Base64Decode(doc.InnerText);
            validationParameters.IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String("c8wfH2hkyI0nJE6p4KjaqCOK4iVWSbNsPwKHnNVlVhw="));
            return base.ValidateToken(decoded, validationParameters);
        }
        public IdentityModelJwtSecurityTokenHandler(TokenValidationParameters validationParams, Dictionary<string, string> inboundClaimTypeMap = null)
        {
            _validationParams = validationParams;

            if (inboundClaimTypeMap != null)
            {
                InboundClaimTypeMap = inboundClaimTypeMap;
            }
        }
        public async Task<ActionResult> Callback(string code, string state)
        {
            CheckState(state);

            using (var client = new HttpClient())
            {
                var resp = await client.PostAsync("https://accounts.google.com/o/oauth2/token",
                                 new FormUrlEncodedContent(new Dictionary<string, string>
                                                               {
                                                                   {"code", code},
                                                                   {"redirect_uri", RedirectUri},
                                                                   {"grant_type", "authorization_code"},
                                                                   {"client_id", ClientId},
                                                                   {"client_secret", ClientSecret}
                                                               }));
                resp.EnsureSuccessStatusCode();
                var tokenResp = await resp.Content.ReadAsAsync<TokenResponse>();

                var certs = await GoogleCertificates.GetCertificates();

                var tokenHandler = new JwtSecurityTokenHandler
                {
                    CertificateValidator = new GoogleCertificateValidator(certs.ToDictionary(t => t.Value.GetCertHashString(), t => t.Value))
                };

                var validationParameters = new TokenValidationParameters()
                {
                    AllowedAudience = ClientId,
                    ValidIssuer = "accounts.google.com",
                    SigningTokens = certs.Select(p => new X509SecurityToken(p.Value))
                };
                var principal = tokenHandler.ValidateToken(tokenResp.id_token, validationParameters);

                var jwt = new JwtSecurityToken(tokenResp.id_token);

                var viewModel = new ViewModel
                                    {
                                        JwtHeader = jwt.Header,
                                        JwtPayload = jwt.Payload,
                                        Principal = principal
                                    };

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResp.access_token);
                resp = await client.GetAsync("https://www.googleapis.com/tasks/v1/users/@me/lists");
                resp.EnsureSuccessStatusCode();
                var taskLists = await resp.Content.ReadAsAsync<TaskLists>();
                foreach(var list in taskLists.items)
                {
                    resp = await client.GetAsync(string.Format("https://www.googleapis.com/tasks/v1/lists/{0}/tasks",list.id));
                    resp.EnsureSuccessStatusCode();
                    var taskList = await resp.Content.ReadAsAsync<TaskList>();
                    viewModel.Tasks.AddRange(taskList.items.Select(item => item.title));
                }
                
                return View(viewModel);
            }
        }
 private static IPrincipal RetrievePrincipal(
     this JwtSecurityTokenHandler tokenHandler,
     string securityToken,
     TokenValidationParameters validationParameters)
 {
     SecurityToken validatedToken;
     return tokenHandler
         .ValidateToken(securityToken, validationParameters, out validatedToken);
 }
        public JwtSecurityTokenHandlerWrapper(TokenValidationParameters validationParams, Dictionary<string, string> inboundClaimTypeMap = null)
        {
            this.validationParams = validationParams;

            if (inboundClaimTypeMap != null)
            {
                InboundClaimTypeMap = inboundClaimTypeMap;
            }
        }
 /// <summary>
 /// Creates an instance of bearer authentication options with default values.
 /// </summary>
 public OAuthBearerAuthenticationOptions() : base()
 {
     AuthenticationScheme = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
     BackchannelTimeout = TimeSpan.FromMinutes(1);
     Challenge = OAuthBearerAuthenticationDefaults.AuthenticationScheme;
     Notifications = new OAuthBearerAuthenticationNotifications();
     RefreshOnIssuerKeyNotFound = true;
     SystemClock = new SystemClock();
     TokenValidationParameters = new TokenValidationParameters();
 }
        public WsFederationAuthenticationOptions(string authenticationType)
            : base(authenticationType)
        {
            AuthenticationMode = Security.AuthenticationMode.Active;
            Caption = WsFederationAuthenticationDefaults.Caption;

            _securityTokenHandlers = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers(authenticationType);
            _tokenValidationParameters = new TokenValidationParameters();
            BackchannelTimeout = TimeSpan.FromMinutes(1);    
        }
 public WsFederationAuthenticationOptions(string authenticationType)
     : base(authenticationType)
 {
     AuthenticationMode = Security.AuthenticationMode.Active;
     Caption = WsFederationAuthenticationDefaults.Caption;
     _tokenValidationParameters = new TokenValidationParameters();
     BackchannelTimeout = TimeSpan.FromMinutes(1);
     UseTokenLifetime = true;
     RefreshOnIssuerKeyNotFound = true;
 }
        public async Task<Client> FindClientByIdAsync(string clientId)
        {            
            var clientsUri = $"admin-api/api/clients/{clientId}";

            //var cert = Cert.Load(StoreName.My, StoreLocation.CurrentUser, "b512d01195667dbc7c4222ec6fd563ac64e3d450");
            //var handler = new WebRequestHandler();
            //handler.ClientCertificates.Add(cert);

            // Retrieve an access token from the IdentityAdmin /authorize OAuth endpoint
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(this.identityAdminUri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var cert = Cert.Load(typeof(IOwinBootstrapper).Assembly, "Cert", "idsrv3test.pfx", "idsrv3test");

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("name", "idServer"),
                        new Claim("role", "IdentityAdminManager"),
                        new Claim("scope", "idadmin-api")
                    }),
                    TokenIssuerName = "idServer",                    
                    AppliesToAddress = this.identityAdminUri,
                    Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(10)),
                    SigningCredentials = new X509SigningCredentials(cert)
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var accessToken = tokenHandler.WriteToken(securityToken);

                var jwtParams = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role",
                    ValidAudience = this.identityAdminUri,
                    ValidIssuer = "idServer",                    
                    IssuerSigningToken = new X509SecurityToken(cert)                    
                };

                SecurityToken validatedToken;
                tokenHandler.ValidateToken(accessToken, jwtParams, out validatedToken);                

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                var response = await client.GetAsync(clientsUri);
                var str = await response.Content.ReadAsStringAsync();
            }

            return null;
        }
        public static string Validate(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
        {
            if (validationParameters == null)
            {
                throw new ArgumentNullException("validationParameters");
            }

            if (string.IsNullOrWhiteSpace(issuer))
            {
                throw new SecurityTokenInvalidIssuerException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10211));
            }

            // Throw if all possible places to validate against are null or empty
            if (string.IsNullOrWhiteSpace(validationParameters.ValidIssuer) && (validationParameters.ValidIssuers == null))
            {
                throw new SecurityTokenInvalidIssuerException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10204));
            }

            if (!string.IsNullOrWhiteSpace(validationParameters.ValidIssuer) && string.Equals(validationParameters.ValidIssuer, issuer, StringComparison.Ordinal))
            {
                return issuer;
            }

            if (null != validationParameters.ValidIssuers)
            {
                foreach (string str in validationParameters.ValidIssuers)
                {
                    if (string.Equals(str, issuer, StringComparison.Ordinal))
                    {
                        return issuer;
                    }
                }
            }

            string validIssuer = validationParameters.ValidIssuer ?? "null";
            string validIssuers = "null";
            if (validationParameters.ValidIssuers != null)
            {
                bool first = true;
                foreach (string str in validationParameters.ValidIssuers)
                {
                    if (!string.IsNullOrWhiteSpace(str))
                    {
                        validIssuers += str;
                        if (!first)
                        {
                            validIssuers += ", ";
                        }
                        first = false;
                    }
                }
            }

            throw new SecurityTokenInvalidIssuerException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10205, validIssuer, validIssuers, issuer));
        }
        public void TokenValidationParameters_GetSets()
        {
            TokenValidationParameters validationParameters = new TokenValidationParameters();
            Type type = typeof(TokenValidationParameters);
            PropertyInfo[] properties = type.GetProperties();
            if (properties.Length != 30)
                Assert.Fail("Number of public fields has changed from 30 to: " + properties.Length + ", adjust tests");

            GetSetContext context =
                new GetSetContext
                {
                    PropertyNamesAndSetGetValue = new List<KeyValuePair<string, List<object>>>
                    {
                        new KeyValuePair<string, List<object>>("AuthenticationType", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("CertificateValidator", new List<object>{(string)null, X509CertificateValidator.None, X509CertificateValidatorEx.None}),
                        new KeyValuePair<string, List<object>>("ClockSkew", new List<object>{TokenValidationParameters.DefaultClockSkew, TimeSpan.FromHours(2), TimeSpan.FromMinutes(1)}),
                        new KeyValuePair<string, List<object>>("IssuerSigningKey", new List<object>{(SecurityKey)null, KeyingMaterial.DefaultAsymmetricKey_Public_2048, KeyingMaterial.DefaultSymmetricSecurityKey_256}),
                        new KeyValuePair<string, List<object>>("IssuerSigningKeys", new List<object>{(IEnumerable<SecurityKey>)null, new List<SecurityKey>{KeyingMaterial.DefaultAsymmetricKey_Public_2048, KeyingMaterial.DefaultSymmetricSecurityKey_256}, new List<SecurityKey>()}),
                        new KeyValuePair<string, List<object>>("IssuerSigningToken", new List<object>{(SecurityToken)null, KeyingMaterial.DefaultSymmetricSecurityToken_256, KeyingMaterial.DefaultAsymmetricX509Token_2048}),
                        new KeyValuePair<string, List<object>>("IssuerSigningTokens", new List<object>{(IEnumerable<SecurityToken>)null, new List<SecurityToken>{KeyingMaterial.DefaultAsymmetricX509Token_2048, KeyingMaterial.DefaultSymmetricSecurityToken_256}, new List<SecurityToken>()}),
                        new KeyValuePair<string, List<object>>("NameClaimType", new List<object>{ClaimsIdentity.DefaultNameClaimType, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("RoleClaimType", new List<object>{ClaimsIdentity.DefaultRoleClaimType, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                        new KeyValuePair<string, List<object>>("RequireExpirationTime", new List<object>{true, false, true}),
                        new KeyValuePair<string, List<object>>("RequireSignedTokens", new List<object>{true, false, true}),
                        new KeyValuePair<string, List<object>>("SaveSigninToken", new List<object>{false, true, false}),
                        new KeyValuePair<string, List<object>>("ValidateActor", new List<object>{false, true, false}),
                        new KeyValuePair<string, List<object>>("ValidateAudience", new List<object>{true, false, true}),
                        new KeyValuePair<string, List<object>>("ValidateIssuer", new List<object>{true, false, true}),
                        new KeyValuePair<string, List<object>>("ValidateLifetime", new List<object>{true, false, true}),
                        new KeyValuePair<string, List<object>>("ValidIssuer", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
                    },
                    Object = validationParameters,
                };
            TestUtilities.GetSet(context);

            if (context.Errors.Count != 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(Environment.NewLine);
                foreach (string str in context.Errors)
                    sb.AppendLine(str);

                Assert.Fail(sb.ToString());
            }

            Assert.IsNull(validationParameters.AudienceValidator);
            Assert.IsNotNull(validationParameters.ClientDecryptionTokens);
            Assert.AreEqual(validationParameters.ClientDecryptionTokens.Count, 0);
            Assert.IsNull(validationParameters.LifetimeValidator);
            Assert.IsNull(validationParameters.IssuerSigningKeyResolver);
            Assert.IsNull(validationParameters.IssuerValidator);
            Assert.IsNull(validationParameters.ValidAudiences);
            Assert.IsNull(validationParameters.ValidIssuers);
        }
        /// <summary>
        /// Creates a new instance of <see cref="SecurityKeyResolver"/>
        /// </summary>
        /// <param name="securityToken"> related security token.</param>
        /// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
        internal SecurityKeyResolver(string securityToken, TokenValidationParameters validationParameters)
        {
            _securityToken = securityToken;

            if (validationParameters == null)
            {
                throw new ArgumentNullException("validationParameters");
            }

            _validationParameters = validationParameters;
        }
        private IEnumerable<Claim> ValidateIdentityToken(string token)
        {
            var parameters = new TokenValidationParameters
            {
                AllowedAudience = "implicitclient",
                ValidIssuer = "https://idsrv3.com",
                SigningToken = new X509SecurityToken(X509.LocalMachine.My.SubjectDistinguishedName.Find("CN=idsrv3test", false).First())
            };

            var id = new JwtSecurityTokenHandler().ValidateToken(token, parameters);
            return id.Claims;
        }
        public override void Configure(IAppBuilder app)
        {
            var jwtParams = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = NameClaimType,
                RoleClaimType = RoleClaimType,
                ValidAudience = Audience,
                ValidIssuer   = Issuer,
            };

            if (SigningCert != null)
            {
                jwtParams.IssuerSigningToken = new X509SecurityToken(SigningCert);
            }
            else
            {
                var bytes = Convert.FromBase64String(SigningKey);
                jwtParams.IssuerSigningToken = new BinarySecretSecurityToken(bytes);
            }

            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                TokenValidationParameters = jwtParams
            });
            app.RequireScopes(new ScopeValidationOptions
            {
                AllowAnonymousAccess = true,
                Scopes = new string[] {
                    Scope
                }
            });
            if (ClaimsTransformation != null)
            {
                app.Use(async(ctx, next) =>
                {
                    var user = ctx.Authentication.User;
                    if (user != null)
                    {
                        user = ClaimsTransformation(user);
                        ctx.Authentication.User = user;
                    }

                    await next();
                });
            }
        }
        private async Task <IEnumerable <Claim> > ValidateIdentityTokenAsync(string token, string state)
        {
            //public key для валидации токена
            const string certString = "MIIDBTCCAfGgAwIBAgIQNQb+T2ncIrNA6cKvUA1GWTAJBgUrDgMCHQUAMBIxEDAOBgNVBAMTB0RldlJvb3QwHhcNMTAwMTIwMjIwMDAwWhcNMjAwMTIwMjIwMDAwWjAVMRMwEQYDVQQDEwppZHNydjN0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqnTksBdxOiOlsmRNd+mMS2M3o1IDpK4uAr0T4/YqO3zYHAGAWTwsq4ms+NWynqY5HaB4EThNxuq2GWC5JKpO1YirOrwS97B5x9LJyHXPsdJcSikEI9BxOkl6WLQ0UzPxHdYTLpR4/O+0ILAlXw8NU4+jB4AP8Sn9YGYJ5w0fLw5YmWioXeWvocz1wHrZdJPxS8XnqHXwMUozVzQj+x6daOv5FmrHU1r9/bbp0a1GLv4BbTtSh4kMyz1hXylho0EvPg5p9YIKStbNAW9eNWvv5R8HN7PPei21AsUqxekK0oW9jnEdHewckToX7x5zULWKwwZIksll0XnVczVgy7fCFwIDAQABo1wwWjATBgNVHSUEDDAKBggrBgEFBQcDATBDBgNVHQEEPDA6gBDSFgDaV+Q2d2191r6A38tBoRQwEjEQMA4GA1UEAxMHRGV2Um9vdIIQLFk7exPNg41NRNaeNu0I9jAJBgUrDgMCHQUAA4IBAQBUnMSZxY5xosMEW6Mz4WEAjNoNv2QvqNmk23RMZGMgr516ROeWS5D3RlTNyU8FkstNCC4maDM3E0Bi4bbzW3AwrpbluqtcyMN3Pivqdxx+zKWKiORJqqLIvN8CT1fVPxxXb/e9GOdaR8eXSmB0PgNUhM4IjgNkwBbvWC9F/lzvwjlQgciR7d4GfXPYsE1vf8tmdQaY8/PtdAkExmbrb9MihdggSoGXlELrPA91Yce+fiRcKY3rQlNWVd4DOoJ/cPXsXwry8pWjNCo5JD8Q+RQ5yZEy7YPoifwemLhTdsBz3hlZr28oCGJ3kbnpW0xGvQb3VHSTVVbeei0CfXoW6iz1";

            var cert = new X509Certificate2(Convert.FromBase64String(certString));

            var result = await this.Request
                         .GetOwinContext()
                         .Authentication
                         .AuthenticateAsync("TempCookie");

            if (result == null)
            {
                throw new InvalidOperationException("No temp cookie");
            }

            if (state != result.Identity.FindFirst("state").Value)
            {
                throw new InvalidOperationException("invalid state");
            }

            var parameters = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidAudience      = "implicitclient",
                ValidIssuer        = IdServBaseUri,
                IssuerSigningToken = new X509SecurityToken(cert)
            };

            var handler = new JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.SecurityToken jwt;
            var id = handler.ValidateToken(token, parameters, out jwt);

            if (id.FindFirst("nonce").Value != result.Identity.FindFirst("nonce").Value)
            {
                throw new InvalidOperationException("Invalid nonce");
            }

            this.Request.GetOwinContext().Authentication.SignOut("TempCookie");

            return(id.Claims);
        }
Exemple #35
0
        public static async Task <ClaimsPrincipal> Validate(string accessToken)
        {
            string stsDiscoveryEndpoint = "https://login.microsoftonline.com/AZURE_TENANT_ID/.well-known/openid-configuration";

            ConfigurationManager <OpenIdConnectConfiguration> configManager = new Microsoft.IdentityModel.Protocols.ConfigurationManager <OpenIdConnectConfiguration>(stsDiscoveryEndpoint);

            OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync();

            System.IdentityModel.Tokens.TokenValidationParameters validationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidIssuer          = config.Issuer,
                ValidateAudience     = false,
                IssuerSigningTokens  = config.SigningTokens,
                CertificateValidator = X509CertificateValidator.None
            };

            JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.SecurityToken jwt = new JwtSecurityToken();

            ClaimsPrincipal result = tokendHandler.ValidateToken(accessToken, validationParameters, out jwt);

            return(result);
        }
        public static void UseIdentityManager(this IAppBuilder app, IdentityManagerConfiguration config)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            config.Validate();

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            if (config.SecurityMode == SecurityMode.LocalMachine)
            {
                var local = new LocalAuthenticationOptions(config.AdminRoleName);
                app.Use <LocalAuthenticationMiddleware>(local);
            }
            else if (config.SecurityMode == SecurityMode.OAuth2)
            {
                var jwtParams = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    RoleClaimType = Constants.ClaimTypes.Role,
                    ValidAudience = config.OAuth2Configuration.Audience,
                    ValidIssuer   = config.OAuth2Configuration.Issuer,
                };
                if (config.OAuth2Configuration.SigningCert != null)
                {
                    jwtParams.IssuerSigningToken = new X509SecurityToken(config.OAuth2Configuration.SigningCert);
                }
                else
                {
                    var bytes = Convert.FromBase64String(config.OAuth2Configuration.SigningKey);
                    jwtParams.IssuerSigningToken = new BinarySecretSecurityToken(bytes);
                }

                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions {
                    TokenValidationParameters = jwtParams
                });
                app.RequireScopes(new ScopeValidationOptions {
                    AllowAnonymousAccess = true,
                    Scopes = new string[] {
                        config.OAuth2Configuration.Scope
                    }
                });
            }

            if (!config.DisableUserInterface)
            {
                app.UseFileServer(new FileServerOptions
                {
                    RequestPath = new PathString("/assets"),
                    FileSystem  = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets")
                });
                app.UseFileServer(new FileServerOptions
                {
                    RequestPath = new PathString("/assets/libs/fonts"),
                    FileSystem  = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets.Content.fonts")
                });
                app.UseStageMarker(PipelineStage.MapHandler);
            }

            SignatureConversions.AddConversions(app);

            var httpConfig = new HttpConfiguration();

            WebApiConfig.Configure(httpConfig, config);
            app.UseWebApi(httpConfig);
            app.UseStageMarker(PipelineStage.MapHandler);
        }
        public static void UseIdentityManager(this IAppBuilder app, IdentityManagerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("config");
            }
            options.Validate();

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            var container = AutofacConfig.Configure(options);

            app.Use <AutofacContainerMiddleware>(container);

            if (options.SecurityMode == SecurityMode.LocalMachine)
            {
                var local = new LocalAuthenticationOptions(options.AdminRoleName);
                app.Use <LocalAuthenticationMiddleware>(local);
            }
            else if (options.SecurityMode == SecurityMode.OAuth2)
            {
                var jwtParams = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    NameClaimType = options.OAuth2Configuration.NameClaimType,
                    RoleClaimType = options.OAuth2Configuration.RoleClaimType,
                    ValidAudience = options.OAuth2Configuration.Audience,
                    ValidIssuer   = options.OAuth2Configuration.Issuer,
                };
                if (options.OAuth2Configuration.SigningCert != null)
                {
                    jwtParams.IssuerSigningToken = new X509SecurityToken(options.OAuth2Configuration.SigningCert);
                }
                else
                {
                    var bytes = Convert.FromBase64String(options.OAuth2Configuration.SigningKey);
                    jwtParams.IssuerSigningToken = new BinarySecretSecurityToken(bytes);
                }

                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions {
                    TokenValidationParameters = jwtParams
                });
                app.RequireScopes(new ScopeValidationOptions {
                    AllowAnonymousAccess = true,
                    Scopes = new string[] {
                        options.OAuth2Configuration.Scope
                    }
                });
                if (options.OAuth2Configuration.ClaimsTransformation != null)
                {
                    app.Use(async(ctx, next) =>
                    {
                        var user = ctx.Authentication.User;
                        if (user != null)
                        {
                            user = options.OAuth2Configuration.ClaimsTransformation(user);
                            ctx.Authentication.User = user;
                        }

                        await next();
                    });
                }
            }

            if (!options.DisableUserInterface)
            {
                app.UseFileServer(new FileServerOptions
                {
                    RequestPath = new PathString("/assets"),
                    FileSystem  = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets")
                });
                app.UseFileServer(new FileServerOptions
                {
                    RequestPath = new PathString("/assets/libs/fonts"),
                    FileSystem  = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets.Content.fonts")
                });
                app.UseStageMarker(PipelineStage.MapHandler);
            }

            SignatureConversions.AddConversions(app);
            app.UseWebApi(WebApiConfig.Configure(options));
            app.UseStageMarker(PipelineStage.MapHandler);
        }
 public static ClaimsPrincipal ValidateSaml2Token(string securityToken, TokenValidationParameters4x validationParameters, out SecurityToken4x validatedToken)
 {
     return(new Saml2SecurityTokenHandler4x().ValidateToken(securityToken, validationParameters, out validatedToken));
 }
        public string DecodeAndValidateIdToken(string idToken, string clientId, string issuer, string audience)
        {
            ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            logger.Debug("DecodeAndValidateIdToken");
            OidcGetKeys oidcGetKeys = new OidcGetKeys();

            oidcGetKeys.keys = new List <Key>();
            IRestResponse <OidcGetKeys> response = null;
            //var clientId = appSettings["oidc.spintnative.clientId"];
            string secretKeyn  = null;
            string secretKeye  = null;
            string jsonPayload = null;

            //find key reference in JWT
            string[] parts   = idToken.Split('.');
            string   header  = parts[0];
            string   payload = parts[1];

            byte[] crypto = Base64UrlDecode(parts[2]);
            System.IdentityModel.Tokens.SecurityToken validatedToken;


            //decode JWT header and payload
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            //SecurityToken tokenReceived = tokenHandler.ReadToken(idToken);
            JwtSecurityToken tokenReceived2 = new JwtSecurityToken(idToken);

            //decode JWT payload
            string  decodePayload = Encoding.UTF8.GetString(Base64UrlDecode(payload));
            JObject payloadData   = JObject.Parse(decodePayload);

            //decode JWT header
            string  decodeHeader = Encoding.UTF8.GetString(Base64UrlDecode(header));
            JObject headerData   = JObject.Parse(decodeHeader);
            //deserialize header to find key id of id token
            OidcHeader oidcHeader = new OidcHeader();

            oidcHeader = Newtonsoft.Json.JsonConvert.DeserializeObject <OidcHeader>(decodeHeader);
            //computer hash from JWT header and payload
            SHA256 sha256 = SHA256.Create();

            byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(header + '.' + payload));

            try
            {
                //get keys from okta
                var client = new RestClient(appSettings["oidc.AuthServer"] + "/v1/keys");

                var request = new RestRequest(Method.GET);
                // request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Accept", "application/json");
                request.AddHeader("Content-Type", "application/json");
                request.AddQueryParameter("client_id", clientId);
                response = client.Execute <OidcGetKeys>(request);
                //loop through returned keys, copy match on kid
                foreach (var item in response.Data.keys)
                {
                    if (oidcHeader.kid == item.kid)
                    {
                        secretKeyn = item.n;
                        secretKeye = item.e;
                    }
                }
            }
            catch (Exception)
            {
                logger.Error("falied to access keys from Authorization Server");
                return("Failed calling keys endpoint");
            }

            try
            {
                //incorporate public received from keys endpoint
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(
                    new RSAParameters()
                {
                    Modulus  = FromBase64Url(secretKeyn),
                    Exponent = FromBase64Url(secretKeye)
                });

                //verify JWT signature versus computed
                RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                rsaDeformatter.SetHashAlgorithm("SHA256");
                bool rspRsa = rsaDeformatter.VerifySignature(hash, crypto);
                if (rspRsa)
                {
                    logger.Debug("Signature validation successful");
                }
                else
                {
                    logger.Error("Signature validation failed");
                    return("Failure; Signature validation");
                }
            }
            catch (Exception)
            {
                logger.Error("Signature validation failed");
                return("Failure; Signature validation");
            }


            //verify remainder of JWT token
            var tokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
            {
                //ValidAudiences = new string[]
                //{
                //    clientId
                //},
                //ValidIssuers = new string[]
                //{
                //    issuer
                //},
                ValidAudience = audience,
                ValidIssuer   = issuer,
                //IssuerSigningToken = new System.ServiceModel.Security.Tokens.BinarySecretSecurityToken(Convert.FromBase64String(secret)),
                //IssuerSigningKey = new X509SecurityKey(cert),
                RequireExpirationTime    = true,
                ValidateLifetime         = true,
                ValidateAudience         = false,
                ValidateIssuer           = true,
                ValidateIssuerSigningKey = false,
                RequireSignedTokens      = false,
                CertificateValidator     = System.IdentityModel.Selectors.X509CertificateValidator.None
            };



            try
            {
                // if token is valid, it will output the validated token that contains the JWT information
                // strip off signature from token
                string token1 = idToken.Substring(0, idToken.LastIndexOf('.') + 1);
                // Convert Base64 encoded token to Base64Url encoding
                string token2 = token1.Replace('+', '-').Replace('/', '_').Replace("=", "");
                System.Security.Claims.ClaimsPrincipal principal = tokenHandler.ValidateToken(token2, tokenValidationParameters, out validatedToken);
            }
            catch (Exception ex)
            {
                logger.Error("Failed to validate token");
                return("Failure; Validating token");
            }
            return(payloadData.ToString());
        }