/// <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)); }
public void ClaimsIdentityExtensions_ToSaml2Assertion_MultipleValuesForSameKey_CombinesTo_OneAttribute() { var ci = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "JohnDoe"), new Claim(ClaimTypes.Role, "Test1"), new Claim(ClaimTypes.Role, "Test2"), }); var assertion = ci.ToSaml2Assertion(new EntityId("http://idp.example.com")); assertion.Statements.OfType <Saml2AttributeStatement>().Should().HaveCount(1); var actual = assertion.Statements.OfType <Saml2AttributeStatement>().Single(); var expected = new Saml2AttributeStatement( new Saml2Attribute(ClaimTypes.Role, new[] { "Test1", "Test2" })); actual.ShouldBeEquivalentTo(expected); }
private static Saml2Assertion CreateSamlAssertionsForTokenRequest(string requestId, SSOLoginData ssoLoginData) { if (!File.Exists(certPath)) { throw new Exception($"Unable to find Certificate. Path: {certPath}"); } var assertion = new Saml2Assertion(new Saml2NameIdentifier("SSO")); assertion.Subject = new Saml2Subject(new Saml2NameIdentifier($"SalesRadixAuthenticationRequest : {requestId}")); assertion.Conditions = new Saml2Conditions() { NotBefore = DateTime.Now.AddSeconds(-30), NotOnOrAfter = DateTime.Now.AddSeconds(30), }; var statement = new Saml2AttributeStatement(); AddAttributeToStatement("FirstName", ssoLoginData.FirstName, statement); AddAttributeToStatement("LastName", ssoLoginData.LastName, statement); AddAttributeToStatement("Email", ssoLoginData.Email, statement); //AddAttributeToStatement("AdditionalEmail1", ssoLoginData.AdditionalEmail1, statement); //AddAttributeToStatement("AdditionalEmail2", ssoLoginData.AdditionalEmail2, statement); //AddAttributeToStatement("RoleId", ssoLoginData.RoleId.ToString(), statement); //AddAttributeToStatement("GlobalUserId", ssoLoginData.GlobalUserId.ToString(), statement); //AddAttributeToStatement("ManagerGlobalId", ssoLoginData.ManagerGlobalUserId.ToString(), statement); assertion.Statements.Add(statement); var x509 = new X509Certificate2(); x509.Import(certPath, certPwd, X509KeyStorageFlags.MachineKeySet); var clientSigningCreds = new X509SigningCredentials(x509); assertion.SigningCredentials = clientSigningCreds; return(assertion); }
private static XElement ToXElement(Saml2AttributeStatement attributeStatement) { var element = new XElement(Saml2Namespaces.Saml2 + "AttributeStatement"); foreach (var attribute in attributeStatement.Attributes) { var attributeElement = new XElement(Saml2Namespaces.Saml2 + "Attribute", new XAttribute("Name", attribute.Name)); attributeElement.AddAttributeIfNotNullOrEmpty("FriendlyName", attribute.FriendlyName); attributeElement.AddAttributeIfNotNullOrEmpty("NameFormat", attribute.NameFormat); attributeElement.AddAttributeIfNotNullOrEmpty("OriginalIssuer", attribute.OriginalIssuer); foreach (var value in attribute.Values) { attributeElement.Add(new XElement(Saml2Namespaces.Saml2 + "AttributeValue", value)); } element.Add(attributeElement); } return(element); }
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 ProcessAttributeStatementPublic(Saml2AttributeStatement statement, ClaimsIdentity identity, string issuer) { ProcessAttributeStatement(statement, identity, issuer); }
private void AddIdCardAsBootstrapToken(XElement assertion) { var attributeStatementElm = assertion.Element(SamlTags.AttributeStatement.Ns + SamlTags.AttributeStatement.TagName); var attributeElm = XmlUtil.CreateElement(SamlTags.Attribute); attributeElm.Add(new XAttribute(SamlAttributes.Name, OioSamlAttributes.DiscoveryEpr)); attributeStatementElm.Add(attributeElm); var attributeValue = XmlUtil.CreateElement(SamlTags.AttributeValue); attributeElm.Add(attributeValue); var endpointReferenceElm = XmlUtil.CreateElement(WsaTags.EndpointReference); attributeValue.Add(endpointReferenceElm); var addressElm = XmlUtil.CreateElement(WsaTags.Address); addressElm.Value = LibertyValues.SosiSTSUri; endpointReferenceElm.Add(addressElm); var metadataElm = XmlUtil.CreateElement(WsaTags.Metadata); endpointReferenceElm.Add(metadataElm); var abstractElm = XmlUtil.CreateElement(LibertyDiscoveryTags.Abstract); abstractElm.Value = "A SOSI idcard"; metadataElm.Add(abstractElm); var serviceTypeElm = XmlUtil.CreateElement(LibertyDiscoveryTags.ServiceType); serviceTypeElm.Value = LibertyValues.SosiUrn; metadataElm.Add(serviceTypeElm); var providerIDElm = XmlUtil.CreateElement(LibertyDiscoveryTags.ProviderId); providerIDElm.Value = LibertyValues.SosiSTSUri; metadataElm.Add(providerIDElm); var securityContextElm = XmlUtil.CreateElement(LibertyDiscoveryTags.SecurityContext); metadataElm.Add(securityContextElm); var securityMechID = XmlUtil.CreateElement(LibertyDiscoveryTags.SecurityMechID); securityMechID.Value = LibertyValues.SamlSecurityMechId; securityContextElm.Add(securityMechID); var tokenElm = XmlUtil.CreateElement(LibertySecurityTags.Token); tokenElm.Add(new XAttribute(LibertyAttributes.Usage, LibertyValues.TokenUsageSecurityToken)); securityContextElm.Add(tokenElm); var idCardElm = UserIdCard.Xassertion; tokenElm.Add(idCardElm); var samlAttributeStatement = new Saml2AttributeStatement(); samlAttributeStatement.Attributes.Add(new Saml2Attribute(OioSamlAttributes.DiscoveryEpr, endpointReferenceElm.ToString(SaveOptions.None)) { NameFormat = new Uri(SamlValues.NameFormatUri) }); }
private static void AddAttributeToStatement(string attrName, string attrValue, Saml2AttributeStatement statement) { var attribute = new Saml2Attribute(attrName); attribute.Values.Add(attrValue); statement.Attributes.Add(attribute); }
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); }