internal DerivedKeySecurityToken(int generation, int offset, int length, string label, byte[] nonce, SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm, string id)
 {
     this.length = -1;
     this.offset = -1;
     this.generation = -1;
     this.Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, false);
 }
        /// <summary>
        /// Gets the name of the issuer.
        /// </summary>
        /// <param name="securityToken">The security token.</param>
        /// <returns></returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                throw new ArgumentNullException("securityToken");
            }

            var x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                var issuer = x509Token.Certificate.Thumbprint;
                Debug.WriteLine("Certificate thumbprint: " + issuer);

                return issuer;
            }
            
            var rsaToken = securityToken as RsaSecurityToken;
            if (rsaToken != null)
            {
                var issuer = rsaToken.Rsa.ToXmlString(false);
                Debug.WriteLine("RSA: " + issuer);

                return issuer;
            }

            throw new SecurityTokenException(securityToken.GetType().FullName);
        }
 private void ResolveSecurityToken()
 {
     if (this._securityToken == null)
     {
         lock (this._lock)
         {
             if (this._securityToken == null)
             {
                 ClientCredentialsSecurityTokenManager.KerberosSecurityTokenProviderWrapper wrapper = this._tokenProvider as ClientCredentialsSecurityTokenManager.KerberosSecurityTokenProviderWrapper;
                 if (wrapper != null)
                 {
                     this._securityToken = wrapper.GetToken(new TimeoutHelper(this._timeout).RemainingTime(), this._channelBinding);
                 }
                 else
                 {
                     this._securityToken = this._tokenProvider.GetToken(new TimeoutHelper(this._timeout).RemainingTime());
                 }
             }
         }
     }
     if (this._securityToken == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.ServiceModel.SR.GetString("SecurityTokenNotResolved", new object[] { this._tokenProvider.GetType().ToString() })));
     }
 }
        void ResolveSecurityToken()
        {
            if ( _securityToken == null )
            {
                lock ( _lock )
                {
                    if ( _securityToken == null )
                    {
                        ClientCredentialsSecurityTokenManager.KerberosSecurityTokenProviderWrapper kerbTokenProvider = _tokenProvider 
                                                        as ClientCredentialsSecurityTokenManager.KerberosSecurityTokenProviderWrapper;
                        if (kerbTokenProvider != null)
                        {
                            _securityToken = kerbTokenProvider.GetToken((new TimeoutHelper(_timeout)).RemainingTime(), _channelBinding);
                        }
                        else
                        {
                            _securityToken = _tokenProvider.GetToken((new TimeoutHelper(_timeout)).RemainingTime());
                        }
                    }
                }
            }

            if ( _securityToken == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityTokenException( SR.GetString( SR.SecurityTokenNotResolved, _tokenProvider.GetType().ToString() ) ) );
            }

            return;
        }
        /// <summary>
        /// Turns a RST/ProofKey pair into a GenericXmlSecurityToken.
        /// </summary>
        /// <param name="rstr">The RSTR.</param>
        /// <param name="proofKey">The ProofKey.</param>
        /// <returns>A GenericXmlSecurityToken</returns>
        public static GenericXmlSecurityToken ToGenericXmlSecurityToken(this RequestSecurityTokenResponse rstr, SecurityToken proofKey)
        {
            DateTime? created = null;
            DateTime? expires = null;
            if (rstr.Lifetime != null)
            {
                created = rstr.Lifetime.Created;
                expires = rstr.Lifetime.Expires;
                if (!created.HasValue)
                {
                    created = new DateTime?(DateTime.UtcNow);
                }
                if (!expires.HasValue)
                {
                    expires = new DateTime?(DateTime.UtcNow.AddHours(10.0));
                }
            }
            else
            {
                created = new DateTime?(DateTime.UtcNow);
                expires = new DateTime?(DateTime.UtcNow.AddHours(10.0));
            }

            return new GenericXmlSecurityToken(
                ExtractTokenXml(rstr),
                proofKey,
                created.Value,
                expires.Value,
                rstr.RequestedAttachedReference,
                rstr.RequestedUnattachedReference,
                new ReadOnlyCollection<IAuthorizationPolicy>(new List<IAuthorizationPolicy>()));
        }
