// Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(SSOState ssoState) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); string issuerURL = CreateAbsoluteURL("~/"); Issuer issuer = new Issuer(issuerURL); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = ssoState.authnRequest.ID; subjectConfirmationData.Recipient = ssoState.assertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); // Attributes may be included in the SAML assertion. AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold")); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return samlResponse; }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return samlResponse; }
public virtual bool Equals(X509Certificate other) { if (other == null) { return(false); } if (Pal == null) { return(other.Pal == null); } if (!Issuer.Equals(other.Issuer)) { return(false); } byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) { return(false); } for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) { return(false); } } return(true); }
/// <summary> /// Return a JSON representation of this object. /// </summary> /// <param name="CustomPublishTokenTypeSerializer">A delegate to serialize custom publish token type JSON objects.</param> public JObject ToJSON(CustomJObjectSerializerDelegate <PublishTokenType> CustomPublishTokenTypeSerializer = null) { var JSON = JSONObject.Create( new JProperty("uid", Id.ToString()), Type.HasValue ? new JProperty("type", Type.ToString()) : null, VisualNumber.IsNotNullOrEmpty() ? new JProperty("visual_number", VisualNumber) : null, Issuer.IsNotNullOrEmpty() ? new JProperty("issuer", Issuer) : null, GroupId.HasValue ? new JProperty("group_id", GroupId.ToString()) : null ); return(CustomPublishTokenTypeSerializer != null ? CustomPublishTokenTypeSerializer(this, JSON) : JSON); }
public void InitializedAdministrators() { Issuer issuer = new Issuer("test") { AccountId = "accountId", Administrators = { new AdministratorDetails { Email = "*****@*****.**", }, }, }; using JsonStream json = new JsonStream(); using (Utf8JsonWriter writer = json.CreateWriter()) { writer.WriteStartObject(); ((IJsonSerializable)issuer).WriteProperties(writer); writer.WriteEndObject(); } Assert.AreEqual(@"{""credentials"":{""account_id"":""accountId""},""org_details"":{""admin_details"":[{""email"":""*****@*****.**""}]}}", json.ToString()); }
/// <summary> /// Try to update this contract with a serialization object from the API. /// </summary> /// <param name="src">The serializable source.</param> /// <param name="endedContracts">The ended contracts.</param> /// <returns>True if import successful otherwise, false.</returns> internal bool TryImport(SerializableContractListItem src, ICollection <Contract> endedContracts) { // Note that, before a match is found, all contracts have been marked for deletion: // m_markedForDeletion == true bool matches = MatchesWith(src); if (matches) { // Prevent deletion MarkedForDeletion = false; // Contract is from a serialized object, so populate the missing info if (IssuerID == 0L || Issuer.IsEmptyOrUnknown()) { PopulateContractInfo(src); } // Update if modified ContractState state = GetState(src); if (state != m_state || NeedsAttention) { if (state != m_state || Overdue) { m_state = state; UpdateContractInfo(src); } // If the contract has just finished or expired, add it to the ended list if (NeedsAttention || state == ContractState.Finished) { endedContracts.Add(this); } } } return(matches); }
public SecurityTokenDescriptor CreateTokenDescriptor(IEnumerable <Claim> claims, string appliesToAddress, DateTimeOffset tokenIssueTime, int issuedTokenLifetime) { if (Issuer.IsNullOrEmpty()) { throw new ArgumentNullException("Issuer property"); } var subjectClaims = claims.Where(c => c.Type != ClaimTypes.AuthenticationMethod && c.Type != ClaimTypes.AuthenticationInstant && c.Type != ClaimTypes.NameIdentifier && c.Type != Saml2ClaimTypes.NameIdFormat && c.Type != Saml2ClaimTypes.SessionIndex); if (subjectClaims.Count() < 1) { subjectClaims = AddNameIdAsNameClaim(subjectClaims); } var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(subjectClaims), NotBefore = tokenIssueTime.AddSeconds(-settings.SamlTokenAddNotBeforeTime).UtcDateTime, Expires = tokenIssueTime.AddSeconds(issuedTokenLifetime).UtcDateTime, Audience = appliesToAddress, Issuer = Issuer }; return(tokenDescriptor); }
/// <summary> /// Метод возвращает код эмитента /// </summary> /// <param name="issuer">Эмитент</param> /// <returns></returns> public static string GetIssuerCode(Issuer issuer) { switch (issuer) { case Issuer.Fsk: return "FEES"; case Issuer.Gazprom: return "GAZP"; case Issuer.GmkNorNikel: return "GMKN"; case Issuer.Lukoil: return "LKOH"; case Issuer.Mts: return "MTSS"; case Issuer.Rosneft: return "ROSN"; case Issuer.Rostelekom: return "RTKM"; case Issuer.SberbankAo: return "SBER"; case Issuer.SberbankAp: return "SBERP"; case Issuer.Severstal: return "CHMF"; case Issuer.SurgutNfgAo: return "SNGS"; case Issuer.SurgutNfgAp: return "SNGSP"; case Issuer.Vtb: return "VTBR"; } return null; }
/// <summary> /// Creates a rule and adds it to the given RuleGroup. /// </summary> /// <param name = "issuer">The input issuer for which to apply the rule.</param> /// <param name = "inputClaimType">The input claim type. Null for "all claim types".</param> /// <param name = "inputClaimValue">The input claim value. Null for "all claim values".</param> /// <param name = "outputClaimType">The output claim type. Null for "pass through input type".</param> /// <param name = "outputClaimValue">The output claim value. Null for "pass through input value".</param> /// <param name = "ruleGroup">The rule group to which the rule should be added.</param> /// <param name = "description">Optional human-readable rule description.</param> /// <returns></returns> public static Rule CreateRule( this ManagementService svc, Issuer issuer, string inputClaimType, string inputClaimValue, string outputClaimType, string outputClaimValue, RuleGroup ruleGroup, string description) { var rule = new Rule { Description = description, InputClaimType = inputClaimType, InputClaimValue = inputClaimValue, OutputClaimType = outputClaimType, OutputClaimValue = outputClaimValue, }; svc.AddToRules(rule); svc.SetLink(rule, "Issuer", issuer); svc.SetLink(rule, "RuleGroup", ruleGroup); return(rule); }
public bool CheckSignature(X509Cert signer) { if (Issuer.Equals(signer.Subject)) { return(signer.PubKey.Verify(rawTBSCertificate, Signature.Data)); } return(false); }
public bool IsMatch(X509Certificate cert) { bool subjectMatches = Subject.Replace(" ", "").Equals(cert.Subject.Replace(" ", ""), StringComparison.InvariantCulture); bool issuerMatches = Issuer.Replace(" ", "").Equals(cert.Issuer.Replace(" ", ""), StringComparison.InvariantCulture); bool thumbprintMatches = Thumbprint == String.Join(" ", cert.GetCertHash().Select(h => h.ToString("x2"))); return(subjectMatches && issuerMatches && thumbprintMatches); }
public ActionResult DeleteConfirmed(int id) { Issuer issuer = db.Issuer.Find(id); db.Issuer.Remove(issuer); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Create an instance of <see cref="ToolModel"/>. /// </summary> public ToolModel(HttpContext httpContext) { // These are the platform's Identity Server properties Issuer = httpContext.GetIdentityServerIssuerUri(); AuthorizeUrl = Issuer.EnsureTrailingSlash() + "connect/authorize"; JwkSetUrl = Issuer.EnsureTrailingSlash() + ".well-known/openid-configuration/jwks"; TokenUrl = Issuer.EnsureTrailingSlash() + "connect/token"; }
public async Task <IActionResult> ChargeSvc(string cardCode, decimal price) { SVCChargeOperationViewModel svcBody = new SVCChargeOperationViewModel(); svcBody.StoredValueCardCodeCollection.Add(cardCode); svcBody.CashbackType = SVCCashbackType.None; Issuer issuer = new Issuer(); issuer.Name = "Vittorio"; issuer.Address = "via centomani 11"; issuer.Telephone = "0000000"; issuer.EMail = "*****@*****.**"; issuer.VATNumber = "222222"; svcBody.StoredValueCardReceipt.IssuerData = issuer; ReceiptProduct receiptProduct = new ReceiptProduct(); receiptProduct.Code = cardCode; receiptProduct.Name = "VittorioCard"; receiptProduct.Price = price; receiptProduct.Quantity = 1; receiptProduct.Family = ""; receiptProduct.Mode = ""; svcBody.StoredValueCardReceipt.Products.Add(receiptProduct); Payment payment = new Payment(); payment.CardCode = cardCode; svcBody.StoredValueCardReceipt.Payments.Add(payment); ShopReceipt shopReceipt = new ShopReceipt(); shopReceipt.IssueDate = DateTime.Now; shopReceipt.UserData = ""; svcBody.StoredValueCardReceipt.IssueDate = DateTime.Now; svcBody.StoredValueCardReceipt.UserData = ""; SenderData senderData = new SenderData(); senderData.Shop = Constants.SHOP; senderData.Terminal = Constants.TERMINAL; senderData.Type = 0; senderData.Number = 0; senderData.CashDrawer = 0; senderData.Operator = ""; svcBody.StoredValueCardReceipt.SenderData = senderData; var charge = await _svcService.Charge(svcBody); return(View("AssociaCarta", charge)); }
private static XElement SerializaIssuer(Issuer issuer) { XElement issuerElement = new XElement("issuer"); issuerElement.SetAttributeValue("uri", issuer.Uri); issuerElement.SetAttributeValue("thumbprint", issuer.Thumbprint); issuerElement.SetAttributeValue("displayName", issuer.DisplayName); return(issuerElement); }
public IssuerModel SerializeIssuer(Issuer issuer) { var result = new IssuerModel( issuer.Id, issuer.Name ); return(result); }
private void ProcessCommonFields(StringBuilder sb) { if (String40Methods.IsNullOrWhiteSpace(Secret)) { throw new Exception("Secret must be a filled out base32 encoded string"); } string strippedSecret = Secret.Replace(" ", ""); string escapedIssuer = null; string escapedLabel = null; if (!String40Methods.IsNullOrWhiteSpace(Issuer)) { if (Issuer.Contains(":")) { throw new Exception("Issuer must not have a ':'"); } escapedIssuer = Uri.EscapeUriString(Issuer); } if (!String40Methods.IsNullOrWhiteSpace(Label)) { if (Label.Contains(":")) { throw new Exception("Label must not have a ':'"); } escapedLabel = Uri.EscapeUriString(Label); } if (escapedLabel != null) { if (escapedIssuer != null) { escapedLabel = escapedIssuer + ":" + escapedLabel; } } else if (escapedIssuer != null) { escapedLabel = escapedIssuer; } if (escapedLabel != null) { sb.Append(escapedLabel); } sb.Append("?secret=" + strippedSecret); if (escapedIssuer != null) { sb.Append("&issuer=" + escapedIssuer); } if (Digits != 6) { sb.Append("&digits=" + Digits); } }
public async Task <ActionResult> DeleteConfirmed(int id) { Issuer issuer = await db.Issuers.FindAsync(id); db.Issuers.Remove(issuer); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var results = new List <ValidationResult>(); if (Claims?.Where(c => c == "*").Count() > 1) { results.Add(new ValidationResult($"Only one wildcard (*) is allowed in the field {nameof(Claims)}.", new[] { nameof(Claims) })); } if (AuthnResponseBinding == null) { results.Add(new ValidationResult($"The {nameof(AuthnResponseBinding)} field is required.", new[] { nameof(AuthnResponseBinding) })); } if (UpdateState == PartyUpdateStates.Manual) { if (Issuer.IsNullOrEmpty()) { results.Add(new ValidationResult($"The {nameof(Issuer)} field is required.", new[] { nameof(Issuer) })); } if (AuthnUrl.IsNullOrEmpty()) { results.Add(new ValidationResult($"The {nameof(AuthnUrl)} field is required.", new[] { nameof(AuthnUrl) })); } if (AuthnRequestBinding == null) { results.Add(new ValidationResult($"The {nameof(AuthnRequestBinding)} field is required.", new[] { nameof(AuthnRequestBinding) })); } if (!LogoutUrl.IsNullOrWhiteSpace()) { if (LogoutRequestBinding == null) { results.Add(new ValidationResult($"The {nameof(LogoutRequestBinding)} field is required.", new[] { nameof(LogoutRequestBinding) })); } if (LogoutResponseBinding == null) { results.Add(new ValidationResult($"The {nameof(LogoutResponseBinding)} field is required.", new[] { nameof(LogoutResponseBinding) })); } } if (Keys?.Count < Constants.Models.SamlParty.Up.KeysMin) { results.Add(new ValidationResult($"The field {nameof(Keys)} must be at least {Constants.Models.SamlParty.Up.KeysMin}.", new[] { nameof(Keys) })); } } else { if (!MetadataUpdateRate.HasValue) { results.Add(new ValidationResult($"The {nameof(MetadataUpdateRate)} field is required.", new[] { nameof(MetadataUpdateRate) })); } if (MetadataUrl.IsNullOrEmpty()) { results.Add(new ValidationResult($"The {nameof(MetadataUrl)} field is required.", new[] { nameof(MetadataUrl) })); } } return(results); }
// issuerPrivateKey must be set using setIssuerPrivateKey() before calling this method public FirstIssuanceMessageComposite getFirstMessage(string[] attributesParam, IssuerParametersComposite ipc, int numberOfTokensParam, string sessionID, byte[] hd) { /* * token issuance - generate first message */ cOut.write("Issuing U-Prove tokens - generate first message, issuer side"); VerifySessionId(sessionID); try { // specify the attribute values agreed to by the Issuer and Prover int numberOfAttributes = attributesParam.Length; byte[][] attributes = new byte[numberOfAttributes][]; for (int i = 0; i < numberOfAttributes; i++) { attributes[i] = encoding.GetBytes(attributesParam[i]); } IssuerParameters ip = ConvertUtils.convertIssuerParametersComposite(ipc, sessionDB[sessionID]); byte[] issuerPrivateKey = sessionDB[sessionID].privateKey; if (issuerPrivateKey == null) { cOut.write("Issuer side, issuerPrivateKey is null. Did you forget to add the issuer private key for the given sessionKey?"); return(null); } BigInteger bi = new BigInteger(1, issuerPrivateKey); IssuerKeyAndParameters ikap = new IssuerKeyAndParameters(bi, ip); // setup the issuer and generate the first issuance message GroupElement hdG = ip.Gq.CreateGroupElement(hd); Issuer issuer = new Issuer(ikap, numberOfTokensParam, attributes, null, hdG); // Store the issuer in issuersDictionary using the sessionKey as key sessionDB[sessionID].issuer = issuer; FirstIssuanceMessage fi = issuer.GenerateFirstMessage(); // Convert FirstIssuanceMessage members to serializable FirstIssuanceMessageComposite FirstIssuanceMessageComposite fic = ConvertUtils.convertFirstIssuanceMessage(fi); // Add the sessionKey to FirstIssuanceMessageComposite fic.SessionKey = sessionID; return(fic); } catch (Exception e) { cOut.write(e.ToString()); DebugUtils.DebugPrint(e.StackTrace.ToString()); } return(null); }
public ActionResult Edit([Bind(Include = "IdIssuer,NameIssuer,Contact,Address,City,Province,PostalCode,Fone,Email")] Issuer issuer) { if (ModelState.IsValid) { db.Entry(issuer).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(issuer)); }
public async Task <IActionResult> Add([FromBody] Issuer issuer) { issuer = Mapper.Map <Issuer>(await _issuerService.AddAsync(issuer)); return(Created ( uri: $"api/v2/issuers/{issuer.Id}", value: issuer )); }
/// <summary> /// Deletes an <see cref="Issuer"/> having the given name. /// </summary> /// <param name="name">Name of the <see cref="Issuer"/> to delete.</param> public static void DeleteIssuerIfExists(this ManagementService svc, string name) { // Retrieve issuer and delete it if it exists. Issuer issuer = svc.Issuers.Where(m => m.Name == name).FirstOrDefault(); if (issuer != null) { svc.DeleteObject(issuer); } }
public TradeInstrument(string quotesFileName) { string shortFileName = Path.GetFileNameWithoutExtension(quotesFileName); string[] split = shortFileName.Split('_'); Code = split[0].Trim(); _issuer = GetIssuer(Code); Name = GetIssuerName(_issuer); _quotesFileName = quotesFileName; }
protected void btnIdPLogin_Click(object sender, EventArgs e) { // Get the authentication request. Issuer issuer = new Issuer(Global.entityId); AuthnRequest authnRequest = Util.GetAuthnRequest(this); authnRequest.Issuer.NameIdentifier = Global.entityId; // Get SP Resource URL. string spResourceUrl = Util.GetAbsoluteUrl(this, FormsAuthentication.GetRedirectUrl("", false)); // Create relay state. string relayState = Guid.NewGuid().ToString(); // Save the SP Resource URL to the cache. SamlSettings.CacheProvider.Insert(relayState, spResourceUrl, new TimeSpan(1, 0, 0)); switch (Global.SingleSignOnServiceBinding) { case SamlBinding.HttpRedirect: X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SpCertKey]; // Send authentication request using HTTP Redirect. System.Diagnostics.Debug.WriteLine("Sending redirect request to " + Global.SingleSignOnServiceURL); authnRequest.Redirect(Response, Global.SingleSignOnServiceURL, relayState, x509Certificate.PrivateKey, SignatureAlgorithms.RsaSha256); break; case SamlBinding.HttpPost: // Send authentication request using HTTP POST form. System.Diagnostics.Debug.WriteLine("Sending POST request to " + Global.SingleSignOnServiceURL); authnRequest.SendHttpPost(Response, Global.SingleSignOnServiceURL, relayState); // End the response. Response.End(); break; case SamlBinding.HttpArtifact: // Create a new http artifact. string identificationUrl = Util.GetAbsoluteUrl(this, "~/"); Saml2ArtifactType0004 httpArtifact = new Saml2ArtifactType0004(SamlArtifact.GetSourceId(identificationUrl), SamlArtifact.GetHandle()); // Save the authentication request for subsequent sending using the artifact resolution protocol. SamlSettings.CacheProvider.Insert(httpArtifact.ToString(), authnRequest.GetXml(), new TimeSpan(1, 0, 0)); // Send the artifact using HTTP POST form. httpArtifact.SendHttpPost(Response.OutputStream, Global.SingleSignOnServiceURL, relayState); // End the response. Response.End(); break; default: throw new ApplicationException("Invalid binding type"); } }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(Configuration.Issuer); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; // For simplicity, a configured Salesforce user name is used. // NB. You must update the web.config to specify a valid Salesforce user name. // In a real world application you would perform some sort of local to Salesforce identity mapping. Subject subject = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; Conditions conditions = new Conditions(new TimeSpan(1, 0, 0)); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(audienceURI)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified); samlAssertion.Statements.Add(authnStatement); AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx"))); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx"))); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return(samlResponse); }
public override bool ContainsDTO(TEntity entity) { Issuer issuer = entity; return (this.db.Issuers .Any(c => c.CompanyName == issuer.CompanyName && c.Address == issuer.Address )); }
public async Task <ActionResult> Edit([Bind(Include = "issuer_code,issuer_name,issuer_contact_name,issuer_conatct_phone,issuer_email,issuer_desription,issuer_address,issuer_city,issuer_state,issuer_country,view_status,active_status,issuer_geo_data,created_at,updated_at")] Issuer issuer) { if (ModelState.IsValid) { db.Entry(issuer).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(issuer)); }
public void CollaborativeIssuanceTest() { // Issuer setup IssuerSetupParameters isp = new IssuerSetupParameters(); isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; isp.E = new byte[] { (byte)1, (byte)1, (byte)1, (byte)1 }; isp.UseRecommendedParameterSet = true; isp.S = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; IssuerKeyAndParameters ikap = isp.Generate(); IssuerParameters ip = ikap.IssuerParameters; // Issuance byte[][] attributes = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("Attribute 2"), encoding.GetBytes("Attribute 3"), encoding.GetBytes("Attribute 4") }; byte[] tokenInformation = new byte[] { }; byte[] proverInformation = new byte[] { }; int numberOfTokens = 2; // Test cases // 1: CA-RA split (a party trusted by the issuer provides the gamma value) int numTestCases = 1; for (int testCase = 1; testCase <= numTestCases; testCase++) { ProverProtocolParameters ppp = new ProverProtocolParameters(ip); ppp.Attributes = attributes; ppp.NumberOfTokens = numberOfTokens; ppp.TokenInformation = tokenInformation; ppp.ProverInformation = proverInformation; Prover prover = ppp.CreateProver(); IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap); if (testCase == 1) { ipp.Gamma = ProtocolHelper.ComputeIssuanceInput(ip, attributes, tokenInformation, null); } ipp.NumberOfTokens = numberOfTokens; Issuer issuer = ipp.CreateIssuer(); FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage(); SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1); ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2); UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3); // use the token to make sure everything is ok int[] disclosed = new int[0]; byte[] message = encoding.GetBytes("this is the presentation message, this can be a very long message"); FieldZqElement[] unused; byte[] scope = null; PresentationProof proof = PresentationProof.Generate(ip, disclosed, null, 1, scope, message, null, null, upkt[0], attributes, out unused); proof.Verify(ip, disclosed, null, 1, scope, message, null, upkt[0].Token); } }
/// <summary> /// Create a Facebook identity provider with associated keys and permissions configured. /// </summary> /// <param name="applicationId">The Facebook Application ID</param> /// <param name="applicationSecret">The Facebook Application Secret</param> /// <param name="applicationPermissions">The permissions to request from Facebook</param> /// <returns></returns> public static IdentityProvider CreateFacebookIdentityProvider(this ManagementService svc, string applicationId, string applicationSecret, string applicationPermissions) { string name = String.Format(CultureInfo.InvariantCulture, "Facebook-{0}", applicationId); Issuer issuer = new Issuer() { Name = name }; svc.AddToIssuers(issuer); // // Create the Identity Provider // IdentityProvider identityProvider = new IdentityProvider() { DisplayName = name, LoginParameters = applicationPermissions, WebSSOProtocolType = IdentityProviderProtocolType.Facebook.ToString(), }; svc.AddObject("IdentityProviders", identityProvider); svc.SetLink(identityProvider, "Issuer", issuer); // // Create the application Id and application secret keys for this facebook application. // IdentityProviderKey applicationIdKey = new IdentityProviderKey() { DisplayName = "Facebook application ID", Type = IdentityProviderKeyType.ApplicationKey.ToString(), Usage = IdentityProviderKeyUsage.ApplicationId.ToString(), Value = Encoding.UTF8.GetBytes(applicationId), StartDate = DateTime.UtcNow, EndDate = DateTime.MaxValue, }; svc.AddRelatedObject(identityProvider, "IdentityProviderKeys", applicationIdKey); IdentityProviderKey applicationSecretKey = new IdentityProviderKey() { DisplayName = "Facebook application Secret", Type = IdentityProviderKeyType.ApplicationKey.ToString(), Usage = IdentityProviderKeyUsage.ApplicationSecret.ToString(), Value = Encoding.UTF8.GetBytes(applicationSecret), StartDate = DateTime.UtcNow, EndDate = DateTime.MaxValue, }; svc.AddRelatedObject(identityProvider, "IdentityProviderKeys", applicationSecretKey); identityProvider.Issuer = issuer; return(identityProvider); }
public void AddRuleThrowsIfIssuerOfInputClaimDoesNotExists() { var scope = RetrievePolicyScope(); var newIssuer = new Issuer("http://newsampleissuer"); var inputClaim = new InputPolicyClaim(newIssuer, sampleClaimType, "sample value"); var rule = new PolicyRule(AssertionsMatch.Any, new List <InputPolicyClaim> { inputClaim }, GetSampleOutputClaim()); Assert.Throws <PolicyScopeException>(() => scope.AddRule(rule), "The issuer 'http://newsampleissuer' was not found on the issuers section of the scope."); }
public void AddRuleThrowsIfIssuerOfInputClaimDoesNotExists() { var scope = RetrievePolicyScope(); var newIssuer = new Issuer("http://newsampleissuer"); var inputClaim = new InputPolicyClaim(newIssuer, sampleClaimType, "sample value"); var rule = new PolicyRule(AssertionsMatch.Any, new List <InputPolicyClaim> { inputClaim }, GetSampleOutputClaim()); scope.AddRule(rule); }
public ActionResult Create([Bind(Include = "IdIssuer,NameIssuer,Contact,Address,City,Province,PostalCode,Fone,Email")] Issuer issuer) { if (ModelState.IsValid) { db.Issuer.Add(issuer); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(issuer)); }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(Configuration.Issuer); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; // For simplicity, a configured Salesforce user name is used. // NB. You must update the web.config to specify a valid Salesforce user name. // In a real world application you would perform some sort of local to Salesforce identity mapping. Subject subject = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; Conditions conditions = new Conditions(new TimeSpan(1, 0, 0)); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(audienceURI)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified); samlAssertion.Statements.Add(authnStatement); AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx"))); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx"))); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return samlResponse; }
/// <summary> /// Метод возвращает название эмитента /// </summary> /// <param name="issuer">Эмитент</param> /// <returns></returns> public static string GetIssuerName(Issuer issuer) { switch (issuer) { case Issuer.Fsk: return "ФСК"; case Issuer.Gazprom: return "Газпром"; case Issuer.GmkNorNikel: return "ГМКНорНикель"; case Issuer.Lukoil: return "Лукойл"; case Issuer.Mts: return "МТС"; case Issuer.Rosneft: return "Роснефть"; case Issuer.Rostelekom: return "Ростелеком"; case Issuer.SberbankAo: return "Сбербанк ао"; case Issuer.SberbankAp: return "Сбербанк ап"; case Issuer.Severstal: return "Северсталь"; case Issuer.SurgutNfgAo: return "СургутНефтеГаз ао"; case Issuer.SurgutNfgAp: return "СургутНефтеГаз ап"; case Issuer.Vtb: return "ВТБ"; } return null; }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { #region Custom Attributes // If you need to add custom attributes, uncomment the following code var attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("email", SamlAttributeNameFormat.Basic, null, "*****@*****.**")); attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("FirstName", SamlAttributeNameFormat.Basic, null, "John")); attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("LastName", SamlAttributeNameFormat.Basic, null, "Smith")); if (Session["username"] != null && Session["previoususername"] != null) { if (!Session["username"].ToString().ToLower().Equals(Session["previoususername"].ToString().ToLower())) attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("samlsessionstate", SamlAttributeNameFormat.Basic, null, "new")); } #endregion // Set External Account Id for Metanga var externalAccountId = "XAF10964"; if (Session["username"] != null) { externalAccountId = Session["username"].ToString(); } else { Session["username"] = externalAccountId; Session["previoususername"] = externalAccountId; } var consumerServiceUrl = Helper.GetUrl("LinkSelfcareLogin"); // Use the local user's local identity. var subject = new Subject(new NameId(User.Identity.Name)) {NameId = {NameIdentifier = externalAccountId}}; subject.SubjectConfirmations.Add(new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer) { SubjectConfirmationData = new SubjectConfirmationData { Recipient = consumerServiceUrl } }); // Create a new authentication statement. var authnStatement = new AuthnStatement { AuthnContext = new AuthnContext { AuthnContextClassRef = new AuthnContextClassRef(SamlAuthenticateContext.Password) } }; var issuer = new Issuer(GetAbsoluteUrl("~/")); var samlAssertion = new Assertion { Issuer = issuer, Subject = subject }; samlAssertion.Statements.Add(authnStatement); samlAssertion.Statements.Add(attributeStatement); // Get the PFX certificate with Private Key. var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "metangasso.pfx"); const string pwd = "123"; var x509Certificate = new X509Certificate2(filePath, pwd, X509KeyStorageFlags.MachineKeySet); if (!x509Certificate.HasPrivateKey) return; // Create a SAML response object. var samlResponse = new Response { // Assign the consumer service url. Destination = consumerServiceUrl, Issuer = issuer, Status = new Status(SamlPrimaryStatusCode.Success, null) }; // Add assertion to the SAML response object. samlResponse.Assertions.Add(samlAssertion); // Sign the SAML response with the certificate. samlResponse.Sign(x509Certificate); var targetUrl = Helper.GetUrl("LinkSelfcareBilling") + "?SSO=true"; if (Session["SsoLink"] != null) { targetUrl = Session["SsoLink"].ToString(); } // Send the SAML response to the service provider. samlResponse.SendPostBindingForm(Response.OutputStream, consumerServiceUrl, targetUrl); } catch (Exception exception) { Trace.Write("IdentityProvider", "An Error occurred", exception); } }
public static Issuer CreateIssuer(long ID, bool systemReserved) { Issuer issuer = new Issuer(); issuer.Id = ID; issuer.SystemReserved = systemReserved; return issuer; }
private void RedirectWithSAML(string dest) { var FBReturnToken = Session["FBReturnToken"].ToString(); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = WebConfigurationManager.AppSettings["AssertionConsumerServiceURL"]; Issuer issuer = new Issuer( new Uri(Request.Url, Url.Content("~")).ToString()); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); samlResponse.Assertions.Add(new SAMLAssertion(FBReturnToken)); var samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)HttpContext.Application[MvcApplication.DecrypterX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); HttpResponse theResponse = (HttpResponse)HttpContext.GetService(typeof(HttpResponse)); IdentityProvider.SendSAMLResponseByHTTPPost(theResponse, WebConfigurationManager.AppSettings["AssertionConsumerServiceURL"], samlResponseXml, dest); }
public void AddToIssuers(Issuer issuer) { base.AddObject("Issuers", issuer); }
// Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = authnRequest.ID; subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return samlResponse; }