private void ProcessSamlSecurityToken() { string proofToken = "1"; string issuerToken = "2"; string samlConditions = "3"; string samlSubjectNameFormat = "4"; string samlSubjectEmailAddress = "5"; //<snippet5> // Create the list of SAML Attributes. List <SamlAttribute> samlAttributes = new List <SamlAttribute>(); // Add the userAuthenticated claim. List <string> strList = new List <string>(); strList.Add("true"); SamlAttribute mySamlAttribute = new SamlAttribute("http://www.tmpuri.org", "userAuthenticated", strList); samlAttributes.Add(mySamlAttribute); // Create the SAML token with the userAuthenticated claim. It is assumed that // the method CreateSamlToken() is implemented as part of STS-A. SamlSecurityToken samlToken = CreateSamlToken( proofToken, issuerToken, samlConditions, samlSubjectNameFormat, samlSubjectEmailAddress, samlAttributes); //</snippet5> }
/// <summary> /// Creates the security token /// </summary> /// <param name="timeout">Maximum amount of time the method is supposed to take. Ignored in this implementation.</param> /// <returns>A SecurityToken that corresponds to the SAML assertion and proof key specified at construction time</returns> protected override SecurityToken GetTokenCore(TimeSpan timeout) { // Create a SamlSecurityToken from the provided assertion. SamlSecurityToken samlToken = new SamlSecurityToken(assertion); // Create a SecurityTokenSerializer that is used to serialize the SamlSecurityToken WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer(); // Create a memory stream to write the serialized token into // Use an initial size of 64Kb MemoryStream s = new MemoryStream(UInt16.MaxValue); // Create an XmlWriter over the stream XmlWriter xw = XmlWriter.Create(s); // Write the SamlSecurityToken into the stream ser.WriteToken(xw, samlToken); // Seek back to the beginning of the stream s.Seek(0, SeekOrigin.Begin); // Load the serialized token into a DOM XmlDocument dom = new XmlDocument(); dom.Load(s); // Create a KeyIdentifierClause for the SamlSecurityToken SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = samlToken.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>(); // Return a GenericXmlToken from the XML for the SamlSecurityToken, the proof token, the valid from // and valid until times from the assertion and the key identifier clause created above return new GenericXmlSecurityToken(dom.DocumentElement, proofToken, assertion.Conditions.NotBefore, assertion.Conditions.NotOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null); }
/// <summary> /// Gets claims identities from the specified SAML token as a GenericXmlSecurityToken /// </summary> /// <param name="token">SAML token to get identities from</param> /// <param name="audienceUri">Audience URI used to obtain the token</param> /// <param name="trustIssuer">True to automatically trust the issuer. /// False to validate the issuer against the app configuration</param> /// <returns>A collection of claims identities from the SAML token.</returns> public static IEnumerable <ClaimsIdentity> GetIdentitiesFromSamlToken(SecurityToken token, string audienceUri, bool trustIssuer) { SamlSecurityTokenHandler handler = new SamlSecurityTokenHandler { Configuration = new SecurityTokenHandlerConfiguration() }; SamlSecurityToken samlToken = token as SamlSecurityToken; if (samlToken == null && token is GenericXmlSecurityToken) { samlToken = handler.ReadToken(new XmlNodeReader(((GenericXmlSecurityToken)token).TokenXml)) as SamlSecurityToken; } if (samlToken == null) { throw new ArgumentException("The token must be a SAML token or a generic XML SAML token"); } handler.SamlSecurityTokenRequirement.CertificateValidator = X509CertificateValidator.None; handler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUri)); if (trustIssuer) { // configure to auto-trust the issuer ConfigurationBasedIssuerNameRegistry issuers = handler.Configuration.IssuerNameRegistry as ConfigurationBasedIssuerNameRegistry; issuers.AddTrustedIssuer(((X509SecurityToken)samlToken.Assertion.SigningToken).Certificate.Thumbprint, "sts"); } else { handler.Configuration.IssuerNameRegistry.LoadCustomConfiguration( SystemIdentityModelSection.DefaultIdentityConfigurationElement.IssuerNameRegistry.ChildNodes); } return(handler.ValidateToken(samlToken)); }
public SamlSecurityToken ReturnSamlSecurityToken() { string proofToken = "1"; string issuerToken = "2"; string samlConditions = "3"; string samlSubjectNameFormat = "4"; string samlSubjectEmailAddress = "5"; //<snippet3> // Create the list of SAML Attributes. List <SamlAttribute> samlAttributes = new List <SamlAttribute>(); // Add the accessAuthorized claim. List <string> strList = new List <string>(); strList.Add("true"); samlAttributes.Add(new SamlAttribute("http://www.tmpuri.org", "accessAuthorized", strList)); // Create the SAML token with the accessAuthorized claim. It is assumed that // the method CreateSamlToken() is implemented as part of STS-B. SamlSecurityToken samlToken = CreateSamlToken( proofToken, issuerToken, samlConditions, samlSubjectNameFormat, samlSubjectEmailAddress, samlAttributes); //</snippet3> return(samlToken); }
public void CompareSamlSecurityTokens() { TestUtilities.WriteHeader($"{this}.CompareSamlSecurityTokens", true); var context = new CompareContext($"{this}.CompareSamlSecurityTokens"); var samlSecurityToken1 = new SamlSecurityToken(new SamlAssertion(Guid.NewGuid().ToString(), Default.Issuer, DateTime.Parse(Default.IssueInstantString), null, new SamlAdvice(), new List <SamlStatement> { new SamlAttributeStatement(new SamlSubject(), new List <SamlAttribute> { new SamlAttribute("1", "2", "3") }) })); var samlSecurityToken2 = new SamlSecurityToken(new SamlAssertion(Guid.NewGuid().ToString(), Default.Issuer, DateTime.Parse(Default.IssueInstantString), null, new SamlAdvice(), new List <SamlStatement> { new SamlAttributeStatement(new SamlSubject(), new List <SamlAttribute> { new SamlAttribute("1", "2", "3") }) })); IdentityComparer.AreEqual(samlSecurityToken1, samlSecurityToken2, context); Assert.True(context.Diffs.Count(s => s == "Assertion:") == 1); Assert.True(context.Diffs.Count(s => s == "AssertionId:") == 1); Assert.True(context.Diffs.Count(s => s == "Id:") == 1); }
/// <summary> /// Creates the security token /// </summary> /// <param name="timeout">Maximum amount of time the method is supposed to take. Ignored in this implementation.</param> /// <returns>A SecurityToken corresponding the SAML assertion and proof key specified at construction time</returns> protected override SecurityToken GetTokenCore(TimeSpan timeout) { // Create a SamlSecurityToken from the provided assertion SamlSecurityToken samlToken = new SamlSecurityToken(assertion); // Create a SecurityTokenSerializer that will be used to serialize the SamlSecurityToken WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer(); // Create a memory stream to write the serialized token into // Use an initial size of 64Kb MemoryStream s = new MemoryStream(UInt16.MaxValue); // Create an XmlWriter over the stream XmlWriter xw = XmlWriter.Create(s); // Write the SamlSecurityToken into the stream ser.WriteToken(xw, samlToken); // Seek back to the beginning of the stream s.Seek(0, SeekOrigin.Begin); // Load the serialized token into a DOM XmlDocument dom = new XmlDocument(); dom.Load(s); // Create a KeyIdentifierClause for the SamlSecurityToken SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = samlToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>(); // Return a GenericXmlToken from the XML for the SamlSecurityToken, the proof token, the valid from // and valid until times from the assertion and the key identifier clause created above return(new GenericXmlSecurityToken(dom.DocumentElement, proofToken, assertion.Conditions.NotBefore, assertion.Conditions.NotOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null)); }
public BootstrapContext CreateBootStrapContext(IEnumerable <Claim> claims) { ClaimsIdentity id = new ClaimsIdentity(claims); SamlSecurityToken bootStrapToken = TokenHelper.CreateSamlToken(id, FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Realm); return(new BootstrapContext(bootStrapToken, FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[bootStrapToken.GetType()])); }
/// <summary> /// Token Constructor /// </summary> /// <param name="xmlToken">Encrypted xml token</param> public Token(String xmlToken) { byte[] decryptedData = decryptToken(xmlToken); XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8)); m_token = (SamlSecurityToken)WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null); SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List <SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[] { new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator() }), MaximumTokenSkew); if (authenticator.CanValidateToken(m_token)) { ReadOnlyCollection <IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token); m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies); FindIdentityClaims(); } else { throw new Exception("Unable to validate the token."); } }
protected override SecurityToken GetTokenCore(TimeSpan timeout) { SecurityToken securityToken; SamlAssertion samlAssertion; if (base.TokenRequirement.KeyType == SecurityKeyType.SymmetricKey) { securityToken = SamlSecurityTokenProvider.CreateSymmetricProofToken(base.TokenRequirement.KeySize); samlAssertion = this.CreateSamlAssertionWithSymmetricKey((BinarySecretSecurityToken)securityToken); } else { if (base.TokenRequirement.KeyType != SecurityKeyType.AsymmetricKey) { throw new ArgumentOutOfRangeException("KeyType"); } securityToken = SamlSecurityTokenProvider.CreateAsymmetricProofToken(); samlAssertion = this.CreateSamlAssertionWithAsymmetricKey(securityToken); } SamlSecurityToken samlSecurityToken = new SamlSecurityToken(samlAssertion); XmlDocument xmlDocument = new XmlDocument(); using (XmlWriter xmlWriter = xmlDocument.CreateNavigator().AppendChild()) { WSSecurityTokenSerializer wSSecurityTokenSerializer = new WSSecurityTokenSerializer(); wSSecurityTokenSerializer.WriteToken(xmlWriter, samlSecurityToken); } SamlAssertionKeyIdentifierClause samlAssertionKeyIdentifierClause = samlSecurityToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>(); return(new GenericXmlSecurityToken(xmlDocument.DocumentElement, securityToken, samlAssertion.Conditions.NotBefore, samlAssertion.Conditions.NotOnOrAfter, samlAssertionKeyIdentifierClause, samlAssertionKeyIdentifierClause, null)); }
/// <summary> /// Token Authentication. Translates the decrypted data into a AuthContext. /// </summary> /// <param name="reader">The token XML reader.</param> /// <param name="audience">The audience that the token must be scoped for. /// Use <c>null</c> to indicate any audience is acceptable.</param> /// <returns> /// The authorization context carried by the token. /// </returns> internal static AuthorizationContext AuthenticateToken(XmlReader reader, Uri audience) { Contract.Ensures(Contract.Result <AuthorizationContext>() != null); // Extensibility Point: // in order to accept different token types, you would need to add additional // code to create an authenticationcontext from the security token. // This code only supports SamlSecurityToken objects. SamlSecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null) as SamlSecurityToken; if (null == token) { throw new InformationCardException("Unable to read security token"); } ////if (null != token.SecurityKeys && token.SecurityKeys.Count > 0) //// throw new InformationCardException("Token Security Keys Exist"); if (audience == null) { Logger.InfoCard.Warn("SAML token Audience checking will be skipped."); } else { if (token.Assertion.Conditions != null && token.Assertion.Conditions.Conditions != null) { foreach (SamlCondition condition in token.Assertion.Conditions.Conditions) { SamlAudienceRestrictionCondition audienceCondition = condition as SamlAudienceRestrictionCondition; if (audienceCondition != null) { Logger.InfoCard.DebugFormat("SAML token audience(s): {0}", audienceCondition.Audiences.ToStringDeferred()); bool match = audienceCondition.Audiences.Contains(audience); if (!match && Logger.InfoCard.IsErrorEnabled) { Logger.InfoCard.ErrorFormat("Expected SAML token audience of {0} but found {1}.", audience.AbsoluteUri, audienceCondition.Audiences.Select(aud => aud.AbsoluteUri).ToStringDeferred()); } // The token is invalid if any condition is not valid. // An audience restriction condition is valid if any audience // matches the Relying Party. ErrorUtilities.VerifyInfoCard(match, InfoCardStrings.AudienceMismatch); } } } } var samlAuthenticator = new SamlSecurityTokenAuthenticator( new List <SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[] { new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator(), }), MaximumClockSkew); return(AuthorizationContext.CreateDefaultAuthorizationContext(samlAuthenticator.ValidateToken(token))); }
private bool IsCurrentlyTimeEffective(SamlSecurityToken token) { if (token.Assertion.Conditions != null) { return System.IdentityModel.SecurityUtils.IsCurrentlyTimeEffective(token.Assertion.Conditions.NotBefore, token.Assertion.Conditions.NotOnOrAfter, this.maxClockSkew); } return true; }
private bool IsCurrentlyTimeEffective(SamlSecurityToken token) { if (token.Assertion.Conditions != null) { return(System.IdentityModel.SecurityUtils.IsCurrentlyTimeEffective(token.Assertion.Conditions.NotBefore, token.Assertion.Conditions.NotOnOrAfter, this.maxClockSkew)); } return(true); }
public virtual void WriteToken(SamlSecurityToken token, XmlWriter writer, SecurityTokenSerializer keyInfoSerializer) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); #pragma warning suppress 56506 // token.Assertion is never null. token.Assertion.WriteTo(writer, this, keyInfoSerializer); }
/// <summary> /// Token Authentication. Translates the decrypted data into a AuthContext /// /// This method makes a strong assumption that the decrypted token in in UTF-8 format. /// </summary> /// <param name="decryptedTokenData">Decrypted token</param> public static AuthorizationContext AuthenticateToken(byte[] decryptedTokenData) { string t = Encoding.UTF8.GetString(decryptedTokenData); XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedTokenData), Encoding.UTF8)); // Extensibility Point: // in order to accept different token types, you would need to add additional // code to create an authenticationcontext from the security token. // This code only supports SamlSecurityToken objects. SamlSecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null) as SamlSecurityToken; if( null == token ) throw new InformationCardException("Unable to read security token"); if (null != token.SecurityKeys && token.SecurityKeys.Count > 0) throw new InformationCardException("Token Security Keys Exist"); if (null != _audience && null != token.Assertion.Conditions && null != token.Assertion.Conditions.Conditions) { foreach (SamlCondition condition in token.Assertion.Conditions.Conditions) { SamlAudienceRestrictionCondition audienceCondition = condition as SamlAudienceRestrictionCondition; if (null != audienceCondition) { bool match = false; foreach (Uri audience in audienceCondition.Audiences) { match = audience.Equals(_audience); if (match) break; } // // The token is invalid if any condition is not valid. // An audience restriction condition is valid if any audience // matches the Relying Party. // if (!match) { throw new InformationCardException("The token is invalid: The audience restrictions does not match the Relying Party."); } } } } /*SamlSecurityTokenAuthenticator SamlAuthenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[]{ new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator() }), MaximumTokenSkew);*/ SamlSecurityTokenAuthenticator SamlAuthenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[]{ new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator(X509CertificateValidator.None) }), MaximumTokenSkew); return AuthorizationContext.CreateDefaultAuthorizationContext(SamlAuthenticator.ValidateToken(token)); }
/// <summary> /// Requests an SWT Token using an input SAML token. /// </summary> /// <param name="token">The input SAML token.</param> /// <param name="scope">The requested scope.</param> /// <returns>The requested SWT token</returns> public SimpleWebToken Issue(SamlSecurityToken token, Uri scope) { var handler = new SamlSecurityTokenHandler(); var sb = new StringBuilder(128); handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token); return IssueAssertion(sb.ToString(), "SAML", scope); }
private void CreateSamlTokens(SecurityTokenDescriptor tokenDescriptor) { SamlSecurityTokenHandler samlTokenHandler = new SamlSecurityTokenHandler(); SamlSecurityToken token = samlTokenHandler.CreateToken(tokenDescriptor) as SamlSecurityToken; MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms); samlTokenHandler.WriteToken(writer, token); }
private void ParseToken(string xmlToken, X509Certificate2 cert) { int skew = 300; // default to 5 minutes string tokenskew = System.Configuration.ConfigurationManager.AppSettings["MaximumClockSkew"]; if (!string.IsNullOrEmpty(tokenskew)) { skew = Int32.Parse(tokenskew); } XmlReader tokenReader = new XmlTextReader(new StringReader(xmlToken)); EncryptedData enc = new EncryptedData(); enc.TokenSerializer = WSSecurityTokenSerializer.DefaultInstance; enc.ReadFrom(tokenReader); List <SecurityToken> tokens = new List <SecurityToken>(); SecurityToken encryptingToken = new X509SecurityToken(cert); tokens.Add(encryptingToken); SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false); SymmetricSecurityKey encryptingCrypto; // an error here usually means that you have selected the wrong key. encryptingCrypto = (SymmetricSecurityKey)tokenResolver.ResolveSecurityKey(enc.KeyIdentifier[0]); SymmetricAlgorithm algorithm = encryptingCrypto.GetSymmetricAlgorithm(enc.EncryptionMethod); byte[] decryptedData = enc.GetDecryptedBuffer(algorithm); SecurityTokenSerializer tokenSerializer = WSSecurityTokenSerializer.DefaultInstance; XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8)); m_token = (SamlSecurityToken)tokenSerializer.ReadToken(reader, tokenResolver); SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List <SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[] { new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator() }), new TimeSpan(0, 0, skew)); if (authenticator.CanValidateToken(m_token)) { ReadOnlyCollection <IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token); m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies); m_identityClaims = FindIdentityClaims(m_authorizationContext); } else { throw new Exception("Unable to validate the token."); } }
bool IsCurrentlyTimeEffective(SamlSecurityToken token) { if (token.Assertion.Conditions != null) { return(SecurityUtils.IsCurrentlyTimeEffective(token.Assertion.Conditions.NotBefore, token.Assertion.Conditions.NotOnOrAfter, this.maxClockSkew)); } // If SAML Condition is not present then the assertion is valid at any given time. return(true); }
private void RenewIfNeeded() { if (_validToken == null || _validToken.Expires < (DateTime.Now + new TimeSpan(0, 0, 30))) { _validToken = _stsClient.IssueBearerTokenByUserCredential( _user, _password); } }
public PutResponse Put(PutRequest request, SamlSecurityToken token) { PutResponse response; Put(request, out response, token); // the response has no information if it isn't a fault // PutResponse putResponseTyped = putResponse.GetBody<PutResponse>(new ClientSerializer(typeof(PutResponse))); return(response); }
private static void CallMixedMode(SamlSecurityToken token) { var factory = new ChannelFactory <IServiceClientChannel>("*"); factory.ConfigureChannelFactory <IServiceClientChannel>(); var proxy = factory.CreateChannelWithIssuedToken <IServiceClientChannel>(token); proxy.Ping("foo"); proxy.Close(); }
/// <summary> /// Requests an SWT Token using an input SAML token. /// </summary> /// <param name="token">The input SAML token.</param> /// <param name="scope">The requested scope.</param> /// <returns>The requested SWT token</returns> public SimpleWebToken Issue(SamlSecurityToken token, Uri scope) { var handler = new SamlSecurityTokenHandler(); var sb = new StringBuilder(128); handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token); return(IssueAssertion(sb.ToString(), "SAML", scope)); }
public ITokenVisualizer GetTokenVisualizer(SecurityToken token) { SamlSecurityToken samlSecurityToken = token as SamlSecurityToken; if (samlSecurityToken == null) { throw new ArgumentException("Token is not a SamlSecurityToken."); } return(new SamlTokenVisualizer(samlSecurityToken)); }
/// <summary> /// Creates a user identity for the policy. /// </summary> private IUserIdentity CreateUserIdentity(UserTokenPolicy policy) { if (policy == null || policy.TokenType == UserTokenType.Anonymous) { return(null); } if (policy.TokenType == UserTokenType.UserName) { return(new UserIdentity("SomeUser", "password")); } if (policy.TokenType == UserTokenType.Certificate) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); try { foreach (X509Certificate2 certificate in store.Certificates) { if (certificate.HasPrivateKey) { return(new UserIdentity(certificate)); } } return(null); } finally { store.Close(); } } if (policy.TokenType == UserTokenType.IssuedToken) { CertificateIdentifier userid = new CertificateIdentifier(); userid.StoreType = CertificateStoreType.Windows; userid.StorePath = "LocalMachine\\Root"; userid.SubjectName = "UASampleRoot"; X509Certificate2 certificate = userid.Find(); X509SecurityToken signingToken = new X509SecurityToken(certificate); SamlSecurityToken token = CreateSAMLToken("*****@*****.**", signingToken); return(new UserIdentity(token)); } throw ServiceResultException.Create(StatusCodes.BadSecurityPolicyRejected, "User token policy is not supported."); }
private void CreateClaims(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { try { samlSecurityTokenHandler.CreateClaimsPublic(samlToken, issuer, validationParameters); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
private static void InitializeSecurityContext(string tokenString) { tokenString = CryptographyHelper.DecryptFromLocalMachine(tokenString); SettingsSecureFileStore securitySettings = new SettingsSecureFileStore(); ServiceConfiguration configs = securitySettings.GetConfigurations(); if (configs != null) { SecurityToken token = Helper.DeSerializeSecurityToken(tokenString, configs.get_STSThumbprint(), configs.get_STSThumbprintName()); ServiceHelperFactory.get_Instance().set_BaseUri(configs.get_ServiceBaseUrl()); ClientConfiguration settings = securitySettings.GetClientSettingsFromConfigDll(); if (settings == null) { Program.logger.Error("Client configurations for security service not found"); } if (settings != null) { string clientIDFromToken = string.Empty; List <RequestClaim> customClaims = new List <RequestClaim>(); SamlSecurityToken samlToken = token as SamlSecurityToken; if ((samlToken == null || samlToken.Assertion == null || samlToken.Assertion.Statements == null ? false : samlToken.Assertion.Statements.Count > 0)) { SamlAttributeStatement statements = samlToken.Assertion.Statements[0] as SamlAttributeStatement; if ((statements == null || statements.Attributes == null ? false : statements.Attributes.Count > 0)) { SamlAttribute ClientId = statements.Attributes.FirstOrDefault <SamlAttribute>((SamlAttribute z) => StringUtility.EqualsIgnoreCase(z.Name, "clientid")); if ((ClientId == null || ClientId.AttributeValues == null ? false : ClientId.AttributeValues.Count > 0)) { clientIDFromToken = ClientId.AttributeValues[0]; customClaims.Add(new RequestClaim("http://schemas.imanami.com/ws/2014/06/identity/claims/clientId", true, clientIDFromToken)); } } } settings.set_ActAsClientUrl(ServiceHelperFactory.get_Instance().get_BaseUri()); NetworkCredential creds = CredentialCache.DefaultCredentials as NetworkCredential; ClaimsPrincipalSelector claimsPrincipalSelector = (clientIDFromToken == string.Empty ? new ClaimsPrincipalSelector(creds, settings, null) : new ClaimsPrincipalSelector(creds, settings, customClaims)); claimsPrincipalSelector.GetClaimsPrincipal(); ClaimsPrincipal.ClaimsPrincipalSelector = new Func <ClaimsPrincipal>(claimsPrincipalSelector.GetClaimsPrincipal); if (claimsPrincipalSelector.get_ClaimsPrincipal() != null) { claimsPrincipalSelector.get_ClaimsPrincipal().set_ActAsToken(token); } ServiceHelperFactory.get_Instance().set_StsClientConfiguration(settings); ServiceHelperFactory.get_Instance().set_StsUserCredentials(creds); } } else { Program.logger.Error("Client configurations not found"); } }
public void AddTokenTest() { var key = new Uri("http://www.tokencache.com/"); SecurityToken token = new SamlSecurityToken(new SamlAssertion()); TokenCacheHelper.AddToken(key, token); var t = TokenCacheHelper.GetToken(key); Assert.AreEqual(token, t); TokenCacheHelper.AddToken(key, token); t = TokenCacheHelper.GetToken(key); Assert.AreEqual(token, t); }
private static string SerializeToken(SamlAssertion assertion) { SamlSecurityToken token = new SamlSecurityToken(assertion); SamlSerializer serializer = new SamlSerializer(); WSSecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer(); StringWriter stringWriter = new StringWriter(); XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter); serializer.WriteToken(token, xmltextWriter, tokenSerializer); return(stringWriter.ToString()); }
private void ValidateIssuer() { PublicSamlSecurityTokenHandler samlSecurityTokenHandler = new PublicSamlSecurityTokenHandler(); SamlSecurityToken samlToken = IdentityUtilities.CreateSamlSecurityToken(); ValidateIssuer(IdentityUtilities.DefaultIssuer, null, samlToken, samlSecurityTokenHandler, ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters")); ValidateIssuer("bob", null, samlToken, samlSecurityTokenHandler, ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters")); ValidateIssuer("bob", new TokenValidationParameters { ValidateIssuer = false }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); ValidateIssuer("bob", new TokenValidationParameters { }, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204")); ValidateIssuer(IdentityUtilities.DefaultIssuer, new TokenValidationParameters { ValidIssuer = IdentityUtilities.DefaultIssuer }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); ValidateIssuer("bob", new TokenValidationParameters { ValidIssuer = "frank" }, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205")); List <string> validIssuers = new List <string> { "john", "paul", "george", "ringo" }; ValidateIssuer("bob", new TokenValidationParameters { ValidIssuers = validIssuers }, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205")); ValidateIssuer("bob", new TokenValidationParameters { ValidateIssuer = false }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); validIssuers.Add(IdentityUtilities.DefaultIssuer); string issuer = ValidateIssuer(IdentityUtilities.DefaultIssuer, new TokenValidationParameters { ValidIssuers = validIssuers }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); Assert.IsTrue(issuer == IdentityUtilities.DefaultIssuer, "issuer mismatch"); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidateAudience = false, IssuerValidator = IdentityUtilities.IssuerValidatorEcho, }; ValidateIssuer("bob", validationParameters, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204")); validationParameters.ValidateIssuer = false; validationParameters.IssuerValidator = IdentityUtilities.IssuerValidatorThrows; ValidateIssuer("bob", validationParameters, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); }
public string GetSaml11Token() { var claimSets = new List <ClaimSet>(ServiceSecurityContext.Current.AuthorizationContext.ClaimSets); ClaimSet claimSet = claimSets.Find((Predicate <ClaimSet>) delegate(ClaimSet target) { WindowsClaimSet defaultClaimSet = target.Issuer as WindowsClaimSet; return(defaultClaimSet != null); }); var accessControlClaims = claimSet.FindClaims(ClaimTypes.Sid, Rights.PossessProperty); SamlAssertion assertion = Saml11Helper.CreateSamlAssertionFromUserNameClaims(accessControlClaims); SamlSecurityToken token = new SamlSecurityToken(assertion); return(Saml11Helper.SerializeSamlToken(token)); }
private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, IList <ClaimTypeRequirement> claimReqs) { // Create list of confirmation strings List <string> confirmations = new List <string>(); // Add holder-of-key string to list of confirmation strings confirmations.Add(SamlConstants.HolderOfKey); // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier); // Create a list of SAML attributes List <SamlAttribute> attributes = new List <SamlAttribute>(); // Get the claimset we want to place into the SAML assertion ClaimSet cs = GetClaimSet(claimReqs); // Iterate through the claims and add a SamlAttribute for each claim // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims foreach (Claim c in cs) { attributes.Add(new SamlAttribute(c)); } // 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 SamlConditions conditions = new SamlConditions(validFrom, validTo); // Create the SAML assertion SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements); // Set the signing credentials for the SAML assertion string signatureAlgorithm = GetSignatureAlgorithm(signingKey); assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier); SamlSecurityToken token = new SamlSecurityToken(assertion); Console.WriteLine("token.SecurityKeys.Count: {0}", token.SecurityKeys.Count); return(token); }
private static void SerializeSamlTokenToFile(SamlSecurityToken token) { using (var sw = new StreamWriter(@"C:\Data\SVN-Client\dialog\Dialog\WindowsIdentityToClaimsConsole\saml.xml")) { try { var xml = Saml11Helper.SerializeSamlToken(token); sw.Write(xml); Console.WriteLine("Saml Token Successfully Written"); } catch (Exception ex) { Console.WriteLine("Failed to save Saml Token to Disk"); } } }
protected override SecurityToken GetTokenCore(TimeSpan timeout) { SamlSecurityToken samlSecurityToken = new SamlSecurityToken(this.assertion); WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer(); MemoryStream memoryStream = new MemoryStream(65535); XmlWriter writer = XmlWriter.Create(memoryStream); wssecurityTokenSerializer.WriteToken(writer, samlSecurityToken); memoryStream.Seek(0L, SeekOrigin.Begin); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(memoryStream); SamlAssertionKeyIdentifierClause samlAssertionKeyIdentifierClause = samlSecurityToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>(); return(new GenericXmlSecurityToken(xmlDocument.DocumentElement, this.proofToken, this.assertion.Conditions.NotBefore, this.assertion.Conditions.NotOnOrAfter, samlAssertionKeyIdentifierClause, samlAssertionKeyIdentifierClause, null)); }
public static string SerializeSamlToken(SamlSecurityToken token) { var samlBuilder = new StringBuilder(); using (var writer = XmlWriter.Create(samlBuilder)) { try { var keyInfoSerializer = new WSSecurityTokenSerializer(); keyInfoSerializer.WriteToken(writer, token); Console.WriteLine("Saml Token Successfully Created"); } catch (Exception) { Console.WriteLine("Failed to seralize token"); } } return(samlBuilder.ToString()); }
private static void CallMessage(SamlSecurityToken token) { var factory = new ChannelFactory<IServiceClientChannel>( new ClientSamlHttpBinding(SecurityMode.Message), new EndpointAddress( new Uri("http://roadie:9000/Services/ClientSaml/Message"), EndpointIdentity.CreateDnsIdentity("Service"))); factory.Credentials.ServiceCertificate.SetDefaultCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=Service"); factory.ConfigureChannelFactory<IServiceClientChannel>(); var proxy = factory.CreateChannelWithIssuedToken<IServiceClientChannel>(token); proxy.Ping("foo"); proxy.Close(); }
/// <summary> /// Token Constructor /// </summary> /// <param name="xmlToken">Encrypted xml token</param> public Token(String xmlToken) { byte[] decryptedData = decryptToken(xmlToken); XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8)); m_token = (SamlSecurityToken)WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null); SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[]{ new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator() }), MaximumTokenSkew); if (authenticator.CanValidateToken(m_token)) { ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token); m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies); FindIdentityClaims(); } else { throw new Exception("Unable to validate the token."); } }
public virtual void WriteToken (SamlSecurityToken token, XmlWriter writer, SecurityTokenSerializer keyInfoSerializer) { throw new NotImplementedException (); }
/// <summary> /// Build the contents of the SAML token /// </summary> /// <param name="writer"><b>XmlDictionaryWriter</b> to write the contents of this token to</param> protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { // Subject SamlSubject subject = new SamlSubject(); if ( this.useKey != null ) { // Add the key and the Holder-Of-Key confirmation method subject.KeyIdentifier = this.useKey; subject.ConfirmationMethods.Add( SamlConstants.HolderOfKey ); } else { // This is a bearer token subject.ConfirmationMethods.Add( SamlConstants.SenderVouches ); } // Attributes, statements, conditions, and assertions List<SamlStatement> statements = new List<SamlStatement>(); List<SamlAttribute> attributes = GetTokenAttributes(); statements.Add(new SamlAuthenticationStatement(subject, Constants.Saml.AuthenticationMethods.Unspecified, DateTime.Now, null, null, null)); statements.Add(new SamlAttributeStatement(subject, attributes)); SamlConditions conditions = new SamlConditions(DateTime.Now, (DateTime.Now + TimeSpan.FromHours(8.0))); SamlAssertion assertion = new SamlAssertion("uuid-" + Guid.NewGuid(), Program.Issuer, DateTime.Now, conditions, null, statements); // Build the signing token SecurityToken signingToken = new X509SecurityToken(Program.SigningCertificate); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>()); SigningCredentials signingCredentials = new SigningCredentials(signingToken.SecurityKeys[0], SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, keyIdentifier); assertion.SigningCredentials = signingCredentials; // Build the SAML token SamlSecurityToken token = new SamlSecurityToken(assertion); SecurityKeyIdentifierClause attachedReference = token.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>(); SecurityKeyIdentifierClause unattachedReference = token.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>(); // // Write the XML // //writer = XmlDictionaryWriter.CreateTextWriter(File.CreateText("output.xml").BaseStream); // RSTR writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestSecurityTokenResponse, Constants.WSTrust.NamespaceUri.Uri); if (context != null) { writer.WriteAttributeString(Constants.WSTrust.Attributes.Context, context); } // TokenType writer.WriteElementString(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.TokenType, Constants.WSTrust.NamespaceUri.Uri, Constants.WSTrust.TokenTypes.Saml10Assertion); // RequestedSecurityToken (the SAML token) SecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer(); writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedSecurityToken, Constants.WSTrust.NamespaceUri.Uri); tokenSerializer.WriteToken(writer, token); writer.WriteEndElement(); // RequestedAttachedReference writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedAttachedReference, Constants.WSTrust.NamespaceUri.Uri); tokenSerializer.WriteKeyIdentifierClause(writer, attachedReference); writer.WriteEndElement(); // RequestedUnattachedReference writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedUnattachedReference, Constants.WSTrust.NamespaceUri.Uri); tokenSerializer.WriteKeyIdentifierClause(writer, unattachedReference); writer.WriteEndElement(); // RequestedDisplayToken (display token) string displayTokenNS = "http://schemas.xmlsoap.org/ws/2005/05/identity"; writer.WriteStartElement("wsid", "RequestedDisplayToken", displayTokenNS); writer.WriteStartElement("wsid", "DisplayToken", displayTokenNS); foreach (SamlAttribute attribute in attributes) { writer.WriteStartElement("wsid", "DisplayClaim", displayTokenNS); writer.WriteAttributeString("Uri", attribute.Namespace + "/" + attribute.Name); writer.WriteStartElement("wsid", "DisplayTag", displayTokenNS); writer.WriteValue(attribute.Name); writer.WriteEndElement(); writer.WriteStartElement("wsid", "Description", displayTokenNS); writer.WriteValue(attribute.Namespace + "/" + attribute.Name); writer.WriteEndElement(); foreach (string attributeValue in attribute.AttributeValues) { writer.WriteStartElement("wsid", "DisplayValue", displayTokenNS); writer.WriteValue(attributeValue); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); // RSTR End writer.WriteEndElement(); //writer.Close(); }
/// <summary> /// Generates SubjectCollection that represents a SamlToken. /// Only SamlAttributeStatements processed. /// Overwrite this method to customize the creation of statements. /// <para> /// Calls: /// 1. ProcessAttributeStatement for SamlAttributeStatements. /// 2. ProcessAuthenticationStatement for SamlAuthenticationStatements. /// 3. ProcessAuthorizationDecisionStatement for SamlAuthorizationDecisionStatements. /// 4. ProcessCustomStatement for other SamlStatements. /// </para> /// </summary> /// <param name="samlSecurityToken">The token used to generate the SubjectCollection.</param> /// <returns>ClaimsIdentity representing the subject of the SamlToken.</returns> /// <exception cref="ArgumentNullException">Thrown if 'samlSecurityToken' is null.</exception> protected virtual ClaimsIdentity CreateClaims(SamlSecurityToken samlSecurityToken) { if (samlSecurityToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSecurityToken"); } if (samlSecurityToken.Assertion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("samlSecurityToken", SR.GetString(SR.ID1034)); } // // Construct the subject and issuer identities. // Use claim types specified in the security token requirements used for IPrincipal.Role and IIdentity.Name // ClaimsIdentity subject = new ClaimsIdentity(AuthenticationTypes.Federation, _samlSecurityTokenRequirement.NameClaimType, _samlSecurityTokenRequirement.RoleClaimType); string issuer = null; if (this.Configuration == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } if (this.Configuration.IssuerNameRegistry == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4277)); } // SamlAssertion. The SigningToken may or may not be null. // The default IssuerNameRegistry will throw if null. // This callout is provided for extensibility scenarios with custom IssuerNameRegistry. issuer = this.Configuration.IssuerNameRegistry.GetIssuerName(samlSecurityToken.Assertion.SigningToken, samlSecurityToken.Assertion.Issuer); if (string.IsNullOrEmpty(issuer)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4175))); } ProcessStatement(samlSecurityToken.Assertion.Statements, subject, issuer); return subject; }
/// <summary> /// Creates the security token based on the tokenDescriptor passed in. /// </summary> /// <param name="tokenDescriptor">The security token descriptor that contains the information to build a token.</param> /// <exception cref="ArgumentNullException">Thrown if 'tokenDescriptor' is null.</exception> public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor) { if (tokenDescriptor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor"); } IEnumerable<SamlStatement> statements = CreateStatements(tokenDescriptor); // - NotBefore / NotAfter // - Audience Restriction SamlConditions conditions = CreateConditions(tokenDescriptor.Lifetime, tokenDescriptor.AppliesToAddress, tokenDescriptor); SamlAdvice advice = CreateAdvice(tokenDescriptor); string issuerName = tokenDescriptor.TokenIssuerName; SamlAssertion assertion = CreateAssertion(issuerName, conditions, advice, statements); if (assertion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4013))); } assertion.SigningCredentials = GetSigningCredentials(tokenDescriptor); SecurityToken token = new SamlSecurityToken(assertion); // // Encrypt the token if encrypting credentials are set // EncryptingCredentials encryptingCredentials = GetEncryptingCredentials(tokenDescriptor); if (encryptingCredentials != null) { token = new EncryptedSecurityToken(token, encryptingCredentials); } return token; }
public SamlTokenVisualizer(SamlSecurityToken token) { this.Token = token; }
/// <summary> /// Returns the time until which the token should be held in the token replay cache. /// </summary> /// <param name="token">The token to return an expiration time for.</param> /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception> /// <exception cref="SecurityTokenValidationException">The SamlSecurityToken's validity period is greater than the expiration period set to TokenReplayCache.</exception> /// <returns>A DateTime representing the expiration time.</returns> protected virtual DateTime GetTokenReplayCacheEntryExpirationTime(SamlSecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } // // DateTimeUtil handles overflows // DateTime maximumExpirationTime = DateTimeUtil.Add(DateTime.UtcNow, Configuration.TokenReplayCacheExpirationPeriod); // If the token validity period is greater than the TokenReplayCacheExpirationPeriod, throw if (DateTime.Compare(maximumExpirationTime, token.ValidTo) < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityTokenValidationException(SR.GetString(SR.ID1069, token.ValidTo.ToString(), Configuration.TokenReplayCacheExpirationPeriod.ToString()))); } return token.ValidTo; }
private static List<SamlAttribute> GetClaims(SamlSecurityToken samlToken) { IList<System.IdentityModel.Tokens.SamlAttribute> attributes = GetTokenAttributes(samlToken); if (attributes == null) return null; var claims = new List<SamlAttribute>(); foreach (System.IdentityModel.Tokens.SamlAttribute attribute in attributes) { claims.AddRange( SamlAttribute.SamlAttributeFromToken(attribute)); } return claims; }
private void ParseToken(string xmlToken, X509Certificate2 cert) { int skew = 300; // default to 5 minutes string tokenskew = System.Configuration.ConfigurationManager.AppSettings["MaximumClockSkew"]; if (!string.IsNullOrEmpty(tokenskew)) skew = Int32.Parse(tokenskew); XmlReader tokenReader = new XmlTextReader(new StringReader(xmlToken)); EncryptedData enc = new EncryptedData(); enc.TokenSerializer = WSSecurityTokenSerializer.DefaultInstance; enc.ReadFrom(tokenReader); List<SecurityToken> tokens = new List<SecurityToken>(); SecurityToken encryptingToken = new X509SecurityToken(cert); tokens.Add(encryptingToken); SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false); SymmetricSecurityKey encryptingCrypto; // an error here usually means that you have selected the wrong key. encryptingCrypto = (SymmetricSecurityKey)tokenResolver.ResolveSecurityKey(enc.KeyIdentifier[0]); SymmetricAlgorithm algorithm = encryptingCrypto.GetSymmetricAlgorithm(enc.EncryptionMethod); byte[] decryptedData = enc.GetDecryptedBuffer(algorithm); SecurityTokenSerializer tokenSerializer = WSSecurityTokenSerializer.DefaultInstance; XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8)); m_token = (SamlSecurityToken)tokenSerializer.ReadToken(reader, tokenResolver); SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>( new SecurityTokenAuthenticator[]{ new RsaSecurityTokenAuthenticator(), new X509SecurityTokenAuthenticator() }), new TimeSpan(0, 0, skew)); if (authenticator.CanValidateToken(m_token)) { ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token); m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies); m_identityClaims = FindIdentityClaims(m_authorizationContext); } else { throw new Exception("Unable to validate the token."); } }
private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, IList<ClaimTypeRequirement> claimReqs ) { // Create list of confirmation strings List<string> confirmations = new List<string>(); // Add holder-of-key string to list of confirmation strings confirmations.Add(SamlConstants.HolderOfKey); // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier); // Create a list of SAML attributes List<SamlAttribute> attributes = new List<SamlAttribute>(); // Get the claimset we want to place into the SAML assertion ClaimSet cs = GetClaimSet(claimReqs); // Iterate through the claims and add a SamlAttribute for each claim // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims foreach (Claim c in cs) attributes.Add(new SamlAttribute(c)); // 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 SamlConditions conditions = new SamlConditions(validFrom, validTo); // Create the SAML assertion SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements); // Set the signing credentials for the SAML assertion string signatureAlgorithm = GetSignatureAlgorithm(signingKey); assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier); SamlSecurityToken token = new SamlSecurityToken(assertion); Console.WriteLine("token.SecurityKeys.Count: {0}", token.SecurityKeys.Count); return token; }
private string ValidateIssuer(string issuer, TokenValidationParameters validationParameters, SamlSecurityToken samlToken, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { string returnVal = string.Empty; try { returnVal = samlSecurityTokenHandler.ValidateIssuerPublic(issuer, samlToken, validationParameters); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return returnVal; }
public virtual void WriteToken(SamlSecurityToken token, XmlWriter writer, SecurityTokenSerializer keyInfoSerializer) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } token.Assertion.WriteTo(writer, this, keyInfoSerializer); }
private static void CallMixedMode(SamlSecurityToken token) { var factory = new ChannelFactory<IServiceClientChannel>("*"); factory.ConfigureChannelFactory<IServiceClientChannel>(); var proxy = factory.CreateChannelWithIssuedToken<IServiceClientChannel>(token); proxy.Ping("foo"); proxy.Close(); }
public string ValidateIssuerPublic(string issuer, SamlSecurityToken samlToken, TokenValidationParameters validationParameters) { return base.ValidateIssuer(issuer, samlToken, validationParameters); }
/// <summary> /// Creates claims from a Saml securityToken. /// </summary> /// <param name="samlToken">A <see cref="SamlSecurityToken"/> that will be used to create the claims.</param> /// <param name="issuer">the issuer value for each <see cref="Claim"/> in the <see cref="ClaimsIdentity"/>.</param>/// /// <param name="validationParameters"> contains parameters for validating the securityToken.</param> /// <returns>A <see cref="ClaimsIdentity"/> containing the claims from the <see cref="SamlSecurityToken"/>.</returns> protected virtual ClaimsIdentity CreateClaimsIdentity(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters) { if (samlToken == null) { throw new ArgumentNullException("samlToken"); } if (string.IsNullOrWhiteSpace(issuer)) { throw new ArgumentException(ErrorMessages.IDX10221); } if (samlToken.Assertion == null) { throw new ArgumentException(ErrorMessages.IDX10202); } ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(samlToken, issuer); _smSamlHandlerPrivateNeverSetAnyProperties.ProcessStatmentPublic(samlToken.Assertion.Statements, identity, issuer); return identity; }
private void CreateClaims(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { try { samlSecurityTokenHandler.CreateClaimsPublic(samlToken, issuer, validationParameters ); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
bool IsCurrentlyTimeEffective(SamlSecurityToken token) { if (token.Assertion.Conditions != null) { return SecurityUtils.IsCurrentlyTimeEffective(token.Assertion.Conditions.NotBefore, token.Assertion.Conditions.NotOnOrAfter, this.maxClockSkew); } // If SAML Condition is not present then the assertion is valid at any given time. return true; }
private static IList<System.IdentityModel.Tokens.SamlAttribute> GetTokenAttributes(SamlSecurityToken samlToken) { IList<System.IdentityModel.Tokens.SamlAttribute> attributes = null; foreach (SamlStatement statement in samlToken.Assertion.Statements) if (statement.GetType() == typeof(SamlAttributeStatement)) attributes = ((SamlAttributeStatement)statement).Attributes; return attributes; }
public ClaimsIdentity CreateClaimsPublic(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters) { return base.CreateClaimsIdentity(samlToken, issuer, validationParameters); }
public SamlAuthorizationPolicy (SamlSecurityTokenAuthenticator authenticator, SamlSecurityToken token) : base (new UniqueId ().ToString ()) { this.authenticator = authenticator; this.token = token; }