• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Tokens.X509SecurityToken类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: MatchesKeyIdentifierClause

		public void MatchesKeyIdentifierClause ()
		{
			UniqueId id = new UniqueId ();
			X509SecurityToken t = new X509SecurityToken (cert, id.ToString ());
			LocalIdKeyIdentifierClause l =
				new LocalIdKeyIdentifierClause (id.ToString ());
			Assert.IsTrue (t.MatchesKeyIdentifierClause (l), "#1-1");

			l = new LocalIdKeyIdentifierClause ("#" + id.ToString ());
			Assert.IsFalse (t.MatchesKeyIdentifierClause (l), "#1-2");

			X509ThumbprintKeyIdentifierClause h =
				new X509ThumbprintKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (h), "#2-1");

			h = new X509ThumbprintKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (h), "#2-2");

			X509IssuerSerialKeyIdentifierClause i =
				new X509IssuerSerialKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (i), "#3-1");

			i = new X509IssuerSerialKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (i), "#3-2");

			X509RawDataKeyIdentifierClause s =
				new X509RawDataKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (s), "#4-1");

			s = new X509RawDataKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (s), "#4-2");
		}
开发者ID:nlhepler,项目名称:mono,代码行数:32,代码来源:X509SecurityTokenTest.cs


示例2: X509EncryptingCredentials

 /// <summary>
 /// Constructs an encrypting credential based on the x509 token.
 /// </summary>
 /// <param name="token">The x509 security token.</param>
 internal X509EncryptingCredentials(X509SecurityToken token)
     : this(
     token,
     new SecurityKeyIdentifier(token.CreateKeyIdentifierClause<X509IssuerSerialKeyIdentifierClause>()),
     SecurityAlgorithms.DefaultAsymmetricKeyWrapAlgorithm)
 {
 }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:11,代码来源:X509EncryptingCredentials.cs


示例3: Context_PostAuthenticateRequest

        void Context_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;

            // no need to call transformation if session already exists
            if (FederatedAuthentication.SessionAuthenticationModule != null &&
                FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(context.Request.Cookies))
            {
                return;
            }

            var transformer = FederatedAuthentication.ServiceConfiguration.ClaimsAuthenticationManager;
            if (transformer != null)
            {
                var principal = context.User as ClaimsPrincipal;

                if (context.Request.ClientCertificate.IsPresent && context.Request.ClientCertificate.IsValid)
                {
                    var cert = new X509Certificate2(context.Request.ClientCertificate.Certificate);
                    var token = new X509SecurityToken(cert);
                    var certId = new HttpsSecurityTokenHandler().ValidateToken(token).First();

                    principal.Identities.Add(certId);
                }

                var transformedPrincipal = transformer.Authenticate(context.Request.RawUrl, principal);

                context.User = transformedPrincipal;
                Thread.CurrentPrincipal = transformedPrincipal;
            }
        }
开发者ID:bencoveney,项目名称:Thinktecture.IdentityModel.40,代码行数:31,代码来源:ClaimsAuthenticationHttpModule.cs


示例4: GetX509TokenFromCert

 /// <summary>
 /// Utility method to get a X509 Token from a given certificate
 /// </summary>
 /// <param name="storeName">Name of certificate store (e.g. My, TrustedPeople)</param>
 /// <param name="storeLocation">Location of certificate store (e.g. LocalMachine, CurrentUser)</param>
 /// <param name="subjectDistinguishedName">The Subject Distinguished Name of the certificate</param>
 /// <returns>The corresponding X509 Token</returns>
 public static X509SecurityToken GetX509TokenFromCert(StoreName storeName,
                                                      StoreLocation storeLocation,
                                                      string subjectDistinguishedName)
 {
     X509Certificate2 certificate = LookupCertificate(storeName, storeLocation, subjectDistinguishedName);
     X509SecurityToken t = new X509SecurityToken(certificate);
     return t;
 }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:15,代码来源:FederationUtilities.cs


示例5: DefaultValues

		public void DefaultValues ()
		{
			UniqueId id = new UniqueId ();
			X509SecurityToken t = new X509SecurityToken (cert, id.ToString ());
			Assert.AreEqual (id.ToString (), t.Id, "#1");
			Assert.AreEqual (cert, t.Certificate, "#2");
			Assert.AreEqual (cert.NotBefore.ToUniversalTime (), t.ValidFrom, "#3");
			Assert.AreEqual (cert.NotAfter.ToUniversalTime (), t.ValidTo, "#4");
			Assert.AreEqual (1, t.SecurityKeys.Count, "#5");
		}