예제 #6
0
    protected override void WriteTokenCore(System.Xml.XmlWriter writer,
                                           System.IdentityModel.Tokens.SecurityToken token)
    {
        UserNameSecurityToken userToken = token as UserNameSecurityToken;

        string tokennamespace = "o";

        DateTime created    = DateTime.Now;
        string   createdStr = created.ToString("yyyy-MM-ddThh:mm:ss.fffZ");

        // unique Nonce value - encode with SHA-1 for 'randomness'
        // in theory the nonce could just be the GUID by itself
        string phrase = Guid.NewGuid().ToString();
        var    nonce  = GetSHA1String(phrase);

        // in this case password is plain text
        // for digest mode password needs to be encoded as:
        // PasswordAsDigest = Base64(SHA-1(Nonce + Created + Password))
        // and profile needs to change to
        //string password = GetSHA1String(nonce + createdStr + userToken.Password);

        string password = userToken.Password;

        writer.WriteRaw(string.Format(
                            "<{0}:UsernameToken u:Id=\"" + token.Id +
                            "\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" +
                            "<{0}:Username>" + userToken.UserName + "</{0}:Username>" +
                            "<{0}:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" +
                            password + "</{0}:Password>" +
                            "<{0}:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" +
                            nonce + "</{0}:Nonce>" +
                            "<u:Created>" + createdStr + "</u:Created></{0}:UsernameToken>", tokennamespace));
    }
 public SupportingTokenSpecification(SecurityToken token, ReadOnlyCollection<IAuthorizationPolicy> tokenPolicies, SecurityTokenAttachmentMode attachmentMode, SecurityTokenParameters tokenParameters)
     : base(token, tokenPolicies)
 {
     SecurityTokenAttachmentModeHelper.Validate(attachmentMode);
     _tokenAttachmentMode = attachmentMode;
     _tokenParameters = tokenParameters;
 }
        /// <summary>
        /// Overrides the base class. Validates the given issuer token. For a incoming SAML token
        /// the issuer token is the Certificate that signed the SAML token.
        /// </summary>
        /// <param name="securityToken">Issuer token to be validated.</param>
        /// <returns>Friendly name representing the Issuer.</returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpAds.IdpAdsIssuerNameRegistry.GetIssuerName",
                "MyTraceSource", SourceLevels.Information);

            //TraceSource ts = new TraceSource("System.ServiceModel");

            X509SecurityToken x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                // Warning: This sample does a simple compare of the Issuer Certificate
                // to a subject name. This is not appropriate for production use. 
                // Check your validation policy and authenticate issuers based off the policy.

                string commonName = x509Token.Certificate.GetNameInfo(X509NameType.SimpleName, false);

                ts.TraceInformation("Certificate CN: " + commonName);

                // TODO: Why this is different in the 
                if (CertificateUtil.ValidateCertificate(StoreName.TrustedPeople, StoreLocation.LocalMachine, x509Token.Certificate))
                {
                    ts.TraceInformation("Certificate VALID");

                    return x509Token.Certificate.SubjectName.Name;
                }
            }

            ts.TraceInformation("Untrusted issuer");

            throw new SecurityTokenException("Untrusted issuer.");
        }
 protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token)
 {
     bool flag = false;
     token = null;
     flag = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token);
     if (!flag && (this.outOfBandTokenResolvers != null))
     {
         for (int i = 0; i < this.outOfBandTokenResolvers.Count; i++)
         {
             flag = this.outOfBandTokenResolvers[i].TryResolveToken(keyIdentifier, out token);
             if (flag)
             {
                 break;
             }
         }
     }
     if (!flag)
     {
         for (int j = 0; j < keyIdentifier.Count; j++)
         {
             if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[j], out token))
             {
                 return true;
             }
         }
     }
     return flag;
 }
        protected override void WriteTokenCore(System.Xml.XmlWriter writer,
                                               System.IdentityModel.Tokens.SecurityToken token)
        {
            UserNameSecurityToken userToken = token as UserNameSecurityToken;
            string tokennamespace           = "o";

            DateTime created    = DateTime.UtcNow;
            string   createdStr = created.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

            string phrase = Guid.NewGuid().ToString();
            var    nonce  = Convert.ToBase64String(Encoding.UTF8.GetBytes(phrase));
            SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();
            //Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )
            string Password_Digest = Convert.ToBase64String(sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(phrase + createdStr + userToken.Password)));                     // pxLqPLCXU1EiUS+NnpRuCw==
            var    stringToWrite   = string.Format(
                "<{0}:UsernameToken u:Id=\"" + token.Id +
                "\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" +
                "<{0}:Username>" + userToken.UserName + "</{0}:Username>" +
                "<{0}:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">" +
                Password_Digest + "</{0}:Password>" +
                "<{0}:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" +
                nonce + "</{0}:Nonce>" +
                "<u:Created>" + createdStr + "</u:Created></{0}:UsernameToken>", tokennamespace);

            writer.WriteRaw(stringToWrite);
        }
