private string GetDecryptedSamlToken() { var encryptedSamlToken = GetSamlTokenXml(); var decryptedSamlToken = ""; using (var reader = new StringReader(encryptedSamlToken)) { using (var xmlReader = XmlReader.Create(reader)) { var samlHandler = new Saml2SecurityTokenHandler { Configuration = new SecurityTokenHandlerConfiguration { ServiceTokenResolver = new X509CertificateStoreTokenResolver() } }; var token = samlHandler.ReadToken(xmlReader); using (var writer = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(writer)) { samlHandler.WriteToken(xmlWriter, token); } decryptedSamlToken = writer.GetStringBuilder().ToString(); } } } return(decryptedSamlToken); }
public void LoginAction(AbstractEndpointHandler handler, HttpContext context, Saml20Assertion assertion) { if (handler == null) { Logging.Instance.Error("SamlPrincipalAction - LogOnAction handler is null"); throw new ArgumentNullException("handler"); } if (context == null) { Logging.Instance.Error("SamlPrincipalAction - LogOnAction context is null"); throw new ArgumentNullException("context"); } if (assertion == null) { Logging.Instance.Error("SamlPrincipalAction - LogOnAction assertion is null"); throw new ArgumentNullException("assertion"); } Saml2SecurityTokenHandler securityTokenHandler = this.sessionAuthModule.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[ typeof(Saml2SecurityToken)] as Saml2SecurityTokenHandler; //Generate bootstraptoken from assertion xml if (securityTokenHandler != null) { var assertionXml = assertion.XmlAssertion; using (System.IO.StringReader reader = new System.IO.StringReader(assertionXml.OuterXml)) { XmlReader xReader = XmlReader.Create(reader); var bootstraptoken = securityTokenHandler.ReadToken(xReader); HttpContext.Current.Session["boostraptoken"] = bootstraptoken; } } BuildClaimsPrincipal(assertion); }
public static Saml2SecurityToken CreateSaml2SecurityTokenSigningByRsa(byte[] certificate, string password, params Claim[] claims) { var descriptor = new SecurityTokenDescriptor(); var digestAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1"; var signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; var signingCert = new X509Certificate2(certificate, password); var rsa = signingCert.PrivateKey as RSACryptoServiceProvider; var rsaKey = new RsaSecurityKey(rsa); var rsaClause = new RsaKeyIdentifierClause(rsa); var signingSki = new SecurityKeyIdentifier(rsaClause); var signingCredentials = new SigningCredentials(rsaKey, signatureAlgorithm, digestAlgorithm, signingSki); descriptor.TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"; descriptor.TokenIssuerName = "CN=app.nhin-hv.com, OU=Domain Control Validated, O=app.nhin-hv.com"; descriptor.SigningCredentials = signingCredentials; descriptor.Subject = new ClaimsIdentity(claims); descriptor.AppliesToAddress = "http://localhost/RelyingPartyApplication"; var issueInstant = DateTime.UtcNow; descriptor.Lifetime = new Lifetime(issueInstant, issueInstant + TimeSpan.FromHours(8)); var tokenHandler = new Saml2SecurityTokenHandler(); var token = tokenHandler.CreateToken(descriptor) as Saml2SecurityToken; return(token); }
void IMutateOutgoingTransportMessages.MutateOutgoing(object[] messages, TransportMessage transportMessage) { if (transportMessage.Headers.ContainsKey(SecurityTokenKey)) { transportMessage.Headers.Remove(SecurityTokenKey); } var claimsPrincipal = Thread.CurrentPrincipal as IClaimsPrincipal; if (claimsPrincipal == null) { return; } var bootstrapToken = claimsPrincipal.Identities[0].BootstrapToken; if (bootstrapToken == null) { return; } var handler = new Saml2SecurityTokenHandler(new SamlSecurityTokenRequirement()); var stringBuilder = new StringBuilder(); using (var writer = XmlWriter.Create(stringBuilder)) { handler.WriteToken(writer, bootstrapToken); } var serializedToken = stringBuilder.ToString(); transportMessage.Headers.Add(SecurityTokenKey, serializedToken); }
protected override SecurityToken GetTokenCore(TimeSpan timeout) { SecurityToken securityToken; Saml2Assertion saml2Assertion; if (base.TokenRequirement.KeyType == SecurityKeyType.SymmetricKey) { securityToken = SamlSecurityTokenProvider.CreateSymmetricProofToken(base.TokenRequirement.KeySize); saml2Assertion = this.CreateSamlAssertionWithSymmetricKey((BinarySecretSecurityToken)securityToken); } else { if (base.TokenRequirement.KeyType != SecurityKeyType.AsymmetricKey) { throw new ArgumentOutOfRangeException("KeyType"); } securityToken = SamlSecurityTokenProvider.CreateAsymmetricProofToken(); saml2Assertion = this.CreateSamlAssertionWithAsymmetricKey(securityToken); } Saml2SecurityToken saml2SecurityToken = new Saml2SecurityToken(saml2Assertion); XmlDocument xmlDocument = new XmlDocument(); using (XmlWriter xmlWriter = xmlDocument.CreateNavigator().AppendChild()) { Saml2SecurityTokenHandler saml2SecurityTokenHandler = new Saml2SecurityTokenHandler(); saml2SecurityTokenHandler.WriteToken(xmlWriter, saml2SecurityToken); } SamlAssertionKeyIdentifierClause samlAssertionKeyIdentifierClause = saml2SecurityToken.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>(); return(new GenericXmlSecurityToken(xmlDocument.DocumentElement, securityToken, saml2Assertion.Conditions.NotBefore.Value, saml2Assertion.Conditions.NotOnOrAfter.Value, samlAssertionKeyIdentifierClause, samlAssertionKeyIdentifierClause, null)); }
private void OutputToken(Saml2SecurityTokenHandler handler, Saml2SecurityToken token) { Assert.NotNull(token); _output.WriteLine("SAML assertion:"); if (token == null) { _output.WriteLine("null"); return; } using (var inner = new StringWriter()) { var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, NewLineOnAttributes = false, Encoding = new UTF8Encoding(false) }; using (var writer = XmlWriter.Create(inner, settings)) { handler.WriteToken(writer, token); } _output.WriteLine(inner.ToString()); } }
static bool ValidateSamlToken(string token) { var tokenHandler = new Saml2SecurityTokenHandler(); string keyPrivate = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "key.public.json")); var keyParameter = JsonConvert.DeserializeObject <RSAParameters>(keyPrivate); var rsaSecurityKey = new RsaSecurityKey(keyParameter); var tokenValidateParameter = new TokenValidationParameters { ValidIssuer = "xcode.me", ValidAudience = "aspnetcoreweb", IssuerSigningKey = rsaSecurityKey }; ClaimsPrincipal principal = null; try { principal = tokenHandler.ValidateToken(token, tokenValidateParameter, out SecurityToken validatedToken); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(principal != null && principal.Identity.IsAuthenticated); }
private static SecurityToken GetBootstrapToken() { string rawToken = Saml20Identity.Current["urn:liberty:disco:2006-08:DiscoveryEPR"][0].AttributeValue[0]; byte[] raw = Convert.FromBase64String(rawToken); using (var memoryStream = new MemoryStream(raw)) { string content; using (StreamReader reader = new StreamReader(memoryStream, Encoding.Unicode)) { content = reader.ReadToEnd(); } } SecurityToken bootstrapToken; using (var memoryStream = new MemoryStream(raw)) { using (var streamReader = new StreamReader(memoryStream)) { using (var xmlTextReader = new XmlTextReader(streamReader)) { SecurityTokenHandler handler = new Saml2SecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); bootstrapToken = handler.ReadToken(xmlTextReader); } } } return(bootstrapToken); }
public void GetSets() { Saml2SecurityTokenHandler samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX10101")); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected); }
static void TransportTransportMessageReceived(object sender, TransportMessageReceivedEventArgs e) { if (!ConfigureClaimFlow.Flow) { return; } if (!e.Message.Headers.ContainsKey(SecurityTokenKey)) { return; } var serializedToken = e.Message.Headers[SecurityTokenKey]; var certificate = ExtractCertificate(serializedToken); var handler = new Saml2SecurityTokenHandler(new SamlSecurityTokenRequirement()); var tokens = new List <SecurityToken> { new X509SecurityToken(certificate) }; var resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false); handler.Configuration = new SecurityTokenHandlerConfiguration { IssuerTokenResolver = resolver, IssuerNameRegistry = new InternalIssuerNameRegistry(), CertificateValidator = X509CertificateValidator.None }; using (var reader = XmlReader.Create(new StringReader(serializedToken))) { var bootstrapToken = handler.ReadToken(reader); handler.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never; handler.Configuration.MaxClockSkew = TimeSpan.MaxValue; var collection = handler.ValidateToken(bootstrapToken); Thread.CurrentPrincipal = new ClaimsPrincipal(collection); } }
static void TokenDemo() { Saml2SecurityTokenHandler h = new Saml2SecurityTokenHandler(); var token = h.CreateToken(new SecurityTokenDescriptor()); System.Console.WriteLine(token); }
public void GetTokenTest(WsFederationMessageTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.GetTokenTest", theoryData); try { // GetToken (for other than NETSTANDARD 1.4) uses XmlReaders to obtain token from Wresult. // GetToken(string) {internal} uses string manipulation to obtain token. // The result should be the same token. var tokenUsingReader = theoryData.WsFederationMessageTestSet.WsFederationMessage.GetToken(); var tokenFromString = WsFederationMessage.GetToken(theoryData.WsFederationMessageTestSet.WsFederationMessage.Wresult); if (string.Compare(tokenUsingReader, tokenFromString) != 0) { context.AddDiff("string.Compare(tokenUsingReader, tokenFromString) != 0"); } if (theoryData.TokenValidationParameters != null) { var tokenHandler = new Saml2SecurityTokenHandler(); tokenHandler.ValidateToken(tokenUsingReader, theoryData.TokenValidationParameters, out SecurityToken validatedToken); } theoryData.ExpectedException.ProcessNoException(context); } catch (Exception ex) { theoryData.ExpectedException.ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
public void GetSets() { var samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); var context = new GetSetContext { PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > > { new KeyValuePair <string, List <object> >("MaximumTokenSizeInBytes", new List <object> { (object)TokenValidationParameters.DefaultMaximumTokenSizeInBytes, (object)1000, (object)10 }), new KeyValuePair <string, List <object> >("SetDefaultTimesOnTokenCreation", new List <object> { true, false, true }), new KeyValuePair <string, List <object> >("TokenLifetimeInMinutes", new List <object> { (object)60, (object)1000, (object)10 }), }, Object = samlSecurityTokenHandler }; TestUtilities.GetSet(context); samlSecurityTokenHandler = new Saml2SecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException("IDX10101:"), context); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected, context); TestUtilities.SetGet(samlSecurityTokenHandler, "Serializer", null, ExpectedException.ArgumentNullException(), context); TestUtilities.AssertFailIfErrors("Saml2SecurityTokenHandlerTests_GetSets", context.Errors); }
public ActionResult <bool> Validate([FromHeader] string token) { var tokenHandler = new Saml2SecurityTokenHandler(); var publicKey = System.IO.File.ReadAllText(Path.Combine(_env.ContentRootPath, "public.key")); var rsaParameters = JsonConvert.DeserializeObject <RSAParameters>(publicKey); var rsaSecurityKey = new RsaSecurityKey(rsaParameters); var tokenValidationParameters = new TokenValidationParameters { ValidIssuer = "https://www.jjj.me", ValidAudience = "https://api.jjj.me", IssuerSigningKey = rsaSecurityKey }; ClaimsPrincipal retVal = null; try { retVal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken validatedToken); } catch (Exception ex) { Console.WriteLine(ex); } return(retVal != null && retVal.Identity.IsAuthenticated); }
static GenericXmlSecurityToken WrapJwt(string jwt) { var subject = new ClaimsIdentity("saml"); subject.AddClaim(new Claim("jwt", jwt)); var descriptor = new SecurityTokenDescriptor { TokenType = TokenTypes.Saml2TokenProfile11, TokenIssuerName = "urn:wrappedjwt", Subject = subject }; var handler = new Saml2SecurityTokenHandler(); var token = handler.CreateToken(descriptor); var xmlToken = new GenericXmlSecurityToken( XElement.Parse(token.ToTokenXmlString()).ToXmlElement(), null, DateTime.Now, DateTime.Now.AddHours(1), null, null, null); return(xmlToken); }
public async Task <string> GenerateSerializedRstr(ValidatedWsFederationSigninRequest request) { var now = _clock.UtcNow.UtcDateTime; var principal = request.Subject.Identity as ClaimsIdentity; var nameIdClaim = principal.FindFirst(ClaimTypes.NameIdentifier); if (nameIdClaim == null) { nameIdClaim = new Claim(ClaimTypes.NameIdentifier, principal.Name); nameIdClaim.Properties.Add(ClaimProperties.SamlNameIdentifierFormat, Saml2Constants.NameIdentifierFormats.UnspecifiedString); principal.AddClaim(nameIdClaim); } var tokenDescriptor = new SecurityTokenDescriptor { Audience = request.RequestMessage.Wtrealm, Expires = now.AddSeconds(request.Client.IdentityTokenLifetime), IssuedAt = now, Issuer = _options.IssuerUri, NotBefore = now, SigningCredentials = await _keys.GetSigningCredentialsAsync(), Subject = principal }; //For whatever reason, the Digest method isn't specified in the builder extensions for identity server. //Not a good solution to force the user to use th eoverload that takes SigningCredentials //IdentityServer4/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs //Instead, it should be supported in: // The overload that takes a X509Certificate2 // The overload that looks it up in a cert store // The overload that takes an RsaSecurityKey // AddDeveloperSigningCredential //For now, this is a workaround. if (tokenDescriptor.SigningCredentials.Digest == null) { _logger.LogInformation($"SigningCredentials does not have a digest specified. Using default digest algorithm of {SecurityAlgorithms.Sha256Digest}"); tokenDescriptor.SigningCredentials = new SigningCredentials(tokenDescriptor.SigningCredentials.Key, tokenDescriptor.SigningCredentials.Algorithm, SecurityAlgorithms.Sha256Digest); } _logger.LogDebug("Creating SAML 2.0 security token."); var tokenHandler = new Saml2SecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); _logger.LogDebug("Serializing RSTR."); var rstr = new RequestSecurityTokenResponse { AppliesTo = new AppliesTo(request.RequestMessage.Wtrealm), KeyType = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey", Lifetime = new Lifetime(now, now.AddSeconds(request.Client.IdentityTokenLifetime)), RequestedSecurityToken = token, RequestType = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue", TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" }; return(RequestSecurityTokenResponseSerializer.Serialize(rstr)); }
private void CreateSaml2Tokens(SecurityTokenDescriptor tokenDescriptor) { Saml2SecurityTokenHandler samlTokenHandler = new Saml2SecurityTokenHandler(); Saml2SecurityToken token = samlTokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken; MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms); samlTokenHandler.WriteToken(writer, token); }
static async Task Main(string[] args) { IdentityModelEventSource.ShowPII = true; await Task.Delay(5000); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), new Claim(ClaimTypes.Name, "username") }; var identity = new ClaimsIdentity(claims, "Sample"); var handler = new Saml2SecurityTokenHandler(); var parameters = CreateRsaParameters(); using var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(parameters); var descriptor = new SecurityTokenDescriptor { Issuer = "urn:sample.identityprovider", Audience = "urn:sample.issuer", IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow.AddMinutes(-5), Expires = DateTime.UtcNow.AddHours(2), Subject = identity, SigningCredentials = SignatureMethod.RsaSha256.CreateCredentials(new RsaSecurityKey(rsa)) }; var token = handler.CreateToken(descriptor); var binding = new WsTrustIssuedTokenBinding(); var endpoint = new EndpointAddress("https://localhost:5001/trust/13"); var factory = new WsTrustChannelFactory(binding, endpoint); factory.SecurityTokenHandlers.Add(handler); for (var i = 0; i < iterations; i++) { var channel = factory.CreateChannelWithIssuedToken(token); var request = new WsTrustRequest(WsTrustConstants.Trust13.WsTrustActions.Issue) { KeyType = WsTrustKeyTypes.Trust13.Bearer, AppliesTo = new AppliesTo(new EndpointReference("urn:sample:relyingparty")) }; var response = await channel.IssueAsync(request); var requestedToken = response.GetRequestedSecurityToken() as GenericXmlSecurityToken; var assertion = requestedToken.Element.OuterXml; Console.WriteLine(assertion); } Console.ReadKey(); }
public async Task <string> GenerateSerializedRstr(ValidatedWsFederationRequest request) { var now = _clock.UtcNow.UtcDateTime; var credential = await _keys.GetSigningCredentialsAsync(); var key = credential.Key as X509SecurityKey; var tokenDescriptor = new SecurityTokenDescriptor { Audience = request.RequestMessage.Wtrealm, Expires = now.AddSeconds(request.Client.IdentityTokenLifetime), IssuedAt = now, Issuer = _options.IssuerUri, NotBefore = now, SigningCredentials = key == null ? credential : new X509SigningCredentials(key.Certificate, _federationOptions.DefaultSignatureAlgorithm), Subject = await CreateSubjectAsync(request) }; //For whatever reason, the Digest method isn't specified in the builder extensions for identity server. //Not a good solution to force the user to use the overload that takes SigningCredentials //IdentityServer4/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs //Instead, it should be supported in: // The overload that takes a X509Certificate2 // The overload that looks it up in a cert store // The overload that takes an RsaSecurityKey // AddDeveloperSigningCredential //For now, this is a workaround. if (tokenDescriptor.SigningCredentials.Digest == null) { _logger.LogInformation($"SigningCredentials does not have a digest specified. Using default digest algorithm of {SecurityAlgorithms.Sha256Digest}"); tokenDescriptor.SigningCredentials = new SigningCredentials(tokenDescriptor.SigningCredentials.Key, tokenDescriptor.SigningCredentials.Algorithm ?? _federationOptions.DefaultSignatureAlgorithm, _federationOptions.DefaultDigestAlgorithm); } _logger.LogDebug("Creating SAML 2.0 security token."); var tokenHandler = new Saml2SecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); _logger.LogDebug("Serializing RSTR."); var rstr = new RequestSecurityTokenResponse { AppliesTo = new AppliesTo(request.RequestMessage.Wtrealm), KeyType = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey", Lifetime = new Lifetime { Created = XmlConvert.ToString(now, XmlDateTimeSerializationMode.Utc), Expires = XmlConvert.ToString(now.AddSeconds(request.Client.IdentityTokenLifetime), XmlDateTimeSerializationMode.Utc), }, RequestedSecurityToken = token, RequestType = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue", TokenType = WsFederationConstants.TokenTypes.Saml2TokenProfile11 }; return(RequestSecurityTokenResponseSerializer.Serialize(rstr)); }
//TODO: Handle both SAML 1.1 and SAML 2.0 private static SecurityToken DeserializeToken(string rstrString) { var doc = XDocument.Parse(rstrString); XNamespace wstrust = "http://schemas.xmlsoap.org/ws/2005/02/trust"; var requestedTokenElement = doc.Root.Element(wstrust + "RequestedSecurityToken"); XNamespace assertionNs = "urn:oasis:names:tc:SAML:2.0:assertion"; var assertion = requestedTokenElement.Element(assertionNs + "Assertion"); var handler = new Saml2SecurityTokenHandler(); return(handler.ReadSaml2Token(assertion.ToString())); }
// public static SamlSecurityToken CreateSamlSecurityToken(byte[] certificate, string password, params Claim[] claims) // { // const string acsUrl = "http://blueprintsys.com"; // var assertion = new SamlAssertion(new SamlNameIdentifier(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 static string Serialize(Saml2SecurityToken token) { var handler = new Saml2SecurityTokenHandler(); var sw = I18NHelper.CreateStringWriterInvariant(); using (var textWriter = new XmlTextWriter(sw)) { handler.WriteToken(textWriter, token); return(sw.ToString()); } }
private Saml2SecurityToken ParseToken(string token, Saml2SecurityTokenHandler samlHandler) { using (var reader = new StringReader(token)) { using (var xmlReader = XmlReader.Create(reader)) { //Parses the token, as well as decrypting it return((Saml2SecurityToken)samlHandler.ReadToken(xmlReader)); } } }
public static Saml2Assertion MakeNemIdAssertion(X509Certificate2 certificate) { var doc = Global.SignedTokenXml(); Saml2Assertion sa; using (var rd = doc.CreateReader()) { var s2sth = new Saml2SecurityTokenHandler { /*Configuration = new SecurityTokenHandlerConfiguration * { * IssuerTokenResolver = new Saml2IssuerTokenResolver() * }*/ }; var s2st = s2sth.ReadToken(rd) as Saml2SecurityToken; sa = s2st.Assertion; } var ass = new Saml2Assertion(new Saml2NameIdentifier(sa.Issuer.Value)) { Conditions = new Saml2Conditions { NotOnOrAfter = DateTime.Now + TimeSpan.FromHours(8), NotBefore = DateTime.Now }, Subject = new Saml2Subject(new Saml2NameIdentifier(certificate.SubjectName.Name)) }; ass.Subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer")) { SubjectConfirmationData = new Saml2SubjectConfirmationData { NotOnOrAfter = DateTime.Now + TimeSpan.FromHours(8), Recipient = new Uri("https://staging.fmk-online.dk/fmk/saml/SAMLAssertionConsumer") } }); var q = from att in sa.Statements.OfType <Saml2AttributeStatement>().First().Attributes select new Saml2Attribute(att.Name, att.Values.First()) { NameFormat = att.NameFormat }; ass.Statements.Add(new Saml2AttributeStatement(q)); ass.Statements.Add(new Saml2AuthenticationStatement(new Saml2AuthenticationContext(new Uri("element:urn:oasis:names:tc:SAML:2.0:ac:classes:X509")), DateTime.Now)); /*var secClause = new X509RawDataKeyIdentifierClause(certificate); * var issuerKeyIdentifier = new SecurityKeyIdentifier(secClause); * issuerKeyIdentifier.Add(secClause);*/ ass.SigningCredentials = new X509SigningCredentials(certificate); //, SignedXml.XmlDsigRSASHA1Url, SignedXml.XmlDsigSHA1Url); return(ass); }
private string GetTokenString(string organizationName, bool isServiceBusScope) { // Generate Saml assertions.. string issuerName = DefaultIssuer; //string issuerName = "localhost"; Saml2NameIdentifier saml2NameIdentifier = new Saml2NameIdentifier(issuerName); // this is the issuer name. Saml2Assertion saml2Assertion = new Saml2Assertion(saml2NameIdentifier); Uri acsScope = new Uri(StsPath(solutionName, isServiceBusScope)); saml2Assertion.Conditions = new Saml2Conditions(); saml2Assertion.Conditions .AudienceRestrictions.Add(new Saml2AudienceRestriction(acsScope)); // this is the ACS uri. saml2Assertion.Conditions.NotOnOrAfter = DateTime.Now.AddDays(1); // Should this be utc? saml2Assertion.Conditions.NotBefore = DateTime.Now.AddHours(-1); // should this be utc? string certName = "localhost"; X509Certificate2 localCert = RetrieveCertificate(certName); if (!localCert.HasPrivateKey) { throw new ArgumentException("Cert should have private key.", "certificate"); } saml2Assertion.SigningCredentials = new X509SigningCredentials(localCert); // this cert should have the private keys. // Add claim assertions. saml2Assertion.Statements.Add( new Saml2AttributeStatement( new Saml2Attribute(OrganizationClaimType, organizationName))); // the submitter should always be a bearer. saml2Assertion.Subject = new Saml2Subject(new Saml2SubjectConfirmation(Saml2Constants.ConfirmationMethods.Bearer)); // Wrap it into a security token. SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler(); SecurityToken securityToken = new Saml2SecurityToken(saml2Assertion); // Serialize the security token. StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlTextWriter.Create(new StringWriter(sb, CultureInfo.InvariantCulture))) { tokenHandler.WriteToken(writer, securityToken); writer.Close(); } return(sb.ToString()); }
private XmlElement GetKeyIdentifierClause(XmlElement samlToken) { if (samlToken == null) { throw new ArgumentNullException("samlToken"); } using (XmlDocumentWriterHelper documentWriterHelper = new XmlDocumentWriterHelper()) { // The key is located in the SAML token. The identifier is to the SAML token. XmlNode idAttribute = samlToken.Attributes.GetNamedItem("ID"); if (idAttribute == null) { throw new InvalidDataException("The SAML token does not have an ID attribute."); } string samlTokenId = idAttribute.Value; SecurityKeyIdentifierClause keyIdentifierClause = new Saml2AssertionKeyIdentifierClause(samlTokenId); Saml2SecurityTokenHandler handler = new Saml2SecurityTokenHandler(); handler.KeyInfoSerializer.WriteKeyIdentifierClause(documentWriterHelper.CreateDocumentWriter(), keyIdentifierClause); XmlDocument xmlDocument = documentWriterHelper.ReadDocument(); return(xmlDocument.DocumentElement); } }
public void ValidateToken() { // parameter validation Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler(); TestUtilities.ValidateToken(securityToken: null, validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentNullException(substringExpected: "name: securityToken")); TestUtilities.ValidateToken(securityToken: "s", validationParameters: null, tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters")); tokenHandler.MaximumTokenSizeInBytes = 1; TestUtilities.ValidateToken(securityToken: "ss", validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: ExpectedException.ArgumentException(substringExpected: "IDX10209")); tokenHandler.MaximumTokenSizeInBytes = TokenValidationParameters.DefaultMaximumTokenSizeInBytes; string samlToken = IdentityUtilities.CreateSaml2Token(); TestUtilities.ValidateToken(samlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, tokenHandler, ExpectedException.NoExceptionExpected); // EncryptedAssertion SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = IdentityUtilities.DefaultAudience, EncryptingCredentials = new EncryptedKeyEncryptingCredentials(KeyingMaterial.DefaultAsymmetricCert_2048), Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1)), SigningCredentials = KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2, Subject = IdentityUtilities.DefaultClaimsIdentity, TokenIssuerName = IdentityUtilities.DefaultIssuer, }; samlToken = IdentityUtilities.CreateSaml2Token(tokenDescriptor); TestUtilities.ValidateToken(samlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(EncryptedTokenDecryptionFailedException), substringExpected: "ID4022")); TokenValidationParameters validationParameters = IdentityUtilities.DefaultAsymmetricTokenValidationParameters; validationParameters.TokenDecryptionKeys = new List <SecurityKey> { KeyingMaterial.DefaultX509Key_2048 }.AsReadOnly(); TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); TestUtilities.ValidateTokenReplay(samlToken, tokenHandler, validationParameters); TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); validationParameters.LifetimeValidator = (nb, exp, st, tvp) => { return(false); }; TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(SecurityTokenInvalidLifetimeException), substringExpected: "IDX10230:")); validationParameters.ValidateLifetime = false; validationParameters.LifetimeValidator = IdentityUtilities.LifetimeValidatorThrows; TestUtilities.ValidateToken(securityToken: samlToken, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); }
/// <summary> /// Authenticates the specified message. /// </summary> /// <returns> /// Returns <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1"/>. /// </returns> /// <param name="authPolicy">The authorization policy.</param><param name="listenUri">The URI at which the message was received.</param><param name="message">The message to be authenticated.</param> public override ReadOnlyCollection <IAuthorizationPolicy> Authenticate(ReadOnlyCollection <IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message) { if (WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.Headers["fedAuth"] != null) { var tokenString = WebOperationContext.Current.IncomingRequest.Headers["fedAuth"]; var handler = new Saml2SecurityTokenHandler(); var token = handler.ReadToken(tokenString); var identities = handler.ValidateToken(token); var principal = new ClaimsPrincipal(identities); Thread.CurrentPrincipal = principal; } return(base.Authenticate(authPolicy, listenUri, ref message)); }
public static XmlElement SerialiseToken(Saml2SecurityToken token) { var handler = new Saml2SecurityTokenHandler(); var sb = new StringBuilder(); using (var writer = XmlWriter.Create(sb)) { handler.WriteToken(writer, token); writer.Flush(); var document = new XmlDocument(); document.LoadXml(sb.ToString()); return(document.DocumentElement); } }
public FinishSsoEndpointMiddleware( Saml2SecurityTokenHandler handler, TokenValidationParametersFactory parametersFactory, ISystemClock clock, Saml2pSerializer serializer, Saml2pCache cache, Saml2pPartnerProvider partners, Saml2pEncodingService encoder, IOptionsMonitor <Saml2pOptions> monitor, ILoggerFactory factory, RequestDelegate _) : this(handler, parametersFactory, clock, serializer, cache, partners, encoder, monitor, factory) { }
public void GeneratedTokenHasNameId() { var generator = GetDefaultResponseGenerator(); var request = GetDefaultValidatedRequest(); var response = generator.GenerateSerializedRstr(request).Result; var tokenString = GetTokenString(response); var handler = new Saml2SecurityTokenHandler(); var token = handler.ReadSaml2Token(tokenString); var nameId = token.Assertion.Subject.NameId; Assert.AreEqual("bob", nameId.Value); Assert.AreEqual(Saml2Constants.NameIdentifierFormats.UnspecifiedString, nameId.Format.AbsoluteUri); }
public static string CreateSaml2Token(string name) { var id = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "SAML"); var descriptor = new SecurityTokenDescriptor { Subject = id, AppliesToAddress = "https://test", TokenIssuerName = "http://issuer", SigningCredentials = GetSamlSigningCredential(), }; var handler = new Saml2SecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); var token = handler.CreateToken(descriptor); return token.ToTokenXmlString(); }
void IMutateOutgoingTransportMessages.MutateOutgoing(object[] messages, TransportMessage transportMessage) { if (transportMessage.Headers.ContainsKey(SecurityTokenKey)) transportMessage.Headers.Remove(SecurityTokenKey); var claimsPrincipal = Thread.CurrentPrincipal as IClaimsPrincipal; if (claimsPrincipal == null) return; var bootstrapToken = claimsPrincipal.Identities[0].BootstrapToken; var handler = new Saml2SecurityTokenHandler(new SamlSecurityTokenRequirement()); var stringBuilder = new StringBuilder(); using (var writer = XmlWriter.Create(stringBuilder)) { handler.WriteToken(writer, bootstrapToken); } var serializedToken = stringBuilder.ToString(); transportMessage.Headers.Add(SecurityTokenKey, serializedToken); }
static void TransportTransportMessageReceived(object sender, TransportMessageReceivedEventArgs e) { if (!ConfigureClaimFlow.Flow) return; if (!e.Message.Headers.ContainsKey(SecurityTokenKey)) return; var serializedToken = e.Message.Headers[SecurityTokenKey]; var certificate = ExtractCertificate(serializedToken); var handler = new Saml2SecurityTokenHandler(new SamlSecurityTokenRequirement()); var tokens = new List<SecurityToken> {new X509SecurityToken(certificate)}; var resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false); handler.Configuration = new SecurityTokenHandlerConfiguration { IssuerTokenResolver = resolver, IssuerNameRegistry = new InternalIssuerNameRegistry(), CertificateValidator = X509CertificateValidator.None }; using (var reader = XmlReader.Create(new StringReader(serializedToken))) { var bootstrapToken = handler.ReadToken(reader); handler.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never; handler.Configuration.MaxClockSkew = TimeSpan.MaxValue; var collection = handler.ValidateToken(bootstrapToken); Thread.CurrentPrincipal = new ClaimsPrincipal(collection); } }