private static void LoginWithUsernamePassword(AuthenticationHeaderValue credentials, SecurityTokenHandlerCollection handlers, HttpApplication context) { try { var cred = EncodingFactory.ReadFileText(Convert.FromBase64String(credentials.Parameter)); var separator = cred.IndexOf(':'); var name = cred.Substring(0, separator); var password = cred.Substring(separator + 1); var manager = new TokenManager(GetServiceName(context), name, password); SecurityToken token = null; var xmlSecurityToken = manager.GetToken(HttpContext.Current.Request.Url.ToString()) as GenericXmlSecurityToken; if (xmlSecurityToken != null) { token = handlers.ReadToken(new XmlTextReader(new StringReader(xmlSecurityToken.TokenXml.OuterXml))); } var securityToken = handlers.ValidateToken(token); var principal = new ClaimsPrincipal(securityToken); var identity = principal.Identity as ClaimsIdentity; if (identity != null) { identity.BootstrapContext = new BootstrapContext(xmlSecurityToken.TokenXml.OuterXml); } Thread.CurrentPrincipal = principal; context.Context.User = principal; var sessionToken = new SessionSecurityToken(principal); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); } catch (Exception) { context.Response.AppendHeader("X-InvalidCredentials", "basic"); throw; } }
private ClaimsPrincipal ParseToken(GenericXmlSecurityToken genericToken) { using (XmlReader samlReader = XmlReader.Create(new StringReader(genericToken.TokenXml.OuterXml))) { SecurityTokenHandlerCollection tokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); SecurityTokenHandlerConfiguration config = tokenHandlers.Configuration; var securityTokens = new List <SecurityToken> { new X509SecurityToken(CertificateHelper.GetCertificate(_tokenClientOptions.StoreName, _tokenClientOptions.StoreLocation, _tokenClientOptions.SubjectDistinguishedName)) }; config.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(securityTokens.AsReadOnly(), false); config.CertificateValidator = X509CertificateValidator.PeerOrChainTrust; config.IssuerTokenResolver = new X509CertificateStoreTokenResolver(_tokenClientOptions.StoreName, _tokenClientOptions.StoreLocation); config.IssuerNameRegistry = _nameRegistry; config.AudienceRestriction.AllowedAudienceUris.Add(_tokenClientOptions.AudienceUri); SecurityToken samlToken = tokenHandlers.ReadToken(samlReader); ClaimsIdentity tokenIdentity = tokenHandlers.ValidateToken(samlToken).FirstOrDefault(); return(new ClaimsPrincipal(tokenIdentity)); } }
private static void LoginWithToken(AuthenticationHeaderValue credentials, SecurityTokenHandlerCollection handlers, HttpApplication context) { try { var token = Convert.FromBase64String(credentials.Parameter); using (var stream = new MemoryStream(token)) { using (var xmlReader = XmlReader.Create(stream)) { var securityToken = handlers.ReadToken(xmlReader); var identities = handlers.ValidateToken(securityToken); var principal = new ClaimsPrincipal(identities); var identity = principal.Identity as ClaimsIdentity; if (identity != null) { identity.BootstrapContext = new BootstrapContext(token); } Thread.CurrentPrincipal = principal; context.Context.User = principal; } } } catch (Exception) { context.Response.AppendHeader("X-InvalidCredentials", "token"); throw; } }
private ClaimsPrincipal GetClaimsPrincipal(SignInResponseMessage signInResponse) { try { //configure the certificate and some service token handler configuration properties (these basically match the web.config settings for MVC 4/5 app). SecurityTokenHandlerConfiguration config = new SecurityTokenHandlerConfiguration(); config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Options.Realm)); config.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; //we have dodgy certs in dev ConfigurationBasedIssuerNameRegistry inr = new ConfigurationBasedIssuerNameRegistry(); inr.AddTrustedIssuer(Options.SigningCertThumbprint, Options.ClaimsIssuer); config.IssuerNameRegistry = inr; config.CertificateValidator = System.IdentityModel.Selectors.X509CertificateValidator.None; //we have dodgy certs in dev //Load up an XmlDocument with the result. Have to use XmlDocument so we can generate a valid reader unfortunately. XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(signInResponse.Result); //Add the namespaces and search for Assertion or EncryptedAssertion XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDoc.NameTable); nsMan.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512"); nsMan.AddNamespace("saml2", "urn:oasis:names:tc:SAML:2.0:assertion"); var parentNodes = "trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/"; var assertionNode = xmlDoc.SelectSingleNode(parentNodes + "saml2:EncryptedAssertion", nsMan); if (assertionNode == null) { assertionNode = xmlDoc.SelectSingleNode(parentNodes + "saml2:Assertion", nsMan); } else { //this is an encrypted response so add a ServiceTokenResolver of X509CertificateStoreTokenResolver so the assertion can be decrypted. Hard codes LocalMachine - could be configured as well. config.ServiceTokenResolver = new X509CertificateStoreTokenResolver(Options.EncryptionCertStoreName, StoreLocation.LocalMachine); } if (assertionNode == null) { throw new Exception("No assertion element found in Response."); } using (var reader = new XmlNodeReader(assertionNode)) { //Get the token and convert it to a Claims Principal for return SecurityTokenHandlerCollection collection = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config); var securityToken = collection.ReadToken(reader); var claimsIdentities = collection.ValidateToken(securityToken); ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentities); return(principal); } } catch (Exception ex) { //TODO: Add some logging var err = ex; } return(null); }
IClaimsPrincipal AuthenticateSecurityToken(string endpoint, SecurityToken token) { ClaimsIdentityCollection claims = _handlers.ValidateToken(token); IClaimsPrincipal principal = ClaimsPrincipal.CreateFromIdentities(claims); return(CustomSecurityTokenServiceConfiguration.Current.ClaimsAuthenticationManager.Authenticate(endpoint, principal)); }
private void ValidateToken(string securityToken, TokenValidationParameters validationParameters, SecurityTokenHandlerCollection tokenHandlers, ExpectedException expectedException) { try { SecurityToken validatedToken; tokenHandlers.ValidateToken(securityToken, validationParameters, out validatedToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } }
private ClaimsPrincipal GetPrincipal(string tokenString) { var tokenHandlerCollection = new SecurityTokenHandlerCollection(); tokenHandlerCollection.AddOrReplace(new JwtSecurityTokenHandler()); tokenHandlerCollection.AddOrReplace(new SamlSecurityTokenHandler()); var principal = tokenHandlerCollection.ValidateToken(tokenString, new TokenValidationParameters { RequireSignedTokens = false, ValidateLifetime = false, ValidateAudience = false, ValidateIssuer = false, ValidateActor = false, ValidateIssuerSigningKey = false }, out _); return(principal); }
private ReadOnlyCollection <ClaimsIdentity> ValidateAssertion(string assertionXml) { ReadOnlyCollection <ClaimsIdentity> claimsIdentities = null; Saml2SecurityToken securityToken; StringReader reader = new StringReader(assertionXml); using (XmlReader xmlReader = XmlReader.Create(reader)) { if (!xmlReader.ReadToFollowing("saml2:Assertion")) { throw new SecurityTokenValidationException("SAML2 Assertion not found."); } FixedSaml2SecurityTokenHandler tokenHandler = new FixedSaml2SecurityTokenHandler(Recipient); SecurityTokenHandler[] tokenHandlers = new SecurityTokenHandlers[] { tokenHandler }; SecurityTokenHandlerCollection handlerCollection = new SecurityTokenHandlerCollection(tokenHandlers); ConfigurationBasedIssuerNameRegistry issuerNameRegistry = new ConfigurationBasedIssuerNameRegistry(); foreach (TrustedIssuer issuer in TrustedIssuers) { issuerNameRegistry.AddTrustedIssuer(issuer.CertificateThumbprint, issuer.IssuerName); } handlerCollection.Configuration.IssuerNameRegistry = issuerNameRegistry; AudienceRestriction restriction = new AudienceRestriction(AudienceUriMode.Always); foreach (Uri allowedAudience in AllowedAudiences) { restriction.AllowedAudiencesUris.Add(allowedAudience); } handlerCollection.Configuration.AudienceRestriction = restriction; securityToken = (Saml2SecurityToken)handlerCollection.ReadToken(xmlReader.ReadSubtree()); claimsIdentities = handlerCollection.ValidateToken(securityToken); } return(claimsIdentities); }
/// <summary> /// Creates the identities for the represented by the <see cref="SecurityToken"/>. /// </summary> /// <param name="securityTokenXml">The <see cref="XmlElement"/> representation of the security token.</param> /// <param name="securityTokenHandlers">The collection of <see cref="SecurityTokenHandler"/> objects that may /// be used to read and validate the security token this object represents.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns> /// <exception cref="InvalidOperationException">If either parameter 'securityTokenXml' or 'securityTokenHandlers' are null.</exception> protected virtual ReadOnlyCollection<ClaimsIdentity> ValidateToken(XmlElement securityTokenXml, SecurityTokenHandlerCollection securityTokenHandlers) { if (securityTokenXml == null || securityTokenHandlers == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4052))); } SecurityToken securityToken = GetSecurityToken(); return securityTokenHandlers.ValidateToken(securityToken); }
/// <summary>Converts a SecurityToken to an IClaimsPrincipal.</summary> /// <param name="token">The token.</param> /// <param name="handler">The handler.</param> /// <returns>An IClaimsPrincipal</returns> public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler) { var ids = handler.ValidateToken(token); return(new ClaimsPrincipal(from identity in ids select identity)); }
/// <summary> /// Converts a SecurityToken to an IClaimsPrincipal. /// </summary> /// <param name="token">The token.</param> /// <param name="handler">The handler.</param> /// <returns> /// An IClaimsPrincipal /// </returns> public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler) { return new ClaimsPrincipal(handler.ValidateToken(token).Select(identity => identity)); }
/// <summary>Converts a SecurityToken to an IClaimsPrincipal.</summary> /// <param name="token">The token.</param> /// <param name="handler">The handler.</param> /// <returns>An IClaimsPrincipal</returns> public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler) { return (new ClaimsPrincipal(handler.ValidateToken(token).Select(identity => identity))); }
private static void LoginWithUsernamePassword(AuthenticationHeaderValue credentials, SecurityTokenHandlerCollection handlers, HttpApplication context) { try { var cred = EncodingFactory.ReadFileText(Convert.FromBase64String(credentials.Parameter)); var separator = cred.IndexOf(':'); var name = cred.Substring(0, separator); var password = cred.Substring(separator + 1); var manager = new TokenManager(GetServiceName(context), name, password); SecurityToken token = null; var xmlSecurityToken = manager.GetToken(HttpContext.Current.Request.Url.ToString()) as GenericXmlSecurityToken; if (xmlSecurityToken != null) { token = handlers.ReadToken(new XmlTextReader(new StringReader(xmlSecurityToken.TokenXml.OuterXml))); } var securityToken = handlers.ValidateToken(token); var principal = new ClaimsPrincipal(securityToken); var identity = principal.Identity as ClaimsIdentity; if (identity != null) identity.BootstrapContext = new BootstrapContext(xmlSecurityToken.TokenXml.OuterXml); Thread.CurrentPrincipal = principal; context.Context.User = principal; var sessionToken = new SessionSecurityToken(principal); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); } catch (Exception) { context.Response.AppendHeader("X-InvalidCredentials", "basic"); throw; } }
/// <summary> /// Converts a SecurityToken to an IClaimsPrincipal. /// </summary> /// <param name="token">The token.</param> /// <param name="handler">The handler.</param> /// <returns>An IClaimsPrincipal</returns> public static IClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler) { var ids = handler.ValidateToken(token); return ClaimsPrincipal.CreateFromIdentities(ids); }
public ActionResult Authenticate(string ReturnUrl) { if (Request.Form.Get(WSFederationConstants.Parameters.Result) != null) { var settings = this.SettingsService.Retrieve(); // Parse sign-in response SignInResponseMessage message = WSFederationMessage.CreateFromFormPost(System.Web.HttpContext.Current.Request) as SignInResponseMessage; XmlTextReader xmlReader = new XmlTextReader( new StringReader(message.Result)); XDocument xDoc = XDocument.Load(xmlReader); XNamespace xNs = "http://schemas.xmlsoap.org/ws/2005/02/trust"; var rst = xDoc.Descendants(xNs + "RequestedSecurityToken").FirstOrDefault(); if (rst == null) { throw new ApplicationException("No RequestedSecurityToken element was found in the returned XML token. Ensure an unencrypted SAML 2.0 token is issued."); } var rstDesc = rst.Descendants().FirstOrDefault(); if (rstDesc == null) { throw new ApplicationException("No valid RequestedSecurityToken element was found in the returned XML token. Ensure an unencrypted SAML 2.0 token is issued."); } var config = new SecurityTokenHandlerConfiguration(); config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(settings.AudienceUrl)); config.CertificateValidator = X509CertificateValidator.None; config.IssuerNameRegistry = new AccessControlServiceIssuerRegistry( settings.StsIssuerUrl, settings.X509CertificateThumbprint); var securityTokenHandlers = new SecurityTokenHandlerCollection(config); securityTokenHandlers.Add(new Saml11SecurityTokenHandler()); securityTokenHandlers.Add(new Saml2SecurityTokenHandler()); securityTokenHandlers.Add(new EncryptedSecurityTokenHandler()); var token = securityTokenHandlers.ReadToken(rstDesc.CreateReader()); ClaimsIdentityCollection claims = securityTokenHandlers.ValidateToken(token); IPrincipal principal = new ClaimsPrincipal(claims); // Map claims to local users string roleClaimValue = ""; string usernameClaimValue = ""; string emailClaimValue = ""; foreach (var claimsIdentity in claims) { foreach (var claim in claimsIdentity.Claims) { if (claim.ClaimType == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && settings.TranslateClaimsToOrchardRoles) { roleClaimValue = claim.Value; } else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" && settings.TranslateClaimsToOrchardUserProperties) { emailClaimValue = claim.Value; } else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name") { usernameClaimValue = claim.Value; } else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" && string.IsNullOrEmpty(usernameClaimValue)) { usernameClaimValue = claim.Value; } } } if (string.IsNullOrEmpty(usernameClaimValue)) { throw new SecurityException("Could not determine username from input claims. Ensure a \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\" or \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier\" claim is issued by the STS."); } IUser user = MembershipService.GetUser(settings.FederatedUsernamePrefix + usernameClaimValue); if (user == null) { user = MembershipService.CreateUser(new CreateUserParams(settings.FederatedUsernamePrefix + usernameClaimValue, Guid.NewGuid().ToString(), emailClaimValue, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true)); } AuthenticationService.SignIn(user, false); if (!string.IsNullOrEmpty(roleClaimValue)) { var role = RoleService.GetRoleByName(roleClaimValue); if (role != null) { UserRolesPartRecord currentRole = UserRolesRepository.Get(r => r.UserId == user.Id && r.Role == role); if (currentRole == null) { UserRolesRepository.Create(new UserRolesPartRecord { UserId = user.Id, Role = role }); } } } } return(new RedirectResult(ReturnUrl)); }
/// <summary> /// Converts a SecurityToken to an IClaimsPrincipal. /// </summary> /// <param name="token">The token.</param> /// <param name="handler">The handler.</param> /// <returns>An IClaimsPrincipal</returns> public static IClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler) { var ids = handler.ValidateToken(token); return(ClaimsPrincipal.CreateFromIdentities(ids)); }
static void Main(string[] args) { { // read token var jwtHandler = new JwtSecurityTokenHandler(); //string jwtEncodedString = "eyJ0eXAiOiJKV1QiLCJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjcnNhLXNoYTEiLCJ4NXQiOiI0dnk1YV9oM0NVcFJEd3QzbUFCSUdaWlgxMWcifQ.eyJpc3MiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJhdWQiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJuYmYiOjE0NDEzNzg0MTQsImV4cCI6MTQ0MTk4MzIxNCwidW5pcXVlX25hbWUiOiJXZW5qdW4iLCJnaXZlbl9uYW1lIjoiV2VuanVuIiwiZ3JvdXAiOlsiUkFZTUFSS0xBQlxcRG9tYWluIEFkbWlucyIsIlJBWU1BUktMQUJcXERvbWFpbiBVc2VycyJdLCJhdXRobWV0aG9kIjoiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2F1dGhlbnRpY2F0aW9ubWV0aG9kL3Bhc3N3b3JkIiwiYXV0aF90aW1lIjoiMjAxNS0wOS0wNFQxNDo1MzoyNi4xNDdaIn0.NTEU48x2-faKVISrv50ucfwJSma4lDuAFGOe5e6QScOxT7rNUilyn3SxIsUVtRKVDLY1Inof8FhARiBUXcoED153z9EyQVoqX4xgWwTccKzcRGdwELn77iK1bGl_Mb51mj4QWbDARSVXS3m4fMrS4V70XuDXhWM5bv7xpRUxW5ibkMu6Ih60OVUvStLb7XM1RZ3mvtqjFhOTO1Omsng5gU2OViLsuPBoNCi-nMyi47qKz5R3X502uFvCQirLud3Igjc0OqMhRkZzz-NNAvo4i_78fTmvrltyLMxHgTuiM7w9vGsGQ-u6SA-PR9LT3lkIlhtuzkBZLi1wWS55Gmc-1g"; string jwtEncodedString = "eyJ0eXAiOiJKV1QiLCJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjcnNhLXNoYTEiLCJ4NXQiOiI0dnk1YV9oM0NVcFJEd3QzbUFCSUdaWlgxMWcifQ.eyJpc3MiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJhdWQiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJuYmYiOjE0NDEzNzg0MTQsImV4cCI6MTQ0MTk4MzIxNCwidW5pcXVlX25hbWUiOiJXZW5qdW4iLCJnaXZlbl9uYW1lIjoiV2VuanVuIiwiZ3JvdXAiOlsiUkFZTUFSS0xBQlxcRG9tYWluIEFkbWlucyIsIlJBWU1BUktMQUJcXERvbWFpbiBVc2VycyJdLCJhdXRobWV0aG9kIjoiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2F1dGhlbnRpY2F0aW9ubWV0aG9kL3Bhc3N3b3JkIiwiYXV0aF90aW1lIjoiMjAxNS0wOS0wNFQxNDo1MzoyNi4xNDdaIn0.NTEU48x2-faKVISrv50ucfwJSma4lDuAFGOe5e6QScOxT7rNUilyn3SxIsUVtRKVDLY1Inof8FhARiBUXcoED153z9EyQVoqX4xgWwTccKzcRGdwELn77iK1bGl_Mb51mj4QWbDARSVXS3m4fMrS4V70XuDXhWM5bv7xpRUxW5ibkMu6Ih60OVUvStLb7XM1RZ3mvtqjFhOTO1Omsng5gU2OViLsuPBoNCi-nMyi47qKz5R3X502uFvCQirLud3Igjc0OqMhRkZzz-NNAvo4i_78fTmvrltyLMxHgTuiM7w9vGsGQ-u6SA-PR9LT3lkIlhtuzkBZLi1wWS55Gmc-1g"; SecurityToken sToken = jwtHandler.ReadToken(jwtEncodedString); X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var cs = store.Certificates.Find(X509FindType.FindByThumbprint, "E2FCB96BF877094A510F0B77980048199657D758", false); X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "E2FCB96BF877094A510F0B77980048199657D758", false)[0]; TokenValidationParameters validationParameters = new TokenValidationParameters() { AllowedAudience = "https://v-lab/craservice", ValidIssuer = "https://v-lab/craservice", // Fetch the signing token from the FederationMetadata document of the tenant. SigningToken = new X509SecurityToken(certificate) }; var claims1 = jwtHandler.ValidateToken(jwtEncodedString, validationParameters); { var configuration = new SecurityTokenHandlerConfiguration(); configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never; configuration.CertificateValidationMode = X509CertificateValidationMode.None; configuration.RevocationMode = X509RevocationMode.NoCheck; configuration.CertificateValidator = X509CertificateValidator.None; var registry = new ConfigurationBasedIssuerNameRegistry(); registry.AddTrustedIssuer("e2fcb96bf877094a510f0b77980048199617d758", "V-LAB.RAYMARKLAB.COM"); configuration.IssuerNameRegistry = registry; jwtHandler.Configuration = configuration; //var claimP = jwtHandler.ValidateToken(jwtEncodedString); var claims = jwtHandler.ValidateToken(sToken); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// { const string relyingPartyId = "https://adfsserver.security.net/MyApp"; //ID of the relying party in AD FS const string adfsEndpoint = "https://adfsserver.security.net/adfs/services/trust/13/windowsmixed"; const string certSubject = "CN=adfsserver.security.net"; //Setup the connection to ADFS var factory = new WSTrustChannelFactory(new WindowsWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(adfsEndpoint)) { TrustVersion = TrustVersion.WSTrust13 }; //Setup the request object var rst = new RequestSecurityToken { RequestType = RequestTypes.Issue, KeyType = KeyTypes.Bearer, AppliesTo = new EndpointReference(relyingPartyId) }; //Open a connection to ADFS and get a token for the logged in user var channel = factory.CreateChannel(); var genericToken = channel.Issue(rst) as GenericXmlSecurityToken; if (genericToken != null) { //Setup the handlers needed to convert the generic token to a SAML Token var tokenHandlers = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] { new SamlSecurityTokenHandler() }); tokenHandlers.Configuration.AudienceRestriction = new AudienceRestriction(); tokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(relyingPartyId)); var trusted = new TrustedIssuerNameRegistry(certSubject); tokenHandlers.Configuration.IssuerNameRegistry = trusted; //convert the generic security token to a saml token var samlToken = tokenHandlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml))); //convert the saml token to a claims principal var claimsPrincipal = new ClaimsPrincipal(tokenHandlers.ValidateToken(samlToken).First()); //Display token information Console.WriteLine("Name : " + claimsPrincipal.Identity.Name); Console.WriteLine("Auth Type : " + claimsPrincipal.Identity.AuthenticationType); Console.WriteLine("Is Authed : " + claimsPrincipal.Identity.IsAuthenticated); foreach (var c in claimsPrincipal.Claims) { Console.WriteLine(c.Type + " / " + c.Value); } Console.ReadLine(); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// { var stsEndpoint = "https://[server]/adfs/services/trust/13/windowstransport"; var relayPartyUri = "https://localhost:8080/WebApp"; var factory = new WSTrustChannelFactory( new WindowsWSTrustBinding(SecurityMode.Transport), new EndpointAddress(stsEndpoint)); factory.TrustVersion = TrustVersion.WSTrust13; var rst = new RequestSecurityToken { RequestType = RequestTypes.Issue, //AppliesTo = new EndpointAddress(relayPartyUri), AppliesTo = new EndpointReference(relayPartyUri), KeyType = KeyTypes.Symmetric }; var channel = factory.CreateChannel(); SecurityToken token = channel.Issue(rst); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// { var stsEndpoint = "https://[server]/adfs/services/trust/13/UsernameMixed"; var relayPartyUri = "https://localhost:8080/WebApp"; var factory = new WSTrustChannelFactory( new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(stsEndpoint)); factory.TrustVersion = TrustVersion.WSTrust13; // Username and Password here... factory.Credentials.UserName.UserName = ""; factory.Credentials.UserName.Password = ""; var rst = new RequestSecurityToken { RequestType = RequestTypes.Issue, //AppliesTo = new EndpointAddress(relayPartyUri), AppliesTo = new EndpointReference(relayPartyUri), KeyType = KeyTypes.Bearer, }; var channel = factory.CreateChannel(); SecurityToken token = channel.Issue(rst); } }
/// <summary> /// Converts a SecurityToken to an IClaimsPrincipal. /// </summary> /// <param name="token">The token.</param> /// <param name="handler">The handler.</param> /// <returns>An IClaimsPrincipal</returns> public static ClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, SecurityTokenHandlerCollection handler) { var ids = handler.ValidateToken(token); return new ClaimsPrincipal(from identity in ids select identity); }
private static void LoginWithToken(AuthenticationHeaderValue credentials, SecurityTokenHandlerCollection handlers, HttpApplication context) { try { var token = Convert.FromBase64String(credentials.Parameter); using (var stream = new MemoryStream(token)) { using (var xmlReader = XmlReader.Create(stream)) { var securityToken = handlers.ReadToken(xmlReader); var identities = handlers.ValidateToken(securityToken); var principal = new ClaimsPrincipal(identities); var identity = principal.Identity as ClaimsIdentity; if (identity != null) identity.BootstrapContext = new BootstrapContext(token); Thread.CurrentPrincipal = principal; context.Context.User = principal; } } } catch (Exception) { context.Response.AppendHeader("X-InvalidCredentials", "token"); throw; } }