예제 #11
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="other">The SamlClientCredentials to create a copy of</param>
 protected SamlClientCredentials(SamlClientCredentials other) : base ( other )
 {
     // Just do reference copy given sample nature
     this.assertion = other.assertion;            
     this.claims = other.claims;
     this.proofToken = other.proofToken;            
 }
        public async Task<string> SamlToJwtAsync(SecurityToken token, string realm)
        {
            var samlToken = token as SamlSecurityToken;
            if (samlToken == null) throw new ArgumentException("token not an instance of a SamlSecurityToken");

            return await SamlToJwtAsync(samlToken.ToTokenXmlString(), realm);
        }
예제 #13
0
        public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType,
            out SecurityToken token)
        {
            token = null;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = appliesTo,
                KeyType = KeyTypes.Bearer,
                TokenType = tokenType
            };

            try
            {
                var rstr = _sts.Issue(principal, rst);
                token = rstr.RequestedSecurityToken.SecurityToken;
                return true;
            }
            catch (Exception e)
            {
                Tracing.Error("Failed to issue token. An exception occurred. " + e);
                return false;
            }
        }
 internal protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
 {
     if (token is GenericXmlSecurityToken)
         return base.CreateGenericXmlTokenKeyIdentifierClause(token, referenceStyle);
     else
         return this.CreateKeyIdentifierClause<SecurityContextKeyIdentifierClause, LocalIdKeyIdentifierClause>(token, referenceStyle);
 }
 public JwtAuthenticationOwinMiddleware(AppFunc next, IEnumerable<string> AllowedAudiences, string Issuer, SecurityToken SigningToken)
 {
     this.next = next;
     this.AllowedAudiences = AllowedAudiences;
     this.Issuer = Issuer;
     this.SigningToken = SigningToken;
 }
        public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException();
            }

            var userNameToken = token as UserNameSecurityToken;
            if (userNameToken == null)
            {
                throw new SecurityTokenException("Invalid token");
            }

            Validator.Validate( userNameToken.UserName, userNameToken.Password );

            IEnumerable<Claim> claims = new List<Claim>
            {
                new Claim(
                    "http://schemas.microsoft.com/ws/2008/06/identity/claims/ClaimTypes.AuthenticationInstant",
                    XmlConvert.ToString( DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ" ),
                    "http://www.w3.org/2001/XMLSchema#dateTime" ),
                new Claim( System.IdentityModel.Claims.ClaimTypes.Name, userNameToken.UserName)
            };

            return new ReadOnlyCollection<ClaimsIdentity>(new List<ClaimsIdentity> { new ClaimsIdentity(claims, "Password") });
        }
 public DerivedKeySecurityToken CreateToken(SecurityToken tokenToDerive, int maxKeyLength)
 {
     DerivedKeySecurityToken result = new DerivedKeySecurityToken(this.generation, this.offset, this.length,
         this.label, this.nonce, tokenToDerive, this.tokenToDeriveIdentifier, this.derivationAlgorithm, this.Id);
     result.InitializeDerivedKey(maxKeyLength);
     return result;
 }
        /// <summary>
        /// Overrides the base class. Validates the given issuer token. For a incoming SAML token
        /// the issuer token is the Certificate that signed the SAML token.
        /// </summary>
        /// <param name="securityToken">Issuer token to be validated.</param>
        /// <returns>Friendly name representing the Issuer.</returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            Common.CustomTextTraceSource ts = new Common.CustomTextTraceSource("CommercialVehicleCollisionWebservice.WspTrustedIssuerNameRegistry.GetIssuerName",
                "MyTraceSource", SourceLevels.Information);

            
            X509SecurityToken x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                // Warning: This sample does a simple compare of the Issuer Certificate
                // to a subject name. This is not appropriate for production use. 
                // Check your validation policy and authenticate issuers based off the policy.

                ts.TraceInformation("IssuerName: " + x509Token.Certificate.SubjectName.Name);

                string commonName = x509Token.Certificate.GetNameInfo(X509NameType.SimpleName, false);
                ts.TraceInformation("CommonName: " + commonName);

                if (CertificateUtil.ValidateCertificate(StoreName.TrustedPeople, StoreLocation.LocalMachine, x509Token.Certificate))
                {
                    ts.TraceInformation("Certificate is valid");

                    return x509Token.Certificate.SubjectName.Name;
                }
                else
                {
                    ts.TraceInformation("Certificate is NOT VALID");
                }
            }

            throw new SecurityTokenException("Untrusted issuer.");            
        }