开发者ID:nlhepler,项目名称:mono,代码行数:10,代码来源:X509SecurityTokenTest.cs


示例6: GetSigningKeyDescriptor

        private KeyDescriptor GetSigningKeyDescriptor()
        {
            var certificate = _options.SigningCertificate;

            var clause = new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>();
            var key = new KeyDescriptor(new SecurityKeyIdentifier(clause));
            key.Use = KeyType.Signing;

            return key;
        }
开发者ID:mequanta,项目名称:Janitor-old,代码行数:10,代码来源:MetadataResponseGenerator.cs


示例7: Properties

		public void Properties ()
		{
			X509ThumbprintKeyIdentifierClause ic =
				new X509ThumbprintKeyIdentifierClause (cert);
			Assert.AreEqual (cert.GetCertHash (), ic.GetX509Thumbprint (), "#1-1");
			Assert.AreEqual (null, ic.ClauseType, "#1-2");

			ic = new X509SecurityToken (cert).CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause> ();
			Assert.AreEqual (cert.GetCertHash (), ic.GetX509Thumbprint (), "#2-1");
			Assert.AreEqual (null, ic.ClauseType, "#2-2");
		}
开发者ID:nlhepler,项目名称:mono,代码行数:11,代码来源:X509ThumbprintKeyIdentifierClauseTest.cs


示例8: AddDecryptingToken

		public void AddDecryptingToken(X509Certificate2 certificate) {
			Requires.NotNull(certificate, "certificate");
			Requires.True(certificate.HasPrivateKey, "certificate");
			var cert = new X509SecurityToken(certificate);
			try {
				this.AddDecryptingToken(cert);
			} catch {
				cert.Dispose();
				throw;
			}
		}
开发者ID:437072341,项目名称:dotnetopenid,代码行数:11,代码来源:ReceivingTokenEventArgs.cs


示例9: GetReferent

		WrappedKeySecurityToken GetReferent ()
		{
			string id = "referent";
			byte [] key = new byte [32];
			X509SecurityToken token = new X509SecurityToken (cert);
			SecurityKeyIdentifierClause kic =
				new X509ThumbprintKeyIdentifierClause (cert);
			string alg = SecurityAlgorithms.RsaOaepKeyWrap;
			return new WrappedKeySecurityToken (id, key, alg, token,
				new SecurityKeyIdentifier (kic));
		}
开发者ID:nickchal,项目名称:pash,代码行数:11,代码来源:WrappedKeySecurityTokenTest.cs


示例10: AddDecryptingToken

		public void AddDecryptingToken(X509Certificate2 certificate) {
			Contract.Requires<ArgumentNullException>(certificate != null);
			Contract.Requires<ArgumentException>(certificate.HasPrivateKey);
			var cert = new X509SecurityToken(certificate);
			try {
				this.AddDecryptingToken(cert);
			} catch {
				cert.Dispose();
				throw;
			}
		}
开发者ID:enslam,项目名称:dotnetopenid,代码行数:11,代码来源:ReceivingTokenEventArgs.cs


示例11: GetValidationParameters

 private static TokenValidationParameters GetValidationParameters()
 {
     var bytes = Convert.FromBase64String(_securityKey.Value);
     var token = new X509SecurityToken(new X509Certificate2(bytes));
     return new TokenValidationParameters
     {
         ValidAudience = _authority + "/resources",
         ValidIssuer = _authority,
         IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => { return token.SecurityKeys.First(); },
         IssuerSigningToken = token
     };
 }
开发者ID:imranbaloch,项目名称:Samples,代码行数:12,代码来源:JsonWebTokenHttpModule.cs


示例12: X509CertTokenVerificationKey

 public X509CertTokenVerificationKey(X509Certificate2 cert)
 {
     lock (_lock)
         {
             if (_x509Certificate == null)
             {
                 _x509Certificate = cert;
                 _securityToken = new X509SecurityToken(_x509Certificate);
                 base.RawBody = _x509Certificate.RawData;
             }
         }
 }
开发者ID:shushengli,项目名称:azure-sdk-for-media-services,代码行数:12,代码来源:X509CertTokenVerificationKey.cs


