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; } }
public static SecurityToken DeSerializeSecurityToken(string tokenString, string issuerThumbPrint, string issuerThumbprintName) { XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(tokenString)); SecurityTokenHandlerConfiguration conf = new SecurityTokenHandlerConfiguration() { SaveBootstrapContext = true }; conf.AudienceRestriction.AudienceMode = AudienceUriMode.Never; ConfigurationBasedIssuerNameRegistry actAsRegistry = new ConfigurationBasedIssuerNameRegistry(); actAsRegistry.AddTrustedIssuer(issuerThumbPrint, issuerThumbPrint); conf.IssuerNameRegistry = actAsRegistry; List <SecurityToken> tokens = new List <SecurityToken>() { new X509SecurityToken(Constants.DefaultCertificate) }; conf.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection <SecurityToken>(tokens), true); SecurityTokenHandlerCollection handlers = new SecurityTokenHandlerCollection(conf) { new X509CertificateSessionSecurityTokenHandler(Constants.DefaultCertificate), new UserNameTokenHandler(), new SamlTokenHandler(), new EncryptedSecurityTokenHandler() }; return(handlers.ReadToken(xmlTextReader)); }
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 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); }
private SecurityToken ReadSecurityToken(string tokenString, SecurityTokenHandlerCollection handlers) { using (var reader = new XmlTextReader(new StringReader(tokenString))) { var token = handlers.ReadToken(reader); return(token); } }
private SecurityToken ReadToken(string text) { using (XmlReader reader = XmlReader.Create(new StringReader(text))) { reader.MoveToContent(); SecurityTokenHandlerCollection handlers = _federationConfiguration.IdentityConfiguration.SecurityTokenHandlers; return(handlers.CanReadToken(reader) ? handlers.ReadToken(reader) : null); } }
private SecurityToken ReadToken(XmlReader reader) { SecurityTokenHandlerCollection securityTokenHandlers = this._serviceConfiguration.IdentityConfiguration.SecurityTokenHandlers; if (securityTokenHandlers.CanReadToken(reader)) { return(securityTokenHandlers.ReadToken(reader)); } return(null); }
public GenericXmlSecurityToken AuthenticateSaml(string incomingToken, string appliesTo) { // turn string saml token into SecurityToken var samlToken = _handler.ReadToken(new XmlTextReader(new StringReader(incomingToken))); // validate saml token var identity = ValidateSamlToken(samlToken); return(Authenticate(identity, appliesTo)); }
/// <summary>Turns a supported generic XML security token into a security token.</summary> /// <param name="token">The generic XML security token.</param> /// <param name="handler">The security token handler.</param> /// <returns>A SecurityToken</returns> public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token, SecurityTokenHandlerCollection handler) { var xmlTextReader = new XmlTextReader(new StringReader(token.TokenXml.OuterXml)); if (handler.CanReadToken(xmlTextReader)) { return(handler.ReadToken(xmlTextReader)); } throw new InvalidOperationException("Unsupported token type"); }
SecurityToken ReadXmlToken(string tokenXml) { using (StringReader strReader = new StringReader(tokenXml)) { using (XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(strReader))) { reader.MoveToContent(); return(_handlers.ReadToken(reader)); } } }
/// <summary> /// Deserialize the Assertion /// </summary> /// <param name="rawAssertion"></param> /// <returns></returns> protected Saml2SecurityToken DeserializeAssertion(string rawAssertion) { Saml2SecurityToken assertion; using (var reader = XmlReader.Create(new StringReader(rawAssertion))) { reader.ReadToFollowing("Assertion", AssertionURN); SecurityTokenHandlerCollection thc = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); assertion = (Saml2SecurityToken)thc.ReadToken(reader.ReadSubtree()); } return(assertion); }
/// <summary> /// Turns a supported generic XML security token to a security token. /// </summary> /// <param name="token">The generic XML security token.</param> /// <param name="handler">The security token handler.</param> /// <returns>A SecurityToken</returns> public static SecurityToken ToSecurityToken(this GenericXmlSecurityToken token, SecurityTokenHandlerCollection handler) { var reader = new XmlTextReader(new StringReader(token.TokenXml.OuterXml)); if (handler.CanReadToken(reader)) { return handler.ReadToken(reader); } else { throw new InvalidOperationException("Unsupported token type"); } }
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> /// Reads a <see cref="SecurityToken"/> from the provided XML representation. /// </summary> /// <param name="securityTokenXml">The XML representation of the security token.</param> /// <param name="securityTokenHandlers">The <see cref="SecurityTokenHandlerCollection"/> used to /// read the token.</param> /// <returns>A <see cref="SecurityToken"/>.</returns> protected virtual SecurityToken ReadSecurityToken(XmlElement securityTokenXml, SecurityTokenHandlerCollection securityTokenHandlers) { SecurityToken securityToken = null; XmlReader reader = new XmlNodeReader(securityTokenXml); reader.MoveToContent(); securityToken = securityTokenHandlers.ReadToken(reader); if (securityToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4051, securityTokenXml, reader.LocalName, reader.NamespaceURI))); } return securityToken; }
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 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; } }
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)); }
public ActionResult Index(FormCollection collection) { try { string dataInBase64 = collection[0].ToString(); if (String.IsNullOrEmpty(dataInBase64)) { Log.Error("Si è verificato un errore sulla decodificazione della risposta"); return(View("Error")); } byte[] data = System.Convert.FromBase64String(dataInBase64); string base64DecodedASCII = System.Text.Encoding.UTF8.GetString(data); Log.Debug(base64DecodedASCII); XmlDocument xml = new XmlDocument(); xml.PreserveWhitespace = true; xml.LoadXml(base64DecodedASCII); if (SigningHelper.VerifySignature(xml, Log)) { string backUrl = String.Empty; string requestQueryString = String.Empty; string appQueryString = String.Empty; string finalbackUrl = String.Empty; if (System.Web.HttpContext.Current.Request.Cookies[ConfigurationManager.AppSettings["SPID_COOKIE"]] != null) { Guid idRequestSPID = Guid.Parse(System.Web.HttpContext.Current.Request.Cookies[ConfigurationManager.AppSettings["SPID_COOKIE"]].Value.ToString()); Log.Info("Cookie ID Richiesta: " + idRequestSPID); } else { Log.Warn("Attenzione Cookie non trovato"); } Saml2SecurityToken token = null; Dictionary <string, string> spidUserInfo = new Dictionary <string, string>(); AppUser appUser = new AppUser(); using (StringReader sr = new StringReader(base64DecodedASCII)) { using (XmlReader reader = XmlReader.Create(sr)) { reader.ReadToFollowing("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion"); // Deserialize the token so that data can be taken from it and plugged into the RSTR SecurityTokenHandlerCollection coll = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); var tempToken = reader.ReadSubtree(); token = (Saml2SecurityToken)coll.ReadToken(tempToken); spidUserInfo.Add("Esito", "true"); foreach (var item in token.Assertion.Statements) { var type = item.GetType(); if (type.Name == "Saml2AttributeStatement") { foreach (var attr in ((System.IdentityModel.Tokens.Saml2AttributeStatement)item).Attributes) { if (attr.Name.ToLower() == "fiscalnumber" && !String.IsNullOrEmpty(attr.Values.First())) { spidUserInfo.Add(attr.Name, attr.Values.First().Split('-')[1]); } if (attr.Name.ToLower() == "ivaCode" && !String.IsNullOrEmpty(attr.Values.First())) { spidUserInfo.Add(attr.Name, attr.Values.First().Split('-')[1]); } if (attr.Name.ToLower() != "fiscalnumber" && attr.Name.ToLower() != "ivaCode" && !String.IsNullOrEmpty(attr.Values.First())) { spidUserInfo.Add(attr.Name, attr.Values.First()); } if (attr.Name.ToLower() == "name" && !String.IsNullOrEmpty(attr.Values.First())) { appUser.Name = attr.Values.First(); } if (attr.Name.ToLower() == "familyname" && !String.IsNullOrEmpty(attr.Values.First())) { appUser.Surname = attr.Values.First(); } } } } } Session.Add("AppUser", appUser); ViewData["UserInfo"] = spidUserInfo; HttpCookie requestCookie = new HttpCookie("SPID_AUTHENTICATION"); requestCookie.Expires = DateTime.Now.AddMinutes(20); requestCookie.Value = "true"; System.Web.HttpContext.Current.Response.Cookies.Add(requestCookie); return(View("UserData")); } } else { return(View("Error")); } } catch (Exception ex) { Log.Error("Si è verificato un Errore durante l'elaborazione della risposta", ex); return(View("Error")); } }
public ActionResult Index(FormCollection collection) { Guid idRequest; String codicefiscaleIva = ""; HttpContext CurrentContext = _contextAccessor.HttpContext; string spidCookieName = _spidOptions.CookieId; try { string dataBaseInBase64 = collection.First().ToString(); if (String.IsNullOrEmpty(dataBaseInBase64)) { Log.Error("Si è verificato un errore"); return(View("Error")); } byte[] data = System.Convert.FromBase64String(dataBaseInBase64); string base64DecodedASCII = System.Text.Encoding.UTF8.GetString(data); Log.Debug(base64DecodedASCII); XmlDocument xml = new XmlDocument { PreserveWhitespace = true }; xml.LoadXml(base64DecodedASCII); if (SigningHelper.VerifySignature(xml, Log)) { string backUrl = String.Empty; string requestQueryString = String.Empty; string appQueryString = String.Empty; string finalbackUrl = String.Empty; if (CurrentContext.Request.Cookies[spidCookieName] != null) { // TODO: use coockie // idRequest = Guid.Parse(CurrentContext.Request.Cookies[spidCookieName].Value.ToString()); idRequest = Guid.NewGuid(); Log.Info("Recupero Richiesta: " + idRequest); } else { Log.Warn("Cookie non trovato, impossibile proseguire."); } Saml2SecurityToken token = null; Dictionary <string, string> userInfo = new Dictionary <string, string>(); using (StringReader sr = new StringReader(base64DecodedASCII)) { using (XmlReader reader = XmlReader.Create(sr)) { reader.ReadToFollowing("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion"); // Deserialize the token so that data can be taken from it and plugged into the RSTR SecurityTokenHandlerCollection coll = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); var tempToken = reader.ReadSubtree(); token = (Saml2SecurityToken)coll.ReadToken(tempToken); userInfo.Add("Esito", "true"); foreach (var item in token.Assertion.Statements) { var type = item.GetType(); if (type.Name == "Saml2AttributeStatement") { foreach (var attr in ((System.IdentityModel.Tokens.Saml2AttributeStatement)item).Attributes) { if (attr.Name.ToLower() == "fiscalnumber" && !String.IsNullOrEmpty(attr.Values.First())) { codicefiscaleIva = attr.Values.First().Split('-')[1]; userInfo.Add(attr.Name, attr.Values.First().Split('-')[1]); } if (attr.Name.ToLower() == "ivaCode" && !String.IsNullOrEmpty(attr.Values.First())) { codicefiscaleIva = attr.Values.First().Split('-')[1]; userInfo.Add(attr.Name, attr.Values.First().Split('-')[1]); } if (attr.Name.ToLower() != "fiscalnumber" && attr.Name.ToLower() != "ivaCode" && !String.IsNullOrEmpty(attr.Values.First())) { userInfo.Add(attr.Name, attr.Values.First()); } } } } } } ViewData["UserInfo"] = userInfo; return(View("UserData")); } else { ViewData["Message"] = "Ci dispiace ma si è verificato un errore."; return(View("Error")); } } catch (Exception ex) { Log.Error("Si è verificato un Errore durante il Processamento della risposta", ex); return(View("Error")); } }
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); } }