예제 #19
0
        public static SecurityToken GetToken(SecurityToken dobstsToken, string endpointUri, string spRealm)
        {
            // WSTrust call over SSL with credentails sent in the message.
            var binding = new IssuedTokenWSTrustBinding();
            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

            var factory = new WSTrustChannelFactory(
                binding,
                endpointUri);
            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;

            // Request Bearer Token so no keys or encryption required.
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(spRealm),
                KeyType = KeyTypes.Bearer
            };

            // Make the request with the DobstsToken.
            factory.ConfigureChannelFactory();
            var channel = factory.CreateChannelWithIssuedToken(dobstsToken);
            return channel.Issue(rst) as GenericXmlSecurityToken;
        }
        public static ClaimsPrincipal ValidateJwtToken(string jwtToken, out JwtSecurityToken parsedJwt)
        {
            var tokenHandler = new JwtSecurityTokenHandler()
            {
            };

            // Parse JWT from the Base64UrlEncoded wire form (<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
            parsedJwt = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken;

            var  audience = ConfigurationManager.AppSettings["JwtAllowedAudience"] ?? "http://localhost:8080";
            var  issuer   = ConfigurationManager.AppSettings["JwtValidIssuer"] ?? "DotNetNancysolutions";
            var  configValidateAudience = ConfigurationManager.AppSettings["JwtValidateAudience"];
            var  configValidateIssuer   = ConfigurationManager.AppSettings["JwtValidateIssuer"];
            bool validateAudience       = configValidateAudience == null ? false : Convert.ToBoolean(configValidateAudience);
            bool validateIssuer         = configValidateIssuer == null ? true : Convert.ToBoolean(configValidateIssuer);


            TokenValidationParameters validationParams =
                new TokenValidationParameters()
            {
                ValidAudience      = audience,
                ValidateAudience   = validateAudience,
                ValidIssuer        = issuer,
                ValidateIssuer     = validateIssuer,
                IssuerSigningToken = new BinarySecretSecurityToken(SecurityConstants.KeyForHmacSha256),
            };

            System.IdentityModel.Tokens.SecurityToken securityToken = null;
            return(tokenHandler.ValidateToken(jwtToken, validationParams, 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;

            }
            
        }
예제 #22
0
 public static SecurityToken GetIssuedToken(string STSUrl, string audience, string signingCertificateNameClient, SecurityToken bootstrapToken)
 {
     
     var certificate2Client = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateNameClient);
     var certificate2Service = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateNameSTS);
     return TokenClient.GetIssuedToken(new Uri(audience), certificate2Client, certificate2Service, new Uri(STSUrl), bootstrapToken);
 }
        /// <summary>
        /// Overrides the base class. Validates the given issuer token. For a incoming SAML token
        /// the issuer token is the Certificate that signed the SAML token.
        /// </summary>
        /// <param name="securityToken">Issuer token to be validated.</param>
        /// <returns>Friendly name representing the Issuer.</returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdentityProviderSts.IdentityProviderIssuerNameRegistry.GetIssuerName",
                "MyTraceSource", SourceLevels.Information);

            X509SecurityToken x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                // Warning: This sample does a simple compare of the Issuer Certificate
                // to a subject name. This is not appropriate for production use. 
                // Check your validation policy and authenticate issuers based off the policy.
                
                string commonName = x509Token.Certificate.GetNameInfo(X509NameType.SimpleName, false);

                ts.TraceInformation("Certificate CN: " + commonName);

                //if (String.Equals(x509Token.Certificate.SubjectName.Name, "O=CA for Ref GFIPM, [email protected], C=US, S=GA, CN=Reference GFIPM Federation") ||
                //    String.Equals(x509Token.Certificate.SubjectName.Name, "O=CISA, C=US, S=GA, CN=cisaidp.swbs.gtri.gatech.edu"))
                //if (String.Equals(x509Token.Certificate.SubjectName.Name, "O=CISA, C=US, S=GA, CN=cisaidp.swbs.gtri.gatech.edu"))
                if (String.Equals(commonName.ToUpper(), "HA50IDP"))
                {
                    return x509Token.Certificate.SubjectName.Name;
                }
            }

            ts.TraceInformation("Untrusted issuer");

            throw new SecurityTokenException("Untrusted issuer.");
        }
 private void EnsureWrappedToken(SecurityToken token, Message message)
 {
     if (!(token is WrappedKeySecurityToken))
     {
         throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("IncomingSigningTokenMustBeAnEncryptedKey")), message);
     }
 }
 public RequestSecurityTokenResponse(string context, string tokenType, int keySize, EndpointAddress appliesTo, SecurityToken requestedSecurityToken, SecurityToken requestedProofToken, bool computeKey )
     : base(context, tokenType, keySize, appliesTo)
 {
     this.m_requestedSecurityToken = requestedSecurityToken;
     this.m_requestedProofToken = requestedProofToken;
     this.m_computeKey = computeKey;
 }
        /// <summary>
        /// Gets the name of the issuer.
        /// </summary>
        /// <param name="securityToken">The security token.</param>
        /// <returns></returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                Tracing.Error("SimpleIssuerNameRegistry: securityToken is null");
                throw new ArgumentNullException("securityToken");
            }

            X509SecurityToken token = securityToken as X509SecurityToken;
            if (token != null)
            {
                Tracing.Information("SimpleIssuerNameRegistry: X509 SubjectName: " + token.Certificate.SubjectName.Name);
                Tracing.Information("SimpleIssuerNameRegistry: X509 Thumbprint : " + token.Certificate.Thumbprint);
                return token.Certificate.Thumbprint;
            }
            
            RsaSecurityToken token2 = securityToken as RsaSecurityToken;
            if (token2 == null)
            {
                throw new SecurityTokenException(securityToken.GetType().FullName);
            }

            Tracing.Information("SimpleIssuerNameRegistry: RSA Key: " + token2.Rsa.ToXmlString(false));
            return token2.Rsa.ToXmlString(false);
        }
 public override void WriteToken(XmlWriter writer, SecurityToken token)
 {
     writer.WriteStartElement("stringToken");
     string tokenString = this.GetTokenAsString(token);
     writer.WriteString(tokenString);
     writer.WriteEndElement();
 }
        //public override bool CanReadToken(XmlReader reader)
        //{
        //    bool canRead = false;
        //    if (reader != null)
        //    {
        //        if (reader.IsStartElement(BinarySecurityToken)
        //            && (reader.GetAttribute(ValueType) == SimpleWebTokenConstants.ValueTypeUri))
        //        {
        //            canRead = true;
        //        }
        //    }
        //    return canRead;
        //}
        public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            var saml2Token = token as Saml2SecurityToken;
            if (saml2Token == null)
            {
                throw new ArgumentException("The token provided must be of type Saml2SecurityToken.");
            }

            if (DateTime.Compare(saml2Token.ValidTo.Add(Configuration.MaxClockSkew), DateTime.UtcNow) <= 0)
            {
                throw new SecurityTokenExpiredException(
                    "The incoming token has expired. Get a new access token from the Authorization Server.");
            }

            //this.ValidateSignature(simpleWebToken);

            //ValidateAudience(simpleWebToken.Audience);

            ClaimsIdentity claimsIdentity = CreateClaims(saml2Token);

            //if (this.Configuration.SaveBootstrapContext)
            //{
            //    claimsIdentity.BootstrapContext = new BootstrapContext(saml2Token.SerializedToken);
            //}

            var claimCollection = new List<ClaimsIdentity>(new[] { claimsIdentity });
            return claimCollection.AsReadOnly();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CompressedSecurityToken"/> class.
        /// </summary>
        /// <param name="token">The token to be compressed.</param>
        public CompressedSecurityToken(SecurityToken token)
        {
            Contract.Requires(token != null);


            _token = token;
        }