示例13: CreateTlsSspiState

 SspiNegotiationTokenProviderState CreateTlsSspiState(X509SecurityToken token)
 {
     X509Certificate2 clientCertificate;
     if (token == null)
     {
         clientCertificate = null;
     }
     else 
     {
         clientCertificate = token.Certificate;
     }
     TlsSspiNegotiation tlsNegotiation = new TlsSspiNegotiation(String.Empty, SchProtocols.Ssl3Client | SchProtocols.TlsClient, clientCertificate);
     return new SspiNegotiationTokenProviderState(tlsNegotiation);
 }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:14,代码来源:TlsnegoTokenProvider.cs


示例14: ValidateTokenCore

        /// <summary>
        /// Validates the token using the wrapped token handler and generates IAuthorizationPolicy
        /// wrapping the returned ClaimsIdentities.
        /// </summary>
        /// <param name="token">Token to be validated.</param>
        /// <returns>Read-only collection of IAuthorizationPolicy</returns>
        protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore( SecurityToken token )
        {
            ReadOnlyCollection<ClaimsIdentity> identities = null;
            try
            {
                identities = _wrappedX509SecurityTokenHandler.ValidateToken(token);
            }
            catch ( Exception ex )
            {
                if ( !_exceptionMapper.HandleSecurityTokenProcessingException( ex ) )
                {
                    throw;
                }
            }

            // tlsnego will dispose of the x509, when we write out the bootstrap we will get a dispose error.

            bool shouldSaveBootstrapContext = SecurityTokenHandlerConfiguration.DefaultSaveBootstrapContext;
            if ( _wrappedX509SecurityTokenHandler.Configuration != null )
            {
                shouldSaveBootstrapContext = _wrappedX509SecurityTokenHandler.Configuration.SaveBootstrapContext;
            }

            if ( shouldSaveBootstrapContext )
            {
                X509SecurityToken x509Token = token as X509SecurityToken;
                SecurityToken tokenToCache;
                if ( x509Token != null )
                {
                    tokenToCache = new X509SecurityToken( x509Token.Certificate );
                }
                else
                {
                    tokenToCache = token;
                }

                BootstrapContext bootstrapContext = new BootstrapContext(tokenToCache, _wrappedX509SecurityTokenHandler);
                foreach (ClaimsIdentity identity in identities)
                {
                    identity.BootstrapContext = bootstrapContext;
                }
            }

            List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
            policies.Add(new AuthorizationPolicy(identities));

            return policies.AsReadOnly();
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:54,代码来源:WrappedX509SecurityTokenAuthenticator.cs


示例15: GetRemoteSecurity

 public override SecurityMessageProperty GetRemoteSecurity()
 {
     if (this.clientSecurity.TransportToken != null)
     {
         return this.clientSecurity;
     }
     if (this.clientCertificate != null)
     {
         SecurityToken token = new X509SecurityToken(this.clientCertificate);
         ReadOnlyCollection<IAuthorizationPolicy> tokenPolicies = System.ServiceModel.Security.SecurityUtils.NonValidatingX509Authenticator.ValidateToken(token);
         this.clientSecurity = new SecurityMessageProperty();
         this.clientSecurity.TransportToken = new SecurityTokenSpecification(token, tokenPolicies);
         this.clientSecurity.ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies);
         return this.clientSecurity;
     }
     return base.GetRemoteSecurity();
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:17,代码来源:SslStreamSecurityUpgradeAcceptor.cs


示例16: CreateSymmetricKeyBasedAssertion

        /// <summary>
        /// Creates a SAML assertion based on a symmetric proof key
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="signatureToken">An X509SecurityToken that will be used to sign the SAML assertion</param>
        /// <param name="encryptionToken">An X509SecurityToken that will be used to encrypt the proof key</param>
        /// <param name="proofToken">A BinarySecretSecurityToken containing the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the provided signature token</returns>
        public static SamlAssertion CreateSymmetricKeyBasedAssertion(ClaimSet claims, X509SecurityToken signatureToken, X509SecurityToken encryptionToken, BinarySecretSecurityToken proofToken, SecurityAlgorithmSuite algoSuite)
        {
            // Check various input parameters
            if (claims == null)
                throw new ArgumentNullException("claims");

            if (claims.Count == 0)
                throw new ArgumentException("Provided ClaimSet must contain at least one claim");

            if (proofToken == null)
                throw new ArgumentNullException("proofToken");

            if (signatureToken == null)
                throw new ArgumentNullException("signatureToken");

            if (encryptionToken == null)
                throw new ArgumentNullException("encryptionToken");

            if (proofToken == null)
                throw new ArgumentNullException("proofToken");

            if (algoSuite == null)
                throw new ArgumentNullException("algoSuite");

            // Get signing key and a key identifier for same
            SecurityKey signatureKey = signatureToken.SecurityKeys[0];
            SecurityKeyIdentifierClause signatureSkic = signatureToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier signatureKeyIdentifier  = new SecurityKeyIdentifier(signatureSkic);

            // Get encryption key and a key identifier for same
            SecurityKey encryptionKey = encryptionToken.SecurityKeys[0];
            SecurityKeyIdentifierClause encryptionSkic = encryptionToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier encryptionKeyIdentifier = new SecurityKeyIdentifier(encryptionSkic);

            // Encrypt the proof key and create a key identifier for same
            byte[] proofKey = proofToken.GetKeyBytes();
            byte[] encryptedSecret = new byte[proofKey.Length];
            encryptedSecret = encryptionKey.EncryptKey(algoSuite.DefaultAsymmetricKeyWrapAlgorithm, proofKey);
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(new EncryptedKeyIdentifierClause(encryptedSecret, algoSuite.DefaultAsymmetricKeyWrapAlgorithm, encryptionKeyIdentifier));

            // Create the assertion
            return CreateAssertion(claims, signatureKey, signatureKeyIdentifier, proofKeyIdentifier, algoSuite);
        }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:52,代码来源:SamlUtilities.cs


示例17: CreateSAMLToken

        /// <summary>
        /// Creates a SAML token for the specified email address.
        /// </summary>
        public static UserIdentity CreateSAMLToken(string emailAddress)
        {
            // Normally this would be done by a server that is capable of verifying that
            // the user is a legimate holder of email address. Using a local certficate to
            // signed the SAML token is a short cut that would never be done in a real system.
            CertificateIdentifier userid = new CertificateIdentifier();

            userid.StoreType = CertificateStoreType.Windows;
            userid.StorePath = "LocalMachine\\My";
            userid.SubjectName = "UA Sample Client";

            X509Certificate2 certificate = userid.Find();
            X509SecurityToken signingToken = new X509SecurityToken(certificate);

            // Create list of confirmation strings
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List<SamlAttribute> attributes = new List<SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);
            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on 
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                signingToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()));

            return new UserIdentity(new SamlSecurityToken(assertion));
        }
