/// <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 GenericXmlSecurityToken Authenticate(ClaimsIdentity identity, string appliesTo) { var encryptingCert = _configuration.AdfsIntegration.EncryptionCertificate; // create new token var proof = CreateProofDescriptor(encryptingCert); var outputToken = CreateOutputSamlToken(identity, proof, encryptingCert); // turn token into a generic xml security token var outputTokenString = outputToken.ToTokenXmlString(); // create attached and unattached references var handler = new SamlSecurityTokenHandler(); var ar = handler.CreateSecurityTokenReference(outputToken, true); var uar = handler.CreateSecurityTokenReference(outputToken, false); var xmlToken = new GenericXmlSecurityToken( GetElement(outputTokenString), new BinarySecretSecurityToken(proof.GetKeyBytes()), DateTime.UtcNow, DateTime.UtcNow.AddHours(1), ar, uar, new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>())); // send to ADFS federation endpoint return(RequestFederationToken(xmlToken, appliesTo) as GenericXmlSecurityToken); }
public void GetSets() { var samlSecurityTokenHandler = new SamlSecurityTokenHandler(); 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 SamlSecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException(substringExpected: "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 async Task WsFederation_login_return_assertion_success() { var loginUrl = "/account/login?returnUrl=%2Fwsfederation%3Fwtrealm%3Durn%253Aowinrp%26wreply%3Dhttp%253A%252F%252Flocalhost%253A10313%252F%26wa%3Dwsignin1.0"; var response = await _client.GetAsync(loginUrl); Assert.Equal(HttpStatusCode.Found, response.StatusCode); var wsEndpointUrl = "/wsfederation?wtrealm=urn%3Aowinrp&wreply=http%3A%2F%2Flocalhost%3A10313%2F&wa=wsignin1.0"; Assert.Equal(wsEndpointUrl, response.Headers.Location.OriginalString); var request = GetRequest(wsEndpointUrl, response); var wsResponse = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, wsResponse.StatusCode); var contentAsText = await wsResponse.Content.ReadAsStringAsync(); Assert.Contains("action=\"http://localhost:10313/\"", contentAsText); var wreturn = ExtractInBetween(contentAsText, "wresult\" value=\"", "\""); Assert.False(wreturn.StartsWith("%EF%BB%BF")); //don't start with BOM (Byte Order Mark) var wsMessage = new WsFederationMessage { Wresult = WebUtility.HtmlDecode(wreturn), }; var tokenString = wsMessage.GetToken(); var handler = new SamlSecurityTokenHandler(); var canReadToken = handler.CanReadToken(tokenString); Assert.True(canReadToken); }
internal static SamlSecurityToken CreateSamlToken(ClaimsIdentity subject, string audience) { SecurityTokenDescriptor descriptor = TokenHelper.CreateDescriptor(subject, audience, 600); SamlSecurityTokenHandler handler = TokenHelper.GetSamlHandler(); return(handler.CreateToken(descriptor) as SamlSecurityToken); }
public void GetSets() { SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX10101")); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected); }
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); }
/// <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)); }
protected virtual SecurityTokenHandler GetSecurityTokenHandler() { var authPlugin = PluginManager.GetSingleton <SamlOAuthClient>(); //var config = System.IdentityModel.Services.Configuration..FederationConfiguration..; SecurityTokenHandler handler = null; var securityRequirements = new SamlSecurityTokenRequirement(); var securityTokenHandlerConfig = new SecurityTokenHandlerConfiguration(); switch (authPlugin.IdpBindingType) { case SamlBinding.SAML11_POST: handler = new SamlSecurityTokenHandler(securityRequirements) { Configuration = securityTokenHandlerConfig }; break; case SamlBinding.SAML20_POST: handler = new SubjectConfirmationDataSaml2SecurityTokenHandler(securityRequirements, authPlugin.SubjectRecipientValidationMode) { Configuration = securityTokenHandlerConfig }; break; } if (handler == null) { throw new InvalidOperationException( string.Format("No suitable token handler was loaded for the SAML binding type : {0}", tokenProcessorConfiguration.IdpBindingType)); } handler.Configuration.IssuerNameRegistry = new CodeBasedIssuerNameRegistry(tokenProcessorConfiguration.TrustedIssuerThumbprint.Split(',')); handler.Configuration.CertificateValidationMode = tokenProcessorConfiguration.CertificateValidationMode; if (typeof(SamlSecurityTokenHandler).IsAssignableFrom(handler.GetType())) { ((SamlSecurityTokenHandler)handler).CertificateValidator = GetCertificateValidator(handler.Configuration.CertificateValidationMode); } if (typeof(Saml2SecurityTokenHandler).IsAssignableFrom(handler.GetType())) { ((Saml2SecurityTokenHandler)handler).CertificateValidator = GetCertificateValidator(handler.Configuration.CertificateValidationMode); } handler.Configuration.AudienceRestriction.AudienceMode = System.IdentityModel.Selectors.AudienceUriMode.Never; return(handler); }
public async Task WsFederation_signin_request_with_wfresh_user_is_authenticated_wfresh_in_time_frame_return_assertion_success() { // login user var subjectId = "user1"; var loginUrl = string.Format("/account/login?subjectId={0}", WebUtility.UrlEncode(subjectId)); var loginResponse = await _client.GetAsync(loginUrl); var authTime = DateTime.UtcNow; // create ws fed sigin message with wfresh=5 var wsMessage = new WsFederationMessage { Wa = "wsignin1.0", IssuerAddress = "/wsfederation", Wtrealm = "urn:owinrp", Wreply = "http://localhost:10313/", Wfresh = "5", }; var signInUrl = wsMessage.CreateSignInUrl(); var request = new HttpRequestMessage(HttpMethod.Get, signInUrl); // test server doesnt save cookies between requests, // so we set them explicitly for the next request request.SetCookiesFromResponse(loginResponse); var response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var contentAsText = await response.Content.ReadAsStringAsync(); Assert.NotEqual(String.Empty, contentAsText); Assert.Contains("action=\"http://localhost:10313/\"", contentAsText); // extract wreturn to use it later to check if our token is a valid token var wreturn = ExtractInBetween(contentAsText, "wresult\" value=\"", "\""); var wsResponseMessage = new WsFederationMessage { Wresult = WebUtility.HtmlDecode(wreturn), }; var tokenString = wsResponseMessage.GetToken(); var handler = new SamlSecurityTokenHandler(); var canReadToken = handler.CanReadToken(tokenString); Assert.True(canReadToken); var token = handler.ReadSamlToken(tokenString); var authStatements = token.Assertion.Statements.OfType <SamlAuthenticationStatement>(); Assert.Equal(1, authStatements.Count()); var authStatement = authStatements.First(); Assert.True(authStatement.AuthenticationInstant <= authTime.AddMinutes(5)); }
public string IssueTokenAsXml(ClaimsPrincipal principal, string appliesTo) { var token = IssueToken(principal, appliesTo); var buffer = new StringBuilder(); var handler = new SamlSecurityTokenHandler { Configuration = new SecurityTokenHandlerConfiguration() }; var writer = XmlWriter.Create(new StringWriter(buffer)); handler.WriteToken(writer, token); var tokenXml = buffer.ToString(); return(tokenXml); }
public async Task WsFederation_sigin_request_for_logged_in_user_return_assertion_success() { // login user var subjectId = "user1"; var loginUrl = string.Format("/account/login?subjectId={0}", WebUtility.UrlEncode(subjectId)); var loginResponse = await _client.GetAsync(loginUrl); Assert.Equal(HttpStatusCode.OK, loginResponse.StatusCode); // create ws fed sign in message var wsSignInMessage = new WsFederationMessage { Wa = "wsignin1.0", IssuerAddress = "/wsfederation", Wtrealm = "urn:owinrp", Wreply = "http://localhost:10313/", }; var signInUrl = wsSignInMessage.CreateSignInUrl(); var request = new HttpRequestMessage(HttpMethod.Get, signInUrl); // test server doesnt save cookies between requests, // so we set them explicitly for the next request request.SetCookiesFromResponse(loginResponse); // send ws fed sign in request var wsResponse = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, wsResponse.StatusCode); var contentAsText = await wsResponse.Content.ReadAsStringAsync(); Assert.NotEqual(String.Empty, contentAsText); Assert.Contains("action=\"http://localhost:10313/\"", contentAsText); // extract wreturn to use it later to check if our token is a valid token var wreturn = ExtractInBetween(contentAsText, "wresult\" value=\"", "\""); Assert.False(wreturn.StartsWith("%EF%BB%BF")); //don't start with BOM (Byte Order Mark) var wsMessage = new WsFederationMessage { Wresult = WebUtility.HtmlDecode(wreturn), }; var tokenString = wsMessage.GetToken(); var handler = new SamlSecurityTokenHandler(); var canReadToken = handler.CanReadToken(tokenString); Assert.True(canReadToken); }
public WsTrustTestsFixture() { Certificate = new X509Certificate2(Convert.FromBase64String(Certificates.SigningCertificteBase64)); ClientCertificate = new X509Certificate2(Convert.FromBase64String(Certificates.ClientCertificateBase64)); var saml = new SamlSecurityTokenHandler(); var saml2 = new Saml2SecurityTokenHandler(); var god = new GodSecurityTokenHandler(); _handlers = new Dictionary <string, SecurityTokenHandler> { { SamlTokenType, saml }, { Saml2TokenType, saml2 }, { "urn:god", god }, { "urn:deity", god } }; }
/// <summary> /// Initializes an instance of <see cref="WrappedSaml11SecurityTokenAuthenticator"/> /// </summary> /// <param name="saml11SecurityTokenHandler">The Saml11SecurityTokenHandler to wrap.</param> /// <param name="exceptionMapper">Converts token validation exceptions to SOAP faults.</param> public WrappedSaml11SecurityTokenAuthenticator( SamlSecurityTokenHandler saml11SecurityTokenHandler, ExceptionMapper exceptionMapper) : base(new List <SecurityTokenAuthenticator>()) { if (saml11SecurityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("wrappedSaml11SecurityTokenHandler"); } if (exceptionMapper == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exceptionMapper"); } _wrappedSaml11SecurityTokenHandler = saml11SecurityTokenHandler; _exceptionMapper = exceptionMapper; }
public static string WriteSamlToken(SecurityToken token) { using (var stringWriter = new StringWriter()) using (var writer = XmlWriter.Create(stringWriter)) { if (writer == null) { throw new Exception("Could not create XMlWriter based on empty stringwriter"); } var handler = new SamlSecurityTokenHandler(); handler.WriteToken(writer, token); writer.Flush(); var tokenString = stringWriter.ToString(); return(tokenString); } }
private static string CreateSignedXmlWithEmbededTokens(IList <SecurityToken> samlTokens, SigningCredentials xmlSigningCredentials, SigningCredentials tokenSigningCredentials) { var ms = new MemoryStream(); var writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false); var samlTokenHandler = new SamlSecurityTokenHandler(); var saml2TokenHandler = new Saml2SecurityTokenHandler(); var envelopedWriter = new EnvelopedSignatureWriter(writer, xmlSigningCredentials, "ref#1"); envelopedWriter.WriteStartElement("local", "elementName", "http://elementnamespace"); envelopedWriter.WriteElementString("localElement", "SamlWillBeEmbeded"); foreach (var token in samlTokens) { if (token is SamlSecurityToken) { samlTokenHandler.WriteToken(envelopedWriter, token); } else { saml2TokenHandler.WriteToken(envelopedWriter, token); } } envelopedWriter.WriteStartElement("local", "elementName2", "http://elementnamespace"); envelopedWriter.WriteElementString("localElement", "SamlWillBeEmbeded2"); foreach (var token in samlTokens) { if (token is SamlSecurityToken) { samlTokenHandler.WriteToken(envelopedWriter, token); } else { saml2TokenHandler.WriteToken(envelopedWriter, token); } } envelopedWriter.WriteEndElement(); envelopedWriter.WriteEndElement(); envelopedWriter.Flush(); var xml = Encoding.UTF8.GetString(ms.ToArray()); return(xml); }
private static SamlSecurityToken CreateSamlToken(IList <Claim> claims) { var samlTokenHandler = new SamlSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Audience = Default.Audience, NotBefore = Default.NotBefore, Expires = Default.Expires, IssuedAt = Default.IssueInstant, Issuer = Default.Issuer, SigningCredentials = Default.AsymmetricSigningCredentials, Subject = new ClaimsIdentity(claims) }; var token = samlTokenHandler.CreateToken(tokenDescriptor) as SamlSecurityToken; token.SigningKey = Default.AsymmetricSigningKey; return(token); }
public void ReadEpamSignedSamlToken() { var tokenHandler = new SamlSecurityTokenHandler(); var issuerRegistry = new ConfigurationBasedIssuerNameRegistry(); issuerRegistry.AddTrustedIssuer(CERTIFICATE_THUMBPRINT, ISSUER_NAME); tokenHandler.Configuration = new SecurityTokenHandlerConfiguration() { AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never), IssuerNameRegistry = issuerRegistry, MaxClockSkew = TimeSpan.MaxValue }; var xmlReader = XmlReader.Create(new StringReader(Resource.EpamToken)); var token = tokenHandler.ReadToken(xmlReader, new NamedKeyIssuerTokenResolver()) as SamlSecurityToken; var identity = tokenHandler.ValidateToken(token).First(); PrintIdentity(identity); }
public async Task WsFederation_signin_request_with_wfresh_set_to_0_user_is_authenticated_force_resignin_return_assertion_success() { // login user var subjectId = "user1"; var loginUrl = string.Format("/account/login?subjectId={0}", WebUtility.UrlEncode(subjectId)); var loginResponse = await _client.GetAsync(loginUrl); var authTime = DateTime.UtcNow; Thread.Sleep(3000); // TODO: bad workaround to sumulate login for 3 seconds // create ws fed sigin message with wfresh var wsMessage = new WsFederationMessage { Wa = "wsignin1.0", IssuerAddress = "/wsfederation", Wtrealm = "urn:owinrp", Wreply = "http://localhost:10313/", Wfresh = "0", }; var uri = wsMessage.CreateSignInUrl(); var request = new HttpRequestMessage(HttpMethod.Get, uri); // test server doesnt save cookies between requests, // so we set them explicitly for the next request request.SetCookiesFromResponse(loginResponse); // make auth request, for allready logged in user var response = await _client.SendAsync(request); // redirect to sign in package because we enforce it with wfresh=0 Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); uri = response.Headers.Location.OriginalString + "&subjectId=" + subjectId; request = new HttpRequestMessage(HttpMethod.Get, uri); request.SetCookiesFromResponse(response); // login again to satisfy wfresh=0 response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); uri = response.Headers.Location.OriginalString; request = new HttpRequestMessage(HttpMethod.Get, uri); request.SetCookiesFromResponse(response); // do the redirect to auth endpoint response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var contentAsText = await response.Content.ReadAsStringAsync(); Assert.NotEqual(String.Empty, contentAsText); Assert.Contains("action=\"http://localhost:10313/\"", contentAsText); // extract wreturn to use it later to check if our token is a valid token var wreturn = ExtractInBetween(contentAsText, "wresult\" value=\"", "\""); var wsResponseMessage = new WsFederationMessage { Wresult = WebUtility.HtmlDecode(wreturn), }; var tokenString = wsResponseMessage.GetToken(); var handler = new SamlSecurityTokenHandler(); var canReadToken = handler.CanReadToken(tokenString); Assert.True(canReadToken); var token = handler.ReadSamlToken(tokenString); var authStatements = token.Assertion.Statements.OfType <SamlAuthenticationStatement>(); Assert.Equal(1, authStatements.Count()); var authStatement = authStatements.First(); Assert.True(authStatement.AuthenticationInstant <= authTime.AddMinutes(5)); }
/// <summary> /// This method creates a SAML security token authenticator when token type is null. /// It wraps the SAML 1.1 and the SAML 2.0 token handlers that are configured. /// If no token handler was found, then the inner token manager is created. /// </summary> SecurityTokenAuthenticator CreateSamlSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver) { outOfBandTokenResolver = null; SecurityTokenAuthenticator securityTokenAuthenticator = null; SamlSecurityTokenHandler saml11SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.SamlTokenProfile11] as SamlSecurityTokenHandler; Saml2SecurityTokenHandler saml2SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.Saml2TokenProfile11] as Saml2SecurityTokenHandler; if (saml11SecurityTokenHandler != null && saml11SecurityTokenHandler.Configuration == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } if (saml2SecurityTokenHandler != null && saml2SecurityTokenHandler.Configuration == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } if (saml11SecurityTokenHandler != null && saml2SecurityTokenHandler != null) { // // Both SAML 1.1 and SAML 2.0 token handlers have been configured. // WrappedSaml11SecurityTokenAuthenticator wrappedSaml11SecurityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator(saml11SecurityTokenHandler, _exceptionMapper); WrappedSaml2SecurityTokenAuthenticator wrappedSaml2SecurityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator(saml2SecurityTokenHandler, _exceptionMapper); securityTokenAuthenticator = new WrappedSamlSecurityTokenAuthenticator(wrappedSaml11SecurityTokenAuthenticator, wrappedSaml2SecurityTokenAuthenticator); // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens. List <SecurityTokenResolver> resolvers = new List <SecurityTokenResolver>(); resolvers.Add(saml11SecurityTokenHandler.Configuration.ServiceTokenResolver); resolvers.Add(saml2SecurityTokenHandler.Configuration.ServiceTokenResolver); outOfBandTokenResolver = new AggregateTokenResolver(resolvers); } else if (saml11SecurityTokenHandler == null && saml2SecurityTokenHandler != null) { // // SAML 1.1 token handler is not present but SAML 2.0 is. Set the token type to SAML 2.0 // securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator(saml2SecurityTokenHandler, _exceptionMapper); // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens. outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver; } else if (saml11SecurityTokenHandler != null && saml2SecurityTokenHandler == null) { // // SAML 1.1 token handler is present but SAML 2.0 is not. Set the token type to SAML 1.1 // securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator(saml11SecurityTokenHandler, _exceptionMapper); // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens. outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver; } else { securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver); } return(securityTokenAuthenticator); }
/// <summary> /// Overriden from the base class. Creates the requested Token Authenticator. /// Looks up the list of Token Handlers registered with the token Manager /// based on the TokenType Uri in the SecurityTokenRequirement. If none is found, /// then the call is delegated to the inner Token Manager. /// </summary> /// <param name="tokenRequirement">Security Token Requirement for which the Authenticator should be created.</param> /// <param name="outOfBandTokenResolver">Token resolver that resolves any out-of-band tokens.</param> /// <returns>Instance of Security Token Authenticator.</returns> /// <exception cref="ArgumentNullException">'tokenRequirement' parameter is null.</exception> /// <exception cref="NotSupportedException">No Authenticator is registered for the given token type.</exception> public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } outOfBandTokenResolver = null; // Check for a registered authenticator SecurityTokenAuthenticator securityTokenAuthenticator = null; string tokenType = tokenRequirement.TokenType; // // When the TokenRequirement.TokenType is null, we treat this as a SAML issued token case. It may be SAML 1.1 or SAML 2.0. // if (String.IsNullOrEmpty(tokenType)) { return(CreateSamlSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver)); } // // When the TokenType is set, build a token authenticator for the specified token type. // SecurityTokenHandler securityTokenHandler = _securityTokenHandlerCollection[tokenType]; if ((securityTokenHandler != null) && (securityTokenHandler.CanValidateToken)) { outOfBandTokenResolver = GetDefaultOutOfBandTokenResolver(); if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.UserName)) { UserNameSecurityTokenHandler upSecurityTokenHandler = securityTokenHandler as UserNameSecurityTokenHandler; if (upSecurityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(UserNameSecurityTokenHandler)))); } securityTokenAuthenticator = new WrappedUserNameSecurityTokenAuthenticator(upSecurityTokenHandler, _exceptionMapper); } else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.Kerberos)) { securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver); } else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.Rsa)) { RsaSecurityTokenHandler rsaSecurityTokenHandler = securityTokenHandler as RsaSecurityTokenHandler; if (rsaSecurityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(RsaSecurityTokenHandler)))); } securityTokenAuthenticator = new WrappedRsaSecurityTokenAuthenticator(rsaSecurityTokenHandler, _exceptionMapper); } else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.X509Certificate)) { X509SecurityTokenHandler x509SecurityTokenHandler = securityTokenHandler as X509SecurityTokenHandler; if (x509SecurityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(X509SecurityTokenHandler)))); } securityTokenAuthenticator = new WrappedX509SecurityTokenAuthenticator(x509SecurityTokenHandler, _exceptionMapper); } else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.SamlTokenProfile11) || StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.OasisWssSamlTokenProfile11)) { SamlSecurityTokenHandler saml11SecurityTokenHandler = securityTokenHandler as SamlSecurityTokenHandler; if (saml11SecurityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(SamlSecurityTokenHandler)))); } if (saml11SecurityTokenHandler.Configuration == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator(saml11SecurityTokenHandler, _exceptionMapper); // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens. outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver; } else if (StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.Saml2TokenProfile11) || StringComparer.Ordinal.Equals(tokenType, SecurityTokenTypes.OasisWssSaml2TokenProfile11)) { Saml2SecurityTokenHandler saml2SecurityTokenHandler = securityTokenHandler as Saml2SecurityTokenHandler; if (saml2SecurityTokenHandler == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.GetString(SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof(Saml2SecurityTokenHandler)))); } if (saml2SecurityTokenHandler.Configuration == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator(saml2SecurityTokenHandler, _exceptionMapper); // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens. outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver; } else if (StringComparer.Ordinal.Equals(tokenType, ServiceModelSecurityTokenTypes.SecureConversation)) { RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement; if (tr == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4240, tokenRequirement.GetType().ToString())); } securityTokenAuthenticator = SetupSecureConversationWrapper(tr, securityTokenHandler as SessionSecurityTokenHandler, out outOfBandTokenResolver); } else { securityTokenAuthenticator = new SecurityTokenAuthenticatorAdapter(securityTokenHandler, _exceptionMapper); } } else { if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation || tokenType == ServiceModelSecurityTokenTypes.MutualSslnego || tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || tokenType == ServiceModelSecurityTokenTypes.SecurityContext || tokenType == ServiceModelSecurityTokenTypes.Spnego) { RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement; if (tr == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4240, tokenRequirement.GetType().ToString())); } securityTokenAuthenticator = SetupSecureConversationWrapper(tr, null, out outOfBandTokenResolver); } else { securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver); } } return(securityTokenAuthenticator); }
internal static ClaimsIdentity ValidateSaml(SamlSecurityToken token) { SamlSecurityTokenHandler handler = TokenHelper.GetSamlHandler(); return(handler.ValidateToken(token).FirstOrDefault <ClaimsIdentity>()); }
public static void Run(string[] args) { IdentityModelEventSource.ShowPII = true; var testRuns = TestConfig.SetupTestRuns( new List <TestExecutor> { TokenTestExecutors.JsonWebTokenHandler_ValidateToken_InParallel, TokenTestExecutors.JwtSecurityTokenHandler_ValidateToken_InParallel, TokenTestExecutors.Saml2SecurityTokenHandler_ValidateToken_InParallel, TokenTestExecutors.SamlSecurityTokenHandler_ValidateToken_InParallel, TokenTestExecutors.JsonWebTokenHandler_CreateToken_InParallel, TokenTestExecutors.JwtSecurityTokenHandler_CreateToken_InParallel, TokenTestExecutors.Saml2SecurityTokenHandler_CreateToken_InParallel, TokenTestExecutors.SamlSecurityTokenHandler_CreateToken_InParallel, }); var securityTokenDescriptor = TestData.SecurityTokenDescriptor(TestData.RsaSigningCredentials_2048Sha256); var tokenValidationParameters = TestData.TokenValidationParameters(securityTokenDescriptor.SigningCredentials.Key); var jwtTokenHandler = new JwtSecurityTokenHandler(); var jwt = jwtTokenHandler.CreateEncodedJwt(securityTokenDescriptor); var samlTokenHandler = new SamlSecurityTokenHandler(); var samlToken = samlTokenHandler.CreateToken(securityTokenDescriptor); var saml = samlTokenHandler.WriteToken(samlToken); var saml2TokenHandler = new Saml2SecurityTokenHandler(); var saml2Token = saml2TokenHandler.CreateToken(securityTokenDescriptor); var saml2 = saml2TokenHandler.WriteToken(saml2Token); var testConfig = TestConfig.ParseArgs(args); var tokenTestData = new TokenTestRunData { JwtSecurityTokenHandler = new JwtSecurityTokenHandler(), JsonWebTokenHandler = new JsonWebTokenHandler(), JwtToken = jwt, NumIterations = testConfig.NumIterations, Saml2Token = saml2, SamlToken = saml, SamlSecurityTokenHandler = samlTokenHandler, Saml2SecurityTokenHandler = saml2TokenHandler, TokenValidationParameters = tokenValidationParameters, SecurityTokenDescriptor = securityTokenDescriptor }; // run each test to set any static data foreach (var testRun in testRuns) { testRun.TestExecutor(tokenTestData); } var assemblyVersion = typeof(JwtSecurityTokenHandler).Assembly.GetName().Version.ToString(); #if DEBUG var prefix = "DEBUG"; #else var prefix = "RELEASE"; #endif testConfig.Version = $"{prefix}-{assemblyVersion}"; var logName = $"SecurityTokens-{testConfig.Version}_{DateTime.Now.ToString("yyyy.MM.dd.hh.mm.ss")}.txt"; var directory = testConfig.LogDirectory; var logFile = Path.Combine(directory, logName); Directory.CreateDirectory(directory); TestRunner.Run(testConfig, testRuns, tokenTestData); File.WriteAllText(logFile, testConfig.Logger.Logs); }
public void Defaults() { SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); Assert.True(samlSecurityTokenHandler.MaximumTokenSizeInBytes == TokenValidationParameters.DefaultMaximumTokenSizeInBytes, "MaximumTokenSizeInBytes"); }
static string CreateSamlTokenString() { var tokenHandler = new SamlSecurityTokenHandler(); return(tokenHandler.WriteToken(CreateSamlToken())); }
internal static SamlSecurityToken ParseSaml(string tokenString) { SamlSecurityTokenHandler handler = TokenHelper.GetSamlHandler(); return(handler.ReadToken(new XmlTextReader(new StringReader(tokenString))) as SamlSecurityToken); }
private static void AddWaSignInVariation(IList <Claim> claims, string variation, TheoryData <WsFederationSigninMessageTheoryData> theoryData) { var samlToken = CreateSamlToken(claims); var samlSecurityTokenHandler = new SamlSecurityTokenHandler(); theoryData.Add(new WsFederationSigninMessageTheoryData { QueryString = WsFederationTestUtilities.BuildWaSignInMessage(samlToken, samlSecurityTokenHandler, "saml1" + variation), SecurityToken = samlToken, SecurityTokenHandler = samlSecurityTokenHandler, TestId = "Saml1WriteToken" + variation }); theoryData.Add(new WsFederationSigninMessageTheoryData { QueryString = WsFederationTestUtilities.BuildWaSignInMessage(samlSecurityTokenHandler.WriteToken(samlToken), "saml1" + variation), SecurityToken = samlToken, SecurityTokenHandler = samlSecurityTokenHandler, TestId = "Saml1SetToken" + variation }); // this results in %0D in the query string var saml = samlSecurityTokenHandler.WriteToken(samlToken).Replace("
", "\r"); theoryData.Add(new WsFederationSigninMessageTheoryData { QueryString = WsFederationTestUtilities.BuildWaSignInMessage(saml, "saml1" + variation), SecurityToken = samlToken, SecurityTokenHandler = samlSecurityTokenHandler, TestId = "Saml1SetTokenReplace" + variation }); var saml2Token = CreateSaml2Token(claims); var saml2SecurityTokenHandler = new Saml2SecurityTokenHandler(); theoryData.Add(new WsFederationSigninMessageTheoryData { QueryString = WsFederationTestUtilities.BuildWaSignInMessage(saml2Token, saml2SecurityTokenHandler, "saml2" + variation), SecurityToken = saml2Token, SecurityTokenHandler = saml2SecurityTokenHandler, TestId = "Saml2WriteToken" + variation }); theoryData.Add(new WsFederationSigninMessageTheoryData { QueryString = WsFederationTestUtilities.BuildWaSignInMessage(saml2SecurityTokenHandler.WriteToken(saml2Token), "saml2" + variation), SecurityToken = saml2Token, SecurityTokenHandler = saml2SecurityTokenHandler, TestId = "Saml2SetToken" + variation }); // this results in %0D in the query string var saml2 = saml2SecurityTokenHandler.WriteToken(saml2Token).Replace("
", "\r"); theoryData.Add(new WsFederationSigninMessageTheoryData { QueryString = WsFederationTestUtilities.BuildWaSignInMessage(saml2, "saml2" + variation), SecurityToken = saml2Token, SecurityTokenHandler = saml2SecurityTokenHandler, TestId = "Saml2SetTokenReplace" + variation }); }
public void Constructors() { SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); }