예제 #30
0
 /// <summary>
 /// Parameterized constructor
 /// </summary>
 /// <param name="context">The value of the wst:RequestSecurityToken/@Context attribute</param>
 /// <param name="tokenType">The content of the wst:RequestSecurityToken/wst:TokenType element</param>
 /// <param name="requestType"></param>
 /// <param name="keySize">The content of the wst:RequestSecurityToken/wst:KeySize element</param>
 /// <param name="keyType"></param>
 /// <param name="proofKey"></param>
 /// <param name="entropy">A SecurityToken that represents entropy provided by the requester in the wst:RequestSecurityToken/wst:Entropy element</param>
 /// <param name="claimTypeRequirements"></param>
 /// <param name="appliesTo">The content of the wst:RequestSecurityToken/wst:KeySize element</param>
 public RequestSecurityToken(string context, string tokenType, string requestType, int keySize, string keyType , SecurityToken proofKey, SecurityToken entropy, EndpointAddress appliesTo) : base ( context, tokenType,keySize, appliesTo )
 {
     this.keyType = keyType;
     this.proofKey = proofKey;
     this.requestType = requestType;
     this.requestorEntropy = entropy;
 }
예제 #31
0
        protected override bool CanValidateTokenCore(SecurityToken token)
        {
#if FEATURE_CORECLR
            return token is X509SecurityToken;
#else
            return false;
#endif // FEATURE_CORECLR 
        }
예제 #32
0
 public SecurityTokenContainer(SecurityToken token)
 {
     if (token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
     }
     _token = token;
 }