开发者ID:yuriik83,项目名称:UA-.NET,代码行数:65,代码来源:MainForm.cs


示例18: AuthenticateClientCertificate

        public virtual ClaimsPrincipal AuthenticateClientCertificate(X509Certificate2 certificate)
        {
            SecurityTokenHandlerCollection handlers;
            var token = new X509SecurityToken(certificate);

            if (Configuration.TryGetClientCertificateMapping(out handlers))
            {
                var identity = handlers.First().ValidateToken(token);
                return new ClaimsPrincipal(identity);
            }

            return Principal.Anonymous;
        }
开发者ID:rmgreen85,项目名称:Thinktecture.IdentityModel.45,代码行数:13,代码来源:HttpAuthentication.cs


示例19: ValidateRemoteCertificate

 private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     X509Certificate2 certificate2 = new X509Certificate2(certificate);
     SecurityToken token = new X509SecurityToken(certificate2, false);
     ReadOnlyCollection<IAuthorizationPolicy> tokenPolicies = this.serverCertificateAuthenticator.ValidateToken(token);
     this.serverSecurity = new SecurityMessageProperty();
     this.serverSecurity.TransportToken = new SecurityTokenSpecification(token, tokenPolicies);
     this.serverSecurity.ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies);
     AuthorizationContext authorizationContext = this.serverSecurity.ServiceSecurityContext.AuthorizationContext;
     this.parent.IdentityVerifier.EnsureOutgoingIdentity(base.RemoteAddress, base.Via, authorizationContext);
     return true;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:12,代码来源:SslStreamSecurityUpgradeInitiator.cs


示例20: Open

 internal override void Open(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     base.Open(helper.RemainingTime());
     if (this.clientCertificateProvider != null)
     {
         System.ServiceModel.Security.SecurityUtils.OpenTokenProviderIfRequired(this.clientCertificateProvider, helper.RemainingTime());
         this.clientToken = (X509SecurityToken) this.clientCertificateProvider.GetToken(helper.RemainingTime());
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:10,代码来源:SslStreamSecurityUpgradeInitiator.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Json.JsonObject类代码示例发布时间:2022-05-26
下一篇:
C# Tokens.TokenValidationParameters类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap