当前位置: 首页>>代码示例>>C#>>正文


C# Tokens.TokenValidationParameters类代码示例

本文整理汇总了C#中System.IdentityModel.Tokens.TokenValidationParameters的典型用法代码示例。如果您正苦于以下问题:C# TokenValidationParameters类的具体用法?C# TokenValidationParameters怎么用?C# TokenValidationParameters使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TokenValidationParameters类属于System.IdentityModel.Tokens命名空间,在下文中一共展示了TokenValidationParameters类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Index

        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");
            }
        }
开发者ID:aguerere,项目名称:rules,代码行数:29,代码来源:HomeController.cs

示例2: SendAsync

        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);
        }
开发者ID:Inmeta,项目名称:aspc2016,代码行数:35,代码来源:WebAPIConfig.cs

示例3: End2End_OpenIdConnect

        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);
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:33,代码来源:End2EndTests.cs

示例4: ParseToken

        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;
        }
开发者ID:swebgit,项目名称:know-thy-shelf,代码行数:25,代码来源:JwtProvider.cs

示例5: ValidateJwtAccessTokenAsync

        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
                });                
            }
        }
开发者ID:Zoumaho,项目名称:Thinktecture.IdentityServer.v3,代码行数:34,代码来源:TokenValidator.cs

示例6: AuthenticateIdToken

        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;
        }
开发者ID:cyl3392207,项目名称:policydemo2,代码行数:31,代码来源:ARMOAuthModule.cs

示例7: DecodeToken

        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
            });
        }
开发者ID:girmateshe,项目名称:OAuth,代码行数:32,代码来源:JwtController.cs

示例8: Validate

        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;
        }
开发者ID:jayway,项目名称:JayLabs.Owin.OAuthAuthorization,代码行数:30,代码来源:TokenValidator.cs

示例9: ClaimsAuthorizedClient

        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;
        }
开发者ID:belaie,项目名称:AzureAD-BYOA-Provisioning-Samples,代码行数:31,代码来源:TokenHandler.cs

示例10: ValidateToken

        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;

            }
            
        }
开发者ID:JasonSoft,项目名称:single-sign-on,代码行数:35,代码来源:CustomJwtSecurityTokenHandler.cs

示例11: JwtSecurityTokenHandler_Extensibility

        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);
        }
开发者ID:vebin,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:28,代码来源:ExtensibilityTests.cs

示例12: should_create_valid_token

        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);
        }
开发者ID:Scalepoint,项目名称:OAuthJwtAssertionTokenClient,代码行数:28,代码来源:JwtAssertionFactoryTests.cs

示例13: ClaimFromValidIssuer

        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;
        }
开发者ID:belaie,项目名称:AzureAD-BYOA-Provisioning-Samples,代码行数:31,代码来源:TokenHandler.cs

示例14: RetrievePrincipal

 private static IPrincipal RetrievePrincipal(
     this JwtSecurityTokenHandler tokenHandler,
     string securityToken,
     TokenValidationParameters validationParameters)
 {
     SecurityToken validatedToken;
     return tokenHandler
         .ValidateToken(securityToken, validationParameters, out validatedToken);
 }
开发者ID:c4rm4x,项目名称:C4rm4x.Tools,代码行数:9,代码来源:JwtSecurityTokenHandlerExtensions.cs

示例15: CreateClaimsIdentity

 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;
 }
开发者ID:CreatorDev,项目名称:DeviceServer,代码行数:9,代码来源:OrganisationSecurityTokenHandler.cs


注:本文中的System.IdentityModel.Tokens.TokenValidationParameters类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。