예제 #33
0
        protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(System.IdentityModel.Tokens.SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
        {
            if (referenceStyle == SecurityTokenReferenceStyle.Internal)
            {
                return(token.CreateKeyIdentifierClause <LocalIdKeyIdentifierClause>());
            }

            throw new NotSupportedException("External references are not supported for tokens");
        }
예제 #34
0
 public SecurityTokenSpecification(System.IdentityModel.Tokens.SecurityToken token, ReadOnlyCollection <IAuthorizationPolicy> tokenPolicies)
 {
     this.token = token;
     if (tokenPolicies == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenPolicies");
     }
     this.tokenPolicies = tokenPolicies;
 }
        public static string WriteSaml2Token(SecurityToken4x token)
        {
            StringBuilder sb     = new StringBuilder();
            XmlWriter     writer = XmlWriter.Create(sb);

            new Saml2SecurityTokenHandler4x().WriteToken(writer, token);
            writer.Flush();
            writer.Close();
            return(sb.ToString());
        }
        /// <summary>
        /// Validates the token.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns>Collection of identity claims</returns>
        public override ClaimsIdentityCollection ValidateToken(System.IdentityModel.Tokens.SecurityToken token)
        {
            UserNameSecurityToken userNameSecurityToken = token as UserNameSecurityToken;

            MembershipProvider provider   = Membership.Provider;
            bool           isValidated    = provider.ValidateUser(userNameSecurityToken.UserName, userNameSecurityToken.Password);
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(System.IdentityModel.Claims.ClaimTypes.Name, userNameSecurityToken.UserName) });

            ClaimsIdentityCollection claimIdentityCollection = new ClaimsIdentityCollection(new IClaimsIdentity[] { claimsIdentity });

            return(claimIdentityCollection);
        }
예제 #37
0
 public static string WriteSaml2Token(SecurityToken4x token)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var writer = XmlDictionaryWriter.CreateTextWriter(memoryStream, Encoding.UTF8, false))
         {
             new Saml2SecurityTokenHandler4x().WriteToken(writer, token);
             writer.Flush();
             writer.Close();
             return(Encoding.UTF8.GetString(memoryStream.ToArray()));
         }
     }
 }
예제 #38
0
            public override string GetIssuerName(System.IdentityModel.Tokens.SecurityToken securityToken)
            {
                var x509 = securityToken as X509SecurityToken;

                if (x509 != null)
                {
                    if (x509.Certificate.Thumbprint.Equals(trustedThumbrpint, StringComparison.OrdinalIgnoreCase))
                    {
                        return(x509.Certificate.Subject);
                    }
                }

                return(null);
            }
예제 #39
0
        public override string GetIssuerName(System.IdentityModel.Tokens.SecurityToken securityToken)
        {
            if (securityToken == null)
            {
                throw new Exception("securityToken");
            }
            X509SecurityToken token = securityToken as X509SecurityToken;

            if (token != null)
            {
                string thumbprint = token.Certificate.Thumbprint;
                if (this.ConfiguredTrustedIssuers.ContainsKey(thumbprint)) //Breakpoint here
                {
                    return(this.ConfiguredTrustedIssuers[thumbprint]);
                }
            }
            return(null);
            //var ret = base.GetIssuerName(securityToken);
            //return ret;
        }
예제 #40
0
        internal static WCFSecurityToken CreateGenericXmlSecurityToken(WsTrustRequest request, WsTrustResponse trustResponse, WsSerializationContext serializationContext, SecurityAlgorithmSuite algorithmSuite)
        {
            // Create GenericXmlSecurityToken
            // Assumes that token is first and Saml2SecurityToken.
            RequestSecurityTokenResponse response = trustResponse.RequestSecurityTokenResponseCollection[0];

            // Get attached and unattached references
            GenericXmlSecurityKeyIdentifierClause internalSecurityKeyIdentifierClause = null;

            if (response.AttachedReference != null)
            {
                internalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.AttachedReference);
            }

            GenericXmlSecurityKeyIdentifierClause externalSecurityKeyIdentifierClause = null;

            if (response.UnattachedReference != null)
            {
                externalSecurityKeyIdentifierClause = GetSecurityKeyIdentifierForTokenReference(response.UnattachedReference);
            }

            // Get proof token
            WCFSecurityToken proofToken = GetProofToken(request, response, serializationContext, algorithmSuite);

            // Get lifetime
            DateTime created = response.Lifetime?.Created ?? DateTime.UtcNow;
            DateTime expires = response.Lifetime?.Expires ?? created.AddDays(1);

            return(new GenericXmlSecurityToken(response.RequestedSecurityToken.TokenElement,
                                               proofToken,
                                               created,
                                               expires,
                                               internalSecurityKeyIdentifierClause,
                                               externalSecurityKeyIdentifierClause,
                                               null));
        }
