Example #1
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");
            }
        }
Example #2
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);
        }
        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);
        }
Example #4
0
        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;
        }
        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
                });                
            }
        }
Example #6
0
        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;
        }
Example #7
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
            });
        }
        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 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;

            }
            
        }
        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 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);
        }
        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;
        }
 private static IPrincipal RetrievePrincipal(
     this JwtSecurityTokenHandler tokenHandler,
     string securityToken,
     TokenValidationParameters validationParameters)
 {
     SecurityToken validatedToken;
     return tokenHandler
         .ValidateToken(securityToken, validationParameters, out validatedToken);
 }
 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;
 }
Example #16
0
 /// <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);
 }
Example #18
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);
        }
Example #19
0
        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);
            }
        }
        public JwtSecurityTokenHandlerWrapper(TokenValidationParameters validationParams, Dictionary<string, string> inboundClaimTypeMap = null)
        {
            this.validationParams = validationParams;

            if (inboundClaimTypeMap != null)
            {
                InboundClaimTypeMap = inboundClaimTypeMap;
            }
        }
        public IdentityModelJwtSecurityTokenHandler(TokenValidationParameters validationParams, Dictionary<string, string> inboundClaimTypeMap = null)
        {
            _validationParams = validationParams;

            if (inboundClaimTypeMap != null)
            {
                InboundClaimTypeMap = inboundClaimTypeMap;
            }
        }
        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 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);
 }
 /// <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;
     _tokenValidationParameters = new TokenValidationParameters();
     BackchannelTimeout = TimeSpan.FromMinutes(1);
     UseTokenLifetime = true;
     RefreshOnIssuerKeyNotFound = true;
 }
        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 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;
        }
        /// <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;
        }
        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);
        }
        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;
        }