/// <summary> /// Writes out the subject as an XElement. /// </summary> /// <param name="subject">The subject to create xml for.</param> /// <returns>XElement</returns> public static XElement ToXElement(this Saml2Subject subject) { if (subject == null) { throw new ArgumentNullException(nameof(subject)); } var element = new XElement(Saml2Namespaces.Saml2 + "Subject", subject.NameId.ToXElement()); foreach (var subjectConfirmation in subject.SubjectConfirmations) { element.Add(subjectConfirmation.ToXElement()); } if (subject.SubjectConfirmations.Count == 0) { // Although SubjectConfirmation is optional in the SAML core spec, it is // mandatory in the Web Browser SSO Profile and must have a value of bearer. element.Add(new Saml2SubjectConfirmation( new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer")).ToXElement()); } return(element); }
/// <summary> /// Creates a SAML assertion signed with the given certificate. /// </summary> public static Saml2SecurityToken CreateSaml2SecurityToken(byte[] certificate, string password, params Claim[] claims) { const string acsUrl = "http://blueprintsys.com"; var assertion = new Saml2Assertion(new Saml2NameIdentifier(DefaultIssuer)); var conditions = new Saml2Conditions { NotBefore = DateTime.UtcNow, NotOnOrAfter = DateTime.MaxValue }; conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(new Uri(acsUrl, UriKind.RelativeOrAbsolute))); assertion.Conditions = conditions; var subject = new Saml2Subject(); subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(Bearer)); assertion.Subject = subject; var statement = new Saml2AttributeStatement(); foreach (var claim in claims) { statement.Attributes.Add(new Saml2Attribute(claim.Type, claim.Value)); assertion.Statements.Add(statement); } var clientSigningCredentials = new X509SigningCredentials( new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable)); assertion.SigningCredentials = clientSigningCredentials; return(new Saml2SecurityToken(assertion)); }
/// <summary> /// Creates a SAML assertion signed with the given certificate. /// </summary> public static Saml2SecurityToken GetSamlAssertionSignedWithCertificate(String nameIdentifierClaim, byte[] certificateWithPrivateKeyRawBytes, string password) { string acsUrl = string.Format(CultureInfo.InvariantCulture, "https://{0}.{1}", SamplesConfiguration.ServiceNamespace, SamplesConfiguration.AcsHostUrl); Saml2Assertion assertion = new Saml2Assertion(new Saml2NameIdentifier(nameIdentifierClaim)); Saml2Conditions conditions = new Saml2Conditions(); conditions.NotBefore = DateTime.UtcNow; conditions.NotOnOrAfter = DateTime.MaxValue; conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(new Uri(acsUrl, UriKind.RelativeOrAbsolute))); assertion.Conditions = conditions; Saml2Subject subject = new Saml2Subject(); subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(Saml2Constants.ConfirmationMethods.Bearer)); subject.NameId = new Saml2NameIdentifier(nameIdentifierClaim); assertion.Subject = subject; X509SigningCredentials clientSigningCredentials = new X509SigningCredentials( new X509Certificate2(certificateWithPrivateKeyRawBytes, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable)); assertion.SigningCredentials = clientSigningCredentials; return(new Saml2SecurityToken(assertion)); }
public void Saml2SubjectExtensions_ToXElement_CheckNull() { Saml2Subject subject = null; Action a = () => subject.ToXElement(); a.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("subject"); }
private Saml2Assertion CreateSamlAssertion(SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier) { Claim claim = base.ClientCredentials.Claims.FirstOrDefault((Claim c) => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (claim == null) { throw new ArgumentException("At least one NameIdentifier/Identity claim must be present in the claimset", "ClaimsClientCredentials.Claims"); } Saml2Subject saml2Subject = new Saml2Subject { NameId = new Saml2NameIdentifier(claim.Value, new Uri("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified")) }; Saml2SubjectConfirmationData saml2SubjectConfirmationData = new Saml2SubjectConfirmationData(); saml2SubjectConfirmationData.KeyIdentifiers.Add(proofKeyIdentifier); saml2Subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"), saml2SubjectConfirmationData)); IEnumerable <Saml2Attribute> enumerable = from c in base.ClientCredentials.Claims.Except(new Claim[] { claim }) select new Saml2Attribute(c.Type, c.Value); Claim claim2 = base.ClientCredentials.Claims.FirstOrDefault((Claim c) => c.Type == "http://www.tridion.com/2009/08/directoryservice/claims/directoryServiceName"); Saml2NameIdentifier issuer; if (claim2 == null) { Saml2Attribute saml2Attribute = new Saml2Attribute("http://www.tridion.com/2009/08/directoryservice/claims/directoryServiceName", claim.Issuer); enumerable = enumerable.Concat(new Saml2Attribute[] { saml2Attribute }); issuer = new Saml2NameIdentifier(claim.Issuer); } else { issuer = new Saml2NameIdentifier(claim2.Value); } DateTime utcNow = DateTime.UtcNow; Saml2Assertion saml2Assertion = new Saml2Assertion(issuer) { Subject = saml2Subject, IssueInstant = utcNow, Conditions = new Saml2Conditions { NotBefore = new DateTime?(utcNow), NotOnOrAfter = new DateTime?(utcNow + base.TokenValidityTimeSpan) }, Advice = new Saml2Advice(), SigningCredentials = new SigningCredentials(signatureKey, base.SecurityAlgorithmSuite.DefaultAsymmetricSignatureAlgorithm, base.SecurityAlgorithmSuite.DefaultDigestAlgorithm, signatureKeyIdentifier) }; saml2Assertion.Statements.Add(new Saml2AttributeStatement(enumerable)); if (base.ClientCredentials.AudienceUris != null) { saml2Assertion.Conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(base.ClientCredentials.AudienceUris)); } return(saml2Assertion); }
private static IEnumerable <Claim> ClaimsFromSubject(Saml2Subject subject, Saml2NameIdentifier issuer) { if (subject == null) { yield break; } if (subject.NameId != null) { yield return(new Claim("sub", subject.NameId.Value, ClaimValueTypes.String, issuer.Value)); // openid connect yield return(new Claim(ClaimTypes.NameIdentifier, subject.NameId.Value, ClaimValueTypes.String, issuer.Value)); // saml } }
/// <summary> /// Writes out the subject as an XElement. /// </summary> /// <param name="subject">The subject to create xml for.</param> /// <returns>XElement</returns> public static XElement ToXElement(this Saml2Subject subject) { if (subject == null) { throw new ArgumentNullException(nameof(subject)); } return(new XElement(Saml2Namespaces.Saml2 + "Subject", subject.NameId.ToXElement(), new XElement(Saml2Namespaces.Saml2 + "SubjectConfirmation", new XAttribute("Method", "urn:oasis:names:tc:SAML:2.0:cm:bearer")) )); }
public void Saml2SubjectExtensions_ToXElement() { var subjectName = "JohnDoe"; var saml2Subject = new Saml2Subject(new Saml2NameIdentifier(subjectName)); var subject = saml2Subject.ToXElement(); subject.Element(Saml2Namespaces.Saml2 + "NameID").Value.Should().Be(subjectName); // Although SubjectConfirmation is optional in the SAML core spec, it is // mandatory in the Web Browser SSO Profile and must have a value of bearer. subject.Element(Saml2Namespaces.Saml2 + "SubjectConfirmation") .Attribute("Method").Value.Should().Be("urn:oasis:names:tc:SAML:2.0:cm:bearer"); }
private static Saml2Assertion CreateAssertion(SigningCredentials samlpTokenSigningCredentials) { var assertion = new Saml2Assertion(new Saml2NameIdentifier("https://mojeid.regtest.nic.cz/saml/idp.xml", new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:entity"))) { InclusiveNamespacesPrefixList = "ns1 ns2", IssueInstant = DateTime.Parse("2019-04-08T10:30:49Z"), SigningCredentials = samlpTokenSigningCredentials, Id = new Saml2Id("id-2bMsOPOKIqeVIDLqJ") }; var saml2SubjectConfirmationData = new Saml2SubjectConfirmationData { InResponseTo = new Saml2Id("ida5714d006fcc430c92aacf34ab30b166"), NotOnOrAfter = DateTime.Parse("2019-04-08T10:45:49Z"), Recipient = new Uri("https://tnia.eidentita.cz/fpsts/processRequest.aspx") }; var saml2SubjectConfirmation = new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"), saml2SubjectConfirmationData); var saml2Subject = new Saml2Subject(new Saml2NameIdentifier("6dfe0399103d11411b1fa00772b6a13e0858605b80c20ea845769c57b41479ed", new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"))); saml2Subject.SubjectConfirmations.Add(saml2SubjectConfirmation); assertion.Subject = saml2Subject; var saml2AudienceRestrictions = new Saml2AudienceRestriction("urn:microsoft: cgg2010: fpsts"); var saml2Conditions = new Saml2Conditions(); saml2Conditions.AudienceRestrictions.Add(saml2AudienceRestrictions); saml2Conditions.NotBefore = DateTime.Parse("2019-04-08T10:30:49Z"); saml2Conditions.NotOnOrAfter = DateTime.Parse("2019-04-08T10:45:49Z"); assertion.Conditions = saml2Conditions; var saml2AuthenticationContext = new Saml2AuthenticationContext(new Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport")); var saml2Statement = new Saml2AuthenticationStatement(saml2AuthenticationContext) { AuthenticationInstant = DateTime.Parse("2019-04-08T10:30:49Z"), SessionIndex = "id-oTnhrqWtcTTEntvMy" }; assertion.Statements.Add(saml2Statement); return(assertion); }
public XElement BuildRequest() { var x = new XElement(Saml2Namespaces.Saml2P + LocalName); x.Add(base.ToXNodes()); // Set issuer. x.SetElementValue(Saml2Namespaces.Saml2 + "Issuer", Issuer.Id); // End of setting issuer. // Setting name Identifier. Saml2Subject subject = (Saml2Subject)HttpContext.Current.Session["Saml2Subject"]; XElement nameID = new XElement(Saml2Namespaces.Saml2 + "NameID", subject.NameId.Value); nameID.Add(new XAttribute("Format", subject.NameId.Format)); x.Add(nameID); // End of setting name Identifier. x.SetElementValue(Saml2Namespaces.Saml2P + "SessionIndex", HttpContext.Current.Session["SessionIndex"]); return(x); }
internal ReadOnlyCollection <SecurityKey> ResolveSecurityKeys(Saml2Assertion assertion, SecurityTokenResolver resolver) { Saml2Subject subject = assertion.Subject; Saml2SubjectConfirmation confirmation = subject.SubjectConfirmations[0]; if (confirmation.SubjectConfirmationData != null) { this.ValidateConfirmationData(confirmation.SubjectConfirmationData); } List <SecurityKey> list = new List <SecurityKey>(); foreach (SecurityKeyIdentifier identifier in confirmation.SubjectConfirmationData.KeyIdentifiers) { SecurityKey key = null; foreach (SecurityKeyIdentifierClause clause in identifier) { if ((resolver != null) && resolver.TryResolveSecurityKey(clause, out key)) { list.Add(key); break; } } if (key == null) { if (identifier.CanCreateKey) { key = identifier.CreateKey(); list.Add(key); continue; } list.Add(new SecurityKeyElement(identifier, resolver)); } } return(list.AsReadOnly()); }
public static Saml2SecurityToken CreateSaml2Token(string issuedBy, string subject, Dictionary <string, string> claimValues, string certThumbPrint) { Trace.TraceInformation("Entering CreateSaml2Token with issuedBy '{0}', subject '{1}', and thumbprint '{2}'", issuedBy, subject, certThumbPrint); Saml2Assertion assertion = new Saml2Assertion(new Saml2NameIdentifier(issuedBy)); assertion.Id = new Saml2Id(string.Format("icfi_{0}", Guid.NewGuid().ToString())); //assertion.Issuer = new Saml2NameIdentifier(issuedBy); Saml2Subject subj = new Saml2Subject(); subj.NameId = new Saml2NameIdentifier(subject); assertion.Subject = subj; Saml2AttributeStatement samlAttrStatement = new Saml2AttributeStatement(); foreach (string claimKey in claimValues.Keys) { samlAttrStatement.Attributes.Add(new Saml2Attribute(claimKey, claimValues[claimKey])); } assertion.Statements.Add(samlAttrStatement); X509Certificate2 cert = GetCertificate(certThumbPrint); X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert); assertion.SigningCredentials = new SigningCredentials( signingKey, cert.PublicKey.Key.SignatureAlgorithm, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert))); Saml2SecurityToken samlToken = new Saml2SecurityToken(assertion); return(samlToken); }
public void ProcessSamlSubjectPublic(Saml2Subject assertionSubject, ClaimsIdentity subject, string issuer) { base.ProcessSamlSubject(assertionSubject, subject, issuer); }
private async Task <Saml2SecurityToken> CreateSecurityTokenAsync(SignInRequest request, RelyingParty rp, ClaimsIdentity outgoingSubject) { var now = DateTime.Now; var outgoingNameId = outgoingSubject.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (outgoingNameId == null) { _logger.LogError("The user profile does not have a name id"); throw new SignInException("The user profile does not have a name id"); } var issuer = new Saml2NameIdentifier(_options.IssuerName); var nameId = new Saml2NameIdentifier(outgoingNameId.Value); var subjectConfirmationData = new Saml2SubjectConfirmationData(); subjectConfirmationData.NotOnOrAfter = now.AddMinutes( rp.TokenLifetimeInMinutes.GetValueOrDefault(_options.DefaultNotOnOrAfterInMinutes)); if (request.Parameters.ContainsKey("Recipient")) { subjectConfirmationData.Recipient = new Uri(request.Parameters["Recipient"]); } else { subjectConfirmationData.Recipient = new Uri(rp.ReplyUrl); } var subjectConfirmation = new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"), subjectConfirmationData); subjectConfirmation.NameIdentifier = nameId; var subject = new Saml2Subject(subjectConfirmation); var conditions = new Saml2Conditions(new Saml2AudienceRestriction[] { new Saml2AudienceRestriction(request.Realm) }); conditions.NotOnOrAfter = now.AddMinutes( rp.TokenLifetimeInMinutes.GetValueOrDefault(_options.DefaultNotOnOrAfterInMinutes)); conditions.NotBefore = now.Subtract(TimeSpan.FromMinutes(_options.DefaultNotBeforeInMinutes)); var authContext = new Saml2AuthenticationContext(new Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport")); var authStatement = new Saml2AuthenticationStatement(authContext, now); authStatement.SessionIndex = (request.Parameters.ContainsKey("SessionIndex")) ? request.Parameters["SessionIndex"] : null; var attributeStament = new Saml2AttributeStatement(); foreach (var claim in outgoingSubject.Claims) { _logger.LogDebug("Adding attribute in SAML token '{0} - {1}'", claim.Type, claim.Value); attributeStament.Attributes.Add(new Saml2Attribute(claim.Type, claim.Value)); } var assertion = new Saml2Assertion(issuer); assertion.Id = new Saml2Id(); assertion.Subject = subject; assertion.Conditions = conditions; assertion.Statements.Add(attributeStament); assertion.Statements.Add(authStatement); assertion.IssueInstant = now; assertion.SigningCredentials = await _keyService.GetSigningCredentialsAsync(); var token = new Saml2SecurityToken(assertion); token.SigningKey = assertion.SigningCredentials.Key; return(token); }