예제 #41
0
        public override string GetIssuerName(System.IdentityModel.Tokens.SecurityToken securityToken, string requestedIssuerName)
        {
            var ret = base.GetIssuerName(securityToken, requestedIssuerName);

            return(ret);
        }
 public static ClaimsPrincipal ValidateSaml2Token(string securityToken, TokenValidationParameters4x validationParameters, out SecurityToken4x validatedToken)
 {
     return(new Saml2SecurityTokenHandler4x().ValidateToken(securityToken, validationParameters, out validatedToken));
 }
 /// <summary>
 /// When implemented in the derived class the method returns the issuer name
 /// of the given SecurityToken's issuer. The requested issuer name may be considered
 /// in determining the issuer's name.
 /// </summary>
 /// <param name="securityToken">The SecurityToken whose name is requested.</param>
 /// <param name="requestedIssuerName">Input to determine the issuer name</param>
 /// <remarks>The default implementation ignores the requestedIsserName parameter and simply calls the
 /// GetIssuerName( SecurityToken securityToken ) method</remarks>
 /// <returns>Issuer name as a string.</returns>
 public virtual string GetIssuerName(SecurityToken securityToken, string requestedIssuerName)
 {
     return(GetIssuerName(securityToken));
 }
예제 #44
0
        /// <summary>
        /// Checks if Audience Enforcement checks are required for the given token
        /// based on this SamlSecurityTokenRequirement settings.
        /// </summary>
        /// <param name="audienceUriMode">
        /// The <see cref="AudienceUriMode"/> defining the audience requirement.
        /// </param>
        /// <param name="token">The Security token to be tested for Audience
        /// Enforcement.</param>
        /// <returns>True if Audience Enforcement should be applied.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        public virtual bool ShouldEnforceAudienceRestriction(AudienceUriMode audienceUriMode, SecurityToken token)
        {
            if (null == token)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            //
            // Use AudienceUriMode to determine whether the audience
            // should be enforced
            //
            switch (audienceUriMode)
            {
            case AudienceUriMode.Always:
                return(true);

            case AudienceUriMode.Never:
                return(false);

            case AudienceUriMode.BearerKeyOnly:
#pragma warning suppress 56506
                return(null == token.SecurityKeys || 0 == token.SecurityKeys.Count);

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4025, audienceUriMode)));
            }
        }
예제 #45
0
 public abstract string GetIssuerName(SecurityToken securityToken);
예제 #46
0
 public virtual string GetIssuerName(SecurityToken securityToken, System.String requestedIssuerName)
 {
     throw new NotImplementedException();
 }
예제 #47
0
 protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StandardsManagerCannotWriteObject, token.GetType())));
 }
예제 #48
0
 protected override bool CanWriteTokenCore(SecurityToken token)
 {
     return(false);
 }
예제 #49
0
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }
            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSerializer");
            }
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;

            reader.MoveToContent();
            reader.Read();
            if (reader.IsStartElement(samlDictionary.NameIdentifier, samlDictionary.Namespace))
            {
                this.nameFormat    = reader.GetAttribute(samlDictionary.NameIdentifierFormat, null);
                this.nameQualifier = reader.GetAttribute(samlDictionary.NameIdentifierNameQualifier, null);
                reader.MoveToContent();
                this.name = reader.ReadString();
                if (this.name == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLNameIdentifierMissingIdentifierValueOnRead")));
                }
                reader.MoveToContent();
                reader.ReadEndElement();
            }
            if (reader.IsStartElement(samlDictionary.SubjectConfirmation, samlDictionary.Namespace))
            {
                reader.MoveToContent();
                reader.Read();
                while (reader.IsStartElement(samlDictionary.SubjectConfirmationMethod, samlDictionary.Namespace))
                {
                    string str = reader.ReadString();
                    if (string.IsNullOrEmpty(str))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.SubjectConfirmationMethod.Value })));
                    }
                    this.confirmationMethods.Add(str);
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
                if (this.confirmationMethods.Count == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLSubjectConfirmationClauseMissingConfirmationMethodOnRead")));
                }
                if (reader.IsStartElement(samlDictionary.SubjectConfirmationData, samlDictionary.Namespace))
                {
                    reader.MoveToContent();
                    this.confirmationData = reader.ReadString();
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
                if (reader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.KeyInfo, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
                {
                    XmlDictionaryReader reader2 = XmlDictionaryReader.CreateDictionaryReader(reader);
                    this.securityKeyIdentifier = SamlSerializer.ReadSecurityKeyIdentifier(reader2, keyInfoSerializer);
                    this.crypto = SamlSerializer.ResolveSecurityKey(this.securityKeyIdentifier, outOfBandTokenResolver);
                    if (this.crypto == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SamlUnableToExtractSubjectKey")));
                    }
                    this.subjectToken = SamlSerializer.ResolveSecurityToken(this.securityKeyIdentifier, outOfBandTokenResolver);
                }
                if ((this.confirmationMethods.Count == 0) && string.IsNullOrEmpty(this.name))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLSubjectRequiresNameIdentifierOrConfirmationMethodOnRead")));
                }
                reader.MoveToContent();
                reader.ReadEndElement();
            }
            reader.MoveToContent();
            reader.ReadEndElement();
        }
 protected override bool TryResolveTokenCore(System.IdentityModel.Tokens.SecurityKeyIdentifier keyIdentifier, out System.IdentityModel.Tokens.SecurityToken token)
 {
     throw new NotImplementedException();
 }
예제 #51
0
 protected override void WriteTokenCore(System.Xml.XmlWriter writer, System.IdentityModel.Tokens.SecurityToken token)
 {
     throw new NotImplementedException();
 }
예제 #52
0
 /// <summary>
 /// Attempt to add a new entry or update an existing entry.
 /// </summary>
 /// <param name="key">Key to use when adding item</param>
 /// <param name="securityToken">SecurityToken to add to cache, can be null</param>
 /// <param name="expirationTime">The expiration time of the entry.</param>
 public abstract void AddOrUpdate(string key, SecurityToken securityToken, DateTime expirationTime);
예제 #53
0
 protected override bool CanWriteTokenCore(System.IdentityModel.Tokens.SecurityToken token)
 {
     throw new NotImplementedException();
 }
예제 #54
0
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(System.IdentityModel.Tokens.SecurityToken token)
        {
            var securityToken = token as SecurityToken;

            if (securityToken != null)
            {
                // Note that we cannot authenticate the token w/o a password, so it must be retrieved from somewhere
                if (securityToken.ValidateToken(_passwordProvider.RetrievePassword("User1")) != true)
                {
                    throw new SecurityTokenValidationException("Token validation failed");
                }

                // Add claims about user here
                var userClaimSet = new DefaultClaimSet(new Claim(ClaimTypes.Name, securityToken.Info.Username, Rights.PossessProperty));

                var policies = new List <IAuthorizationPolicy>(1)
                {
                    new SecurityTokenAuthorizationPolicy(userClaimSet)
                };
                return(policies.AsReadOnly());
            }

            return(null);
        }
예제 #55
0
 protected override bool CanValidateTokenCore(System.IdentityModel.Tokens.SecurityToken token)
 {
     return(token is SecurityToken);
 }
예제 #56
0
        /// <summary>
        /// Writes the given UsernameSecurityToken to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to write the token to.</param>
        /// <param name="token">SecurityToken to be written.</param>
        /// <exception cref="InvalidOperationException">The given token is not a UsernameSecurityToken.</exception>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'token' is null.</exception>
        public override void WriteToken(XmlWriter writer, SecurityToken token)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            UserNameSecurityToken usernameSecurityToken = token as UserNameSecurityToken;

            if (usernameSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID0018, typeof(UserNameSecurityToken)));
            }

            // <wsse:UsernameToken
            writer.WriteStartElement(
                WSSecurity10Constants.Elements.UsernameToken,
                WSSecurity10Constants.Namespace
                );
            if (!string.IsNullOrEmpty(token.Id))
            {
                // wsu:Id="..."
                writer.WriteAttributeString(
                    WSUtilityConstants.Attributes.IdAttribute,
                    WSUtilityConstants.NamespaceURI,
                    token.Id
                    );
            }
            // <wsse:Username>...</wsse:Username>
            writer.WriteElementString(
                WSSecurity10Constants.Elements.Username,
                WSSecurity10Constants.Namespace,
                usernameSecurityToken.UserName
                );

            // <wsse:Password>...</wsse:Password>
            if (usernameSecurityToken.Password != null)
            {
                writer.WriteStartElement(
                    WSSecurity10Constants.Elements.Password,
                    WSSecurity10Constants.Namespace
                    );

                writer.WriteAttributeString(
                    WSSecurity10Constants.Attributes.Type,
                    null,
                    WSSecurity10Constants.UPTokenPasswordTextValue
                    );

                writer.WriteString(usernameSecurityToken.Password);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();

            writer.Flush();
        }
        public override ClaimsIdentityCollection ValidateToken(SecurityToken token)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomUserNameSecurityTokenHandler.ValidateToken",
              "MyTraceSource", SourceLevels.Information);

            //StackTracer.TraceStack(ts);

            UserNameSecurityToken usernameToken = token as UserNameSecurityToken;
            if (usernameToken == null)
            {
                throw new ArgumentException("usernameToken", "The security token is not a valid username security token.");
            }

            // will throw if fails
            UsernameCredentialStore.AuthenticateUser(usernameToken.UserName, usernameToken.Password);
            
            ClaimsIdentityCollection identities = new ClaimsIdentityCollection();

            IClaimsIdentity claimsIdentity = new ClaimsIdentity("CustomUserNameSecurityTokenHandler");
            claimsIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, usernameToken.UserName));

            identities.Add(claimsIdentity);

            return identities;                      
        }