Пример #1
0
		IDictionary<string, string> IExtensionRequest.Serialize(RelyingParty.IAuthenticationRequest authenticationRequest) {
			var fields = new Dictionary<string, string> {
				{ "mode", Mode },
			};
			if (UpdateUrl != null)
				fields.Add("update_url", UpdateUrl.AbsoluteUri);

			List<string> requiredAliases = new List<string>(), optionalAliases = new List<string>();
			AliasManager aliasManager = new AliasManager();
			foreach (var att in attributesRequested) {
				string alias = aliasManager.GetAlias(att.TypeUri);
				// define the alias<->typeUri mapping
				fields.Add("type." + alias, att.TypeUri);
				// set how many values the relying party wants max
				fields.Add("count." + alias, att.Count.ToString(CultureInfo.InvariantCulture));
				if (att.IsRequired)
					requiredAliases.Add(alias);
				else
					optionalAliases.Add(alias);
			}

			// Set optional/required lists
			if (optionalAliases.Count > 0)
				fields.Add("if_available", string.Join(",", optionalAliases.ToArray()));
			if (requiredAliases.Count > 0)
				fields.Add("required", string.Join(",", requiredAliases.ToArray()));

			return fields;
		}
Пример #2
0
		/// <summary>
		/// Called when an authentication request is about to be sent.
		/// </summary>
		/// <param name="request">The request.</param>
		void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
			RelyingParty.AuthenticationRequest requestInternal = (RelyingParty.AuthenticationRequest)request;
			ErrorUtilities.VerifyProtocol(string.Equals(request.Realm.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal) || DisableSslRequirement, BehaviorStrings.RealmMustBeHttps);

			var pape = requestInternal.AppliedExtensions.OfType<PolicyRequest>().SingleOrDefault();
			if (pape == null) {
				request.AddExtension(pape = new PolicyRequest());
			}

			if (!pape.PreferredPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
				pape.PreferredPolicies.Add(AuthenticationPolicies.PrivatePersonalIdentifier);
			}

			if (!pape.PreferredPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1)) {
				pape.PreferredPolicies.Add(AuthenticationPolicies.USGovernmentTrustLevel1);
			}

			if (!AllowPersonallyIdentifiableInformation && !pape.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
				pape.PreferredPolicies.Add(AuthenticationPolicies.NoPersonallyIdentifiableInformation);
			}

			if (pape.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
				ErrorUtilities.VerifyProtocol(
					(!requestInternal.AppliedExtensions.OfType<ClaimsRequest>().Any() &&
					!requestInternal.AppliedExtensions.OfType<FetchRequest>().Any()),
					BehaviorStrings.PiiIncludedWithNoPiiPolicy);
			}

			Reporting.RecordEventOccurrence(this, "RP");
		}
Пример #3
0
        public void Arrange()
        {
            _relyingParty = new RelyingParty
            {
                Id = "MyClient"
            };
            _relyingPartyRepository = new Mock <IRelyingPartyRepository>();
            _relyingPartyRepository.Setup(r => r.GetAllAsync())
            .ReturnsAsync(new[]
            {
                _relyingParty
            });

            _handler = new GetRelyingPartyQueryHandler(_relyingPartyRepository.Object);

            _query = new GetRelyingPartyQuery
            {
                Id = "MyClient"
            };
        }
        /// <summary>
        /// Creates  a new <see cref=" RelyingParty"/>.
        /// </summary>
        /// <param name="name">Name of this new <see cref=" RelyingParty"/>.</param>
        /// <param name="realm">Realm of the relying party.</param>
        /// <param name="reply">ReplyTo address for the relying party. May be null.</param>
        /// <param name="tokenType">The type of token that the relying party consumes.</param>
        /// <param name="requireEncryption">Whether to require asymmetric token encryption.</param>
        /// <returns>The new <see cref=" RelyingParty"/> created.</returns>
        public static RelyingParty CreateRelyingParty(this ManagementService svc, string name, string realm, string reply, RelyingPartyTokenType tokenType, bool requireEncryption)
        {
            svc.DeleteRelyingPartyByRealmIfExists(realm);

            RelyingParty relyingParty = new RelyingParty()
            {
                AsymmetricTokenEncryptionRequired = requireEncryption,
                Name          = name,
                TokenType     = tokenType.ToString(),
                TokenLifetime = 3600,
            };

            svc.AddToRelyingParties(relyingParty);

            //
            // Create the Realm address
            //
            RelyingPartyAddress realmAddress = new RelyingPartyAddress()
            {
                Address      = realm,
                EndpointType = RelyingPartyAddressType.Realm.ToString(),
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realmAddress);

            if (!string.IsNullOrEmpty(reply))
            {
                //
                // Create the ReplyTo address
                //
                RelyingPartyAddress replyAddress = new RelyingPartyAddress()
                {
                    Address      = reply,
                    EndpointType = RelyingPartyAddressType.Reply.ToString(),
                };

                svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", replyAddress);
            }

            return(relyingParty);
        }
Пример #5
0
        static void DisplayRelyingParty(string relyingPartyName)
        {
            Console.WriteLine("\nRetrieve Relying Party (Name = {0})\n", relyingPartyName);

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            // Retrieve Relying Party
            RelyingParty relyingParty = svc.GetRelyingPartyByName(relyingPartyName, true);

            // Display the values of returned Relying Party
            if (relyingParty != null)
            {
                Console.WriteLine("\tId = {0}\n", relyingParty.Id);
                Console.WriteLine("\tName = {0}\n", relyingParty.Name);
                Console.WriteLine("\tDisplayName = {0}\n", relyingParty.DisplayName);
                Console.WriteLine("\tAsymmetricTokenEncryptionRequired = {0}\n", relyingParty.AsymmetricTokenEncryptionRequired);
                Console.WriteLine("\tTokenType = {0}\n", relyingParty.TokenType);
                Console.WriteLine("\tTokenLifetime = {0}\n", relyingParty.TokenLifetime);

                // display keys associated to the Relying Party
                foreach (RelyingPartyKey relyingPartyKey in relyingParty.RelyingPartyKeys.Where(m => m.Type == "X509Certificate"))
                {
                    DisplayRelyingPartyKey(relyingPartyKey);
                }

                // display addresses associated to the Relying Party
                foreach (RelyingPartyAddress relyingPartyAddress in relyingParty.RelyingPartyAddresses.ToList())
                {
                    DisplayRelyingPartyAddress(relyingPartyAddress);
                }

                Console.WriteLine("\tRule Groups:\n");

                foreach (RelyingPartyRuleGroup relyingPartyRuleGroup in svc
                         .RelyingPartyRuleGroups.Expand("RuleGroup")
                         .Where(r => r.RelyingPartyId == relyingParty.Id))
                {
                    Console.WriteLine("\t\tName: {0}\n", relyingPartyRuleGroup.RuleGroup.Name);
                }
            }
        }
Пример #6
0
        public void RemoveRelyingParty(string relyingPartyName)
        {
            try
            {
                var client = this.CreateManagementServiceClient();

                RelyingParty relyingParty = client.RelyingParties
                                            .Where(m => m.Name == relyingPartyName)
                                            .FirstOrDefault();

                if (relyingParty != null)
                {
                    client.DeleteObject(relyingParty);
                    client.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw TryGetExceptionDetails(ex);
            }
        }
        private void RemoveRelatedKeys(RelyingParty rpToRemove, ManagementService client, Action <LogInfo> logAction)
        {
            var pendingChanges = false;

            foreach (var key in rpToRemove.RelyingPartyKeys)
            {
                RelyingPartyKey keyLocal    = key;
                var             keyToRemove = client.RelyingPartyKeys.Where(
                    k => k.DisplayName.Equals(keyLocal.DisplayName)).Single();

                this.LogMessage(logAction, string.Format("Removing Key '{0}'", keyLocal.DisplayName));
                client.DeleteObject(keyToRemove);

                pendingChanges = true;
            }

            if (pendingChanges)
            {
                client.SaveChanges(SaveChangesOptions.Batch);
                this.LogSavingChangesMessage(logAction);
            }
        }
Пример #8
0
        public bool TryGet(string realm, out RelyingParty relyingParty)
        {
            relyingParty = null;

            using (var entities = IdentityServerConfigurationContext.Get())
            {
                var match = (from rp in entities.RelyingParties
                             where rp.Realm.Equals(realm, StringComparison.OrdinalIgnoreCase) &&
                             rp.Enabled == true
                             orderby rp.Realm descending
                             select rp)
                            .FirstOrDefault();

                if (match != null)
                {
                    relyingParty = match.ToDomainModel();
                    return(true);
                }
            }

            return(false);
        }
        public static RelyingPartyEntity ToEntity(this RelyingParty model, string id, string partitionKey)
        {
            var entity = new RelyingPartyEntity
            {
                PartitionKey = partitionKey,
                RowKey       = id,
                RealmHost    = model.Realm.DnsSafeHost.ToLowerInvariant(),
                RealmPath    = model.Realm.PathAndQuery.ToLowerInvariant(),
                Description  = model.Name,
                ExtraData1   = model.ExtraData1 ?? "",
                ExtraData2   = model.ExtraData2 ?? "",
                ExtraData3   = model.ExtraData3 ?? "",
            };

            if (model.ReplyTo != null)
            {
                entity.ReplyToAddress = model.ReplyTo.AbsoluteUri;
            }
            else
            {
                entity.ReplyToAddress = "";
            }

            if (model.EncryptingCertificate != null)
            {
                entity.EncryptingCertificate = Convert.ToBase64String(model.EncryptingCertificate.RawData);
            }

            if (model.SymmetricSigningKey != null && model.SymmetricSigningKey.Length != 0)
            {
                entity.SymmetricSigningKey = Convert.ToBase64String(model.SymmetricSigningKey);
            }
            else
            {
                entity.SymmetricSigningKey = "";
            }

            return(entity);
        }
Пример #10
0
        public static RuleGroup AddPassthroughRule(this ManagementService svc,
                                                   RelyingParty relyingParty, string ruleGroupName)
        {
            Contract.Requires(svc != null);
            Contract.Requires(relyingParty != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(ruleGroupName));

            var ruleGroup = new RuleGroup()
            {
                Name = ruleGroupName
            };

            svc.AddToRuleGroups(ruleGroup);

            svc.SaveChanges(SaveChangesOptions.Batch);

            var localAuthority = svc.Issuers.Where(
                m => m.Name == "LOCAL AUTHORITY").FirstOrDefault();

            var passthrough = new Rule();

            passthrough.Description = "Passthough all ACS claims";

            svc.AddToRules(passthrough);
            svc.SetLink(passthrough, "RuleGroup", ruleGroup);
            svc.SetLink(passthrough, "Issuer", localAuthority);

            var rprg = new RelyingPartyRuleGroup();

            svc.AddToRelyingPartyRuleGroups(rprg);

            svc.AddLink(relyingParty, "RelyingPartyRuleGroups", rprg);
            svc.AddLink(ruleGroup, "RelyingPartyRuleGroups", rprg);

            svc.SaveChanges(SaveChangesOptions.Batch);

            return(ruleGroup);
        }
        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            var tuple = e.Parameter as Tuple <Config, Uri, Guid>;

            if (tuple == null)
            {
                textOutput.Text = "";
                return;
            }
            // authorization response
            var config   = tuple.Item1;
            var response = tuple.Item2;
            var state    = tuple.Item3;

            // show authorization response
            textOutput.Text = response.ToString();
            // get access token with authorization code
            TokenResponse accessToken = await RelyingParty.GetAccessToken(config, response, state);

            if (accessToken == null)
            {
                return;
            }
            // show access token
            textOutput.Text = accessToken.AccessToken;
            // get userinfo with access token
            UserInfo userinfo = await RelyingParty.GetUserInfo(config, accessToken);

            if (userinfo == null)
            {
                return;
            }
            // show email or username
            textOutput.Text = string.IsNullOrWhiteSpace(userinfo.Mail)
                ? userinfo.UserName
                : userinfo.Mail;
        }
Пример #12
0
        static void UpdateSampleRelyingParty(string relyingPartyName)
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            // Retrieve Relying Party and then delete it
            RelyingParty relyingParty = svc.RelyingParties.Expand("RelyingPartyAddresses").Where(m => m.Name == relyingPartyName).FirstOrDefault();

            if (relyingParty != null)
            {
                // update DisplayName
                relyingParty.DisplayName = "TestRelyingPartyNewDisplayName";
                //update Realm
                RelyingPartyAddress realm = relyingParty.RelyingPartyAddresses.Where(m => m.EndpointType == "Realm").FirstOrDefault();
                if (realm != null)
                {
                    realm.Address = "http://TestRelyingParty/NewRealm";
                    svc.UpdateObject(realm);
                }

                svc.UpdateObject(relyingParty);
                svc.SaveChangesBatch();
            }
        }
        public bool TryGet(string realm, out RelyingParty relyingParty)
        {
            relyingParty = null;

            using (var entities = IdentityServerConfigurationContext.Get())
            {
                var strippedRealm = realm.StripProtocolMoniker();

                var bestMatch = (from rp in entities.RelyingParties
                                 where strippedRealm.Contains(rp.Realm)
                                 orderby rp.Realm descending
                                 select rp)
                                .FirstOrDefault();

                if (bestMatch != null)
                {
                    relyingParty = bestMatch.ToDomainModel();
                    return(true);
                }
            }

            return(false);
        }
Пример #14
0
        public bool TryGet(string realm, out RelyingParty relyingParty)
        {
            relyingParty = null;

            var rps           = GetRelyingPartiesForServer(realm);
            var strippedRealm = realm.ToLowerInvariant().StripProtocolMoniker();

            var bestMatch =
                (from rp in rps
                 let strippedConfig = rp.Realm.AbsoluteUri.ToLowerInvariant().StripProtocolMoniker()
                                      where strippedRealm.Contains(strippedConfig)
                                      orderby rp.Realm.AbsoluteUri.Length descending
                                      select rp)
                .FirstOrDefault();

            if (bestMatch != null)
            {
                relyingParty = bestMatch;
                return(true);
            }

            return(false);
        }
Пример #15
0
        /// <summary>
        /// Configures the ACS service namespace with the proper objects for this sample.
        /// </summary>
        /// <remarks>
        /// Existing objects that are needed for this sample will be deleted and recreated.
        /// </remarks>
        static void Main(string[] args)
        {
            const string rpName                  = "ASPNET Simple Service";
            const string rpRealm                 = "http://localhost:8000/Service/";
            const string serviceIdentityName     = "acssample";
            const string serviceIdentityPassword = "******";
            const string ruleGroupName           = "Default rule group for ASPNET Simple Service";

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            svc.DeleteRelyingPartyByRealmIfExists(rpRealm);
            svc.DeleteServiceIdentityIfExists(serviceIdentityName);
            svc.DeleteRuleGroupByNameIfExists(ruleGroupName);
            svc.SaveChangesBatch();

            RelyingParty relyingParty = svc.CreateRelyingParty(rpName, rpRealm, rpRealm, RelyingPartyTokenType.SWT, false);

            RelyingPartyKey relyingPartyKey = svc.GenerateRelyingPartySymmetricKey(relyingParty, DateTime.UtcNow, DateTime.UtcNow.AddYears(1), true);

            Console.WriteLine("Generated symmetric key value: {0}", Convert.ToBase64String(relyingPartyKey.Value));

            svc.CreateServiceIdentity(serviceIdentityName, Encoding.UTF8.GetBytes(serviceIdentityPassword), ServiceIdentityKeyType.Password, ServiceIdentityKeyUsage.Password);

            RuleGroup ruleGroup = svc.CreateRuleGroup(ruleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            //
            // Add a rule to issue the "action=reverse" claim.
            //
            svc.CreateRule(svc.GetIssuerByName("LOCAL AUTHORITY"), null, null, "action", "reverse", ruleGroup, "Issue action=reverse claim.");
            svc.SaveChangesBatch();

            Console.WriteLine("Sample successfully configured. Press ENTER to continue ...");
            Console.ReadLine();
        }
        public async Task AddAsync_WhenRelyingPartyHasPublicEncryptionCert_ExpectEncryptionCertReturned(DbContextOptions <WsFederationConfigurationDbContext> options)
        {
            // arrange
            var certToStore = new X509Certificate2("Resources/idsrv3test.cer");
            var entity      = new RelyingParty
            {
                Realm = Guid.NewGuid().ToString(),
                EncryptionCertificate = certToStore.GetRawCertData()
            };

            // act
            using (var ctx = new WsFederationConfigurationDbContext(options))
            {
                await ctx.RelyingParties.AddAsync(entity);

                await ctx.SaveChangesAsync();
            }

            // assert
            RelyingParty foundEntity;

            using (var ctx = new WsFederationConfigurationDbContext(options))
            {
                foundEntity = ctx.RelyingParties.FirstOrDefault(x => x.Realm == entity.Realm);
            }

            foundEntity.Should().NotBeNull();
            foundEntity.EncryptionCertificate.Should().NotBeNull();

            var parsedCert = new X509Certificate2(entity.EncryptionCertificate);

            parsedCert.Should().NotBeNull();
            parsedCert.Thumbprint.Should().Be(certToStore.Thumbprint);
            parsedCert.SubjectName.Name.Should().Be(certToStore.SubjectName.Name);
            parsedCert.HasPrivateKey.Should().Be(certToStore.HasPrivateKey);
        }
Пример #17
0
        static void Main(string[] args)
        {
            const string ClientName    = "OAuth2SampleX509Identity";
            const string RPRealm       = "https://oauth2RelyingParty/";
            const string RPName        = "OAuth2 RP";
            const string RuleGroupName = "Default rule group for OAuth2 RP";

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            svc.DeleteServiceIdentityIfExists(ClientName);
            svc.DeleteRelyingPartyByRealmIfExists(RPRealm);
            svc.DeleteRuleGroupByNameIfExists(RuleGroupName);

            svc.SaveChangesBatch();

            X509Certificate2 clientCertificate = new X509Certificate2(@"..\..\..\Certificates\ACS2ClientCertificate.cer");

            svc.CreateServiceIdentity(ClientName, clientCertificate.RawData, ServiceIdentityKeyType.X509Certificate, ServiceIdentityKeyUsage.Signing);

            RelyingParty    relyingParty    = svc.CreateRelyingParty(RPName, RPRealm, null, RelyingPartyTokenType.SWT, false);
            RelyingPartyKey relyingPartyKey = svc.GenerateRelyingPartySymmetricKey(relyingParty, DateTime.UtcNow, DateTime.MaxValue, true);

            Console.WriteLine("Generated symmetric key: {0}", Convert.ToBase64String(relyingPartyKey.Value));

            Issuer    localAuthority = svc.GetIssuerByName("LOCAL AUTHORITY");
            RuleGroup ruleGroup      = svc.CreateRuleGroup(RuleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            svc.CreateRule(localAuthority, null, null, null, null, ruleGroup, "Pass through claims issued by ACS");

            svc.SaveChangesBatch();

            Console.WriteLine("Sample configured successfully. Press <ENTER> to exit...");
            Console.ReadLine();
        }
        private ActionResult SaveRP(string id, RelyingParty rp, RPCertInputModel cert)
        {
            if (cert.RemoveCert == true)
            {
                rp.EncryptingCertificate = null;
            }
            else if (cert.Cert != null)
            {
                rp.EncryptingCertificate = cert.Cert;
            }
            else
            {
                var origRP = this.RelyingPartyRepository.Get(id);
                rp.EncryptingCertificate = origRP.EncryptingCertificate;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    this.RelyingPartyRepository.Update(rp);
                    TempData["Message"] = Resources.RPController.UpdateSuccessful;
                    return(RedirectToAction("RP", new { id }));
                }
                catch (ValidationException ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
                catch
                {
                    ModelState.AddModelError("", Resources.RPController.ErrorUpdatingRelyingParty);
                }
            }

            return(View("RP", rp));
        }
Пример #19
0
        public static AccessControlList GetAccessControlList(Uri relyingPartyUri, AccessControlSettings settings)
        {
            string localPath = relyingPartyUri.LocalPath;

            relyingPartyUri =
                new UriBuilder(relyingPartyUri)
            {
                Scheme = "http", Port = -1, Path = localPath.Substring(0, localPath.EndsWith("/") ? localPath.Length - 1 : localPath.Length)
            }.Uri;

            string              relyingPartyAddress    = relyingPartyUri.AbsoluteUri;
            ManagementService   serviceClient          = ManagementServiceHelper.CreateManagementServiceClient(settings);
            RelyingPartyAddress longestPrefixRpAddress = GetLongestPrefixRelyingPartyAddress(serviceClient, relyingPartyAddress);

            if (longestPrefixRpAddress != null)
            {
                RelyingParty relyingParty = GetRelyingPartyByAddress(serviceClient, longestPrefixRpAddress);
                if (relyingParty != null)
                {
                    return(new AccessControlList(relyingPartyUri, relyingParty, serviceClient));
                }
            }
            throw new InvalidOperationException();
        }
        public static RelyingParties ToEntity(this RelyingParty relyingParty)
        {
            var rpEntity = new RelyingParties
            {
                Name          = relyingParty.Name,
                Enabled       = relyingParty.Enabled,
                Realm         = relyingParty.Realm.AbsoluteUri,
                TokenType     = relyingParty.TokenType,
                TokenLifeTime = relyingParty.TokenLifeTime,
                ExtraData1    = relyingParty.ExtraData1,
                ExtraData2    = relyingParty.ExtraData2,
                ExtraData3    = relyingParty.ExtraData3,
            };

            if (!string.IsNullOrEmpty(relyingParty.Id))
            {
                rpEntity.Id = int.Parse(relyingParty.Id);
            }

            if (relyingParty.ReplyTo != null)
            {
                rpEntity.ReplyTo = relyingParty.ReplyTo.AbsoluteUri;
            }

            if (relyingParty.EncryptingCertificate != null)
            {
                rpEntity.EncryptingCertificate = Convert.ToBase64String(relyingParty.EncryptingCertificate.RawData);
            }

            if (relyingParty.SymmetricSigningKey != null && relyingParty.SymmetricSigningKey.Length != 0)
            {
                rpEntity.SymmetricSigningKey = Convert.ToBase64String(relyingParty.SymmetricSigningKey);
            }

            return(rpEntity);
        }
Пример #21
0
        private static void AddSigningKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] symmetricKey, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
            {
                DisplayName  = "Signing Key for " + relyingPartyName,
                Type         = KeyType.Symmetric.ToString(),
                Usage        = KeyUsage.Signing.ToString(),
                Value        = symmetricKey,
                RelyingParty = relyingParty,
                StartDate    = defaultStartDate,
                EndDate      = defaultEndDate,
                IsPrimary    = true
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
Пример #22
0
        private static void AddSigningKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] signingCert, string signingCertPassword, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
            {
                DisplayName  = "Signing Certificate for " + relyingPartyName,
                Type         = KeyType.X509Certificate.ToString(),
                Usage        = KeyUsage.Signing.ToString(),
                Value        = signingCert,
                Password     = string.IsNullOrEmpty(signingCertPassword) ? null : new UTF8Encoding().GetBytes(signingCertPassword),
                RelyingParty = relyingParty,
                StartDate    = defaultStartDate,
                EndDate      = defaultEndDate,
                IsPrimary    = true
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
Пример #23
0
        private static void AddIdentityProviderToRelyingParty(ManagementService client, string[] allowedIdentityProviders, RelyingParty relyingParty)
        {
            // if no allowed identity providers were set, allow all
            if (allowedIdentityProviders == null)
            {
                allowedIdentityProviders = client.IdentityProviders.ToList().Select(idp => idp.DisplayName).ToArray();
            }

            foreach (var allowedIdp in allowedIdentityProviders)
            {
                var idp = client.IdentityProviders
                          .Where(i => i.DisplayName.Equals(allowedIdp, StringComparison.OrdinalIgnoreCase))
                          .FirstOrDefault();

                if (idp != null)
                {
                    var rpidp = new RelyingPartyIdentityProvider
                    {
                        IdentityProviderId = idp.Id,
                        RelyingPartyId     = relyingParty.Id
                    };

                    client.AddToRelyingPartyIdentityProviders(rpidp);
                    client.SaveChanges();
                }
            }
        }
Пример #24
0
        private static void AddEncryptionKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] encryptionCert, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
            {
                DisplayName  = "Encryption Certificate for " + relyingPartyName,
                Type         = KeyType.X509Certificate.ToString(),
                Usage        = KeyUsage.Encrypting.ToString(),
                Value        = encryptionCert,
                RelyingParty = relyingParty,
                StartDate    = defaultStartDate,
                EndDate      = defaultEndDate
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
		/// <summary>
		/// Tries to find the exact format of AX attribute Type URI supported by the Provider.
		/// </summary>
		/// <param name="request">The authentication request.</param>
		/// <param name="attributeFormat">The attribute formats the RP will try if this discovery fails.</param>
		/// <returns>The AX format(s) to use based on the Provider's advertised AX support.</returns>
		private static bool TryDetectOPAttributeFormat(RelyingParty.IAuthenticationRequest request, out AXAttributeFormats attributeFormat) {
			Requires.NotNull(request, "request");
			attributeFormat = OpenIdExtensionsInteropHelper.DetectAXFormat(request.DiscoveryResult.Capabilities);
			return attributeFormat != AXAttributeFormats.None;
		}
Пример #26
0
        private static Dictionary <string, RelyingParty> .ValueCollection ReadWid(string dbName, SqlConnection conn)
        {
            Dictionary <string, RelyingParty> rps = new Dictionary <string, RelyingParty>();

            SqlDataReader reader = null;

            try
            {
                string     readEncryptedPfxQuery = string.Format(ReadEncryptedPfxQuery, dbName);
                SqlCommand cmd = new SqlCommand(readEncryptedPfxQuery, conn);
                reader = cmd.ExecuteReader();
            } catch (Exception e)
            {
                Console.WriteLine("!!! Exception: {0}", e);
                return(null);
            }

            Console.WriteLine("## Reading Encrypted Signing Key from Database");
            while (reader.Read())
            {
                string xmlString = (string)reader["ServiceSettingsData"];

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xmlString);

                XmlElement root = xmlDocument.DocumentElement;

                XmlElement signingToken = root.GetElementsByTagName("SigningToken")[0] as XmlElement;
                if (signingToken != null)
                {
                    XmlNode encryptedPfx = signingToken.GetElementsByTagName("EncryptedPfx")[0];
                    Console.WriteLine("[-] Encrypted Token Signing Key Begin\r\n{0}\r\n[-] Encrypted Token Signing Key End\r\n", encryptedPfx.InnerText);
                }

                Console.WriteLine("## Reading The Issuer Identifier");

                XmlElement issuer = root.GetElementsByTagName("Issuer")[0] as XmlElement;
                if (issuer != null)
                {
                    XmlNode issuerAddress = issuer.GetElementsByTagName("Address")[0];
                    Console.WriteLine("[-] Issuer Identifier: {0}", issuerAddress.InnerText);
                }
            }
            reader.Close();

            // enumerate scopes and policies
            try
            {
                string readScopePolicies = "";
                switch (dbName)
                {
                case Adfs2012R2:
                    Console.WriteLine("[-] Detected AD FS 2012");
                    readScopePolicies = string.Format(ReadScopePoliciesLegacy, dbName);
                    break;

                case Adfs2016:
                    Console.WriteLine("[-] Detected AD FS 2016");
                    readScopePolicies = string.Format(ReadScopePolicies, dbName);
                    break;

                case Adfs2019:
                    Console.WriteLine("[-] Detected AD FS 2019");
                    Console.WriteLine("[-] Uncharted territory! This might not work...");
                    readScopePolicies = string.Format(ReadScopePolicies, dbName);
                    break;

                default:
                    Console.WriteLine("!!! Couldn't determine AD FS version. Found database {0}.\n Quitting", dbName);
                    break;
                }

                SqlCommand cmd = new SqlCommand(readScopePolicies, conn);
                reader = cmd.ExecuteReader();
            }
            catch (Exception e)
            {
                Console.WriteLine("!!! Exception: {0}", e);
                return(null);
            }

            Console.WriteLine("## Reading Relying Party Trust Information from Database");
            while (reader.Read())
            {
                string name = reader.SafeGetString("Name");
                if (!BuiltInScopes.Any(name.Contains))
                {
                    string       scopeId = reader["ScopeId"].ToString();
                    RelyingParty rp      = new RelyingParty {
                        Name = name, Id = scopeId
                    };
                    rp.IsEnabled          = (bool)reader["Enabled"];
                    rp.SignatureAlgorithm = reader.SafeGetString("SignatureAlgorithm");
                    if (dbName != Adfs2012R2)
                    {
                        rp.AccessPolicy = reader.SafeGetString("PolicyMetadata");
                        if (!reader.IsDBNull(9))
                        {
                            rp.AccessPolicyParam = reader.SafeGetString("ParameterInterface");
                        }
                    }

                    rp.Identity = reader.SafeGetString("IdentityData");

                    if (!reader.IsDBNull(2))
                    {
                        rp.IsSaml             = false;
                        rp.IsWsFed            = true;
                        rp.FederationEndpoint = reader.SafeGetString("WSFederationPassiveEndpoint");
                    }
                    else
                    {
                        rp.IsSaml             = true;
                        rp.IsWsFed            = false;
                        rp.FederationEndpoint = reader.SafeGetString("Location");
                    }

                    if (!reader.IsDBNull(6))
                    {
                        rp.EncryptionCert = reader.SafeGetString("EncryptionCertificate");
                    }

                    rp.SamlResponseSignatureType = (int)reader["SamlResponseSignatureType"];
                    rps[scopeId] = rp;
                }
            }
            reader.Close();

            try
            {
                string     readRules = string.Format(ReadRules, dbName);
                SqlCommand cmd       = new SqlCommand(readRules, conn);
                reader = cmd.ExecuteReader();
            }
            catch (Exception e)
            {
                Console.WriteLine("!!! Exception: {0}", e);
                return(null);
            }

            while (reader.Read())
            {
                string scopeId = reader["ScopeId"].ToString();
                string rule    = reader.SafeGetString("PolicyData");
                if (rps.Keys.Contains(scopeId) && !string.IsNullOrEmpty(rule))
                {
                    PolicyType ruleType = (PolicyType)reader["PolicyUsage"];
                    switch (ruleType)
                    {
                    case PolicyType.StrongAuthAuthorizationRules:
                        rps[scopeId].StrongAuthRules = rule;
                        break;

                    case PolicyType.OnBehalfAuthorizationRules:
                        rps[scopeId].OnBehalfAuthRules = rule;
                        break;

                    case PolicyType.ActAsAuthorizationRules:
                        rps[scopeId].AuthRules = rule;
                        break;

                    case PolicyType.IssuanceRules:
                        rps[scopeId].IssuanceRules = rule;
                        break;
                    }
                }
            }
            reader.Close();
            conn.Close();
            return(rps.Values);
        }
 public static RelyingParty CreateRelyingParty(long ID, int tokenLifetime, bool asymmetricTokenEncryptionRequired, bool systemReserved)
 {
     RelyingParty relyingParty = new RelyingParty();
     relyingParty.Id = ID;
     relyingParty.TokenLifetime = tokenLifetime;
     relyingParty.AsymmetricTokenEncryptionRequired = asymmetricTokenEncryptionRequired;
     relyingParty.SystemReserved = systemReserved;
     return relyingParty;
 }
Пример #28
0
		/// <summary>
		/// Tries to find the exact format of AX attribute Type URI supported by the Provider.
		/// </summary>
		/// <param name="request">The authentication request.</param>
		/// <param name="attributeFormat">The attribute formats the RP will try if this discovery fails.</param>
		/// <returns>The AX format(s) to use based on the Provider's advertised AX support.</returns>
		private static bool TryDetectOPAttributeFormat(RelyingParty.IAuthenticationRequest request, out AXAttributeFormats attributeFormat) {
			Contract.Requires<ArgumentNullException>(request != null);
			attributeFormat = DetectAXFormat(request.DiscoveryResult.Capabilities);
			return attributeFormat != AXAttributeFormats.None;
		}
Пример #29
0
        IDictionary<string, string> IExtensionRequest.Serialize(RelyingParty.IAuthenticationRequest authenticationRequest)
        {
            var fields = new Dictionary<string, string> {
                { "mode", Mode },
            };

            FetchResponse.SerializeAttributes(fields, attributesProvided);

            return fields;
        }
Пример #30
0
		/// <summary>
		/// Called when an authentication request is about to be sent.
		/// </summary>
		/// <param name="request">The request.</param>
		/// <remarks>
		/// Implementations should be prepared to be called multiple times on the same outgoing message
		/// without malfunctioning.
		/// </remarks>
		void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
			// Don't create AX extensions for OpenID 1.x messages, since AX requires OpenID 2.0.
			if (request.Provider.Version.Major >= 2) {
				request.SpreadSregToAX(this.AXFormats);
			}
		}
Пример #31
0
 /// <summary>
 /// Tries to find the exact format of AX attribute Type URI supported by the Provider.
 /// </summary>
 /// <param name="request">The authentication request.</param>
 /// <param name="attributeFormat">The attribute formats the RP will try if this discovery fails.</param>
 /// <returns>The AX format(s) to use based on the Provider's advertised AX support.</returns>
 private static bool TryDetectOPAttributeFormat(RelyingParty.IAuthenticationRequest request, out AXAttributeFormats attributeFormat)
 {
     Contract.Requires(request != null);
     var provider = (RelyingParty.ServiceEndpoint)request.Provider;
     attributeFormat = DetectAXFormat(provider.ProviderDescription.Capabilities);
     return attributeFormat != AXAttributeFormats.None;
 }
Пример #32
0
        public async Task <SignInValidationResult> ValidateAsync(WsFederationMessage message, ClaimsPrincipal user)
        {
            //Logger.Info("Start WS-Federation signin request validation");
            var result = new SignInValidationResult
            {
                WsFederationMessage = message
            };

            // check client
            var client = await _clients.FindEnabledClientByIdAsync(message.Wtrealm);

            if (client == null)
            {
                LogError("Client not found: " + message.Wtrealm, result);

                return(new SignInValidationResult
                {
                    Error = "invalid_relying_party"
                });
            }
            if (client.ProtocolType != IdentityServerConstants.ProtocolTypes.WsFederation)
            {
                LogError("Client is not configured for WS-Federation", result);

                return(new SignInValidationResult
                {
                    Error = "invalid_relying_party"
                });
            }

            result.Client   = client;
            result.ReplyUrl = client.RedirectUris.First();

            // check if additional relying party settings exist
            var rp = await _relyingParties.FindRelyingPartyByRealm(message.Wtrealm);

            if (rp == null)
            {
                rp = new RelyingParty
                {
                    TokenType                = _options.DefaultTokenType,
                    SignatureAlgorithm       = _options.DefaultSignatureAlgorithm,
                    DigestAlgorithm          = _options.DefaultDigestAlgorithm,
                    SamlNameIdentifierFormat = _options.DefaultSamlNameIdentifierFormat,
                    ClaimMapping             = _options.DefaultClaimMapping
                };
            }

            result.RelyingParty = rp;

            if (user == null ||
                user.Identity.IsAuthenticated == false)
            {
                result.SignInRequired = true;
            }

            result.User = user;

            LogSuccess(result);
            return(result);
        }
Пример #33
0
		/// <summary>
		/// Adds a description of the information the relying party site would like
		/// the Provider to include with a positive authentication assertion as an
		/// extension to an authentication request.
		/// </summary>
		IDictionary<string, string> IExtensionRequest.Serialize(RelyingParty.IAuthenticationRequest request) {
			var fields = new Dictionary<string, string>();
			if (PolicyUrl != null)
				fields.Add(Constants.policy_url, PolicyUrl.AbsoluteUri);

			fields.Add(Constants.required, string.Join(",", assembleProfileFields(DemandLevel.Require)));
			fields.Add(Constants.optional, string.Join(",", assembleProfileFields(DemandLevel.Request)));

			return fields;
		}
Пример #34
0
        private static void CreateRelyingParty(ManagementService client, string relyingPartyName, string ruleGroupName, string realmAddress, string replyAddress, TokenType tokenType, int tokenLifetime, bool asymmetricTokenEncryptionRequired, out RelyingParty relyingParty)
        {
            // Create Relying Party
            relyingParty = new RelyingParty
            {
                Name          = relyingPartyName,
                DisplayName   = relyingPartyName,
                Description   = relyingPartyName,
                TokenType     = tokenType.ToString(),
                TokenLifetime = tokenLifetime,
                AsymmetricTokenEncryptionRequired = asymmetricTokenEncryptionRequired
            };

            client.AddObject("RelyingParties", relyingParty);
            client.SaveChanges();

            if (!string.IsNullOrWhiteSpace(ruleGroupName))
            {
                RuleGroup ruleGroup = client.RuleGroups.Where(rg => rg.Name.Equals(ruleGroupName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (ruleGroup == null)
                {
                    ruleGroup = new RuleGroup
                    {
                        Name = ruleGroupName
                    };

                    client.AddToRuleGroups(ruleGroup);
                    client.SaveChanges();
                }

                var relyingPartyRuleGroup = new RelyingPartyRuleGroup
                {
                    RuleGroupId  = ruleGroup.Id,
                    RelyingParty = relyingParty
                };

                client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
            }

            // Create the Realm for Relying Party
            var realm = new RelyingPartyAddress
            {
                Address      = realmAddress,
                EndpointType = RelyingPartyAddressEndpointType.Realm.ToString(),
                RelyingParty = relyingParty
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realm);

            if (!string.IsNullOrEmpty(replyAddress))
            {
                var reply = new RelyingPartyAddress
                {
                    Address      = replyAddress,
                    EndpointType = RelyingPartyAddressEndpointType.Reply.ToString(),
                    RelyingParty = relyingParty
                };

                client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", reply);
            }

            client.SaveChanges(SaveChangesOptions.Batch);
        }
 public void AddToRelyingParties(RelyingParty relyingParty)
 {
     base.AddObject("RelyingParties", relyingParty);
 }
Пример #36
0
        /// <summary>
        /// Configures the ACS service namespace with the proper objects for this sample.
        /// </summary>
        /// <remarks>
        /// Existing objects that are needed for this sample will be deleted and recreated.
        /// </remarks>
        static void Main(string[] args)
        {
            const string rpName    = "ASPNET MVC3 Custom Sign-In Page Sample";
            const string rpRealm   = "http://localhost:64000/";
            const string rpReplyTo = "http://localhost:64000/Account/SignIn";

            const string facebookName = "Facebook";
            const string yahooName    = "Yahoo!";

            const string defaultRuleGroupName = "Default rule group for ASPNET MVC3 Custom Sign-In Page Sample";

            // Please update these with your own Facebook application information
            const string applicationId     = "applicationid";
            const string applicationSecret = "applicationsecret";

            string facebookIdpName = String.Format(CultureInfo.InvariantCulture, "Facebook-{0}", applicationId);

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            //
            // Clean up pre-existing configuration
            //
            svc.DeleteRelyingPartyByRealmIfExists(rpRealm);
            svc.DeleteRuleGroupByNameIfExists(defaultRuleGroupName);
            svc.DeleteIdentityProviderIfExists(facebookIdpName);
            svc.DeleteIdentityProviderIfExists(yahooName);
            svc.SaveChangesBatch();

            //
            // Create Identity Providers
            //
            IdentityProvider live = svc.GetIdentityProviderByName("uri:WindowsLiveID");;

            IdentityProvider facebook = svc.CreateFacebookIdentityProvider(applicationId, applicationSecret, "email,user_events");

            SetSignInInformation(svc, facebook, facebookName);

            IdentityProvider yahoo = svc.CreateOpenIdIdentityProvider(yahooName, "https://open.login.yahooapis.com/openid/op/auth");

            SetSignInInformation(svc, yahoo, yahooName);

            IdentityProvider[] associatedProviders = new[] { live, facebook, yahoo };

            //
            // Create Relying Party
            //
            RelyingParty relyingParty = svc.CreateRelyingParty(rpName, rpRealm, rpReplyTo, RelyingPartyTokenType.SAML_2_0, false);

            svc.AssociateIdentityProvidersWithRelyingParties(associatedProviders, new[] { relyingParty });

            RuleGroup ruleGroup = svc.CreateRuleGroup(defaultRuleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            //
            // Create simple rules to pass through all claims from each issuer.
            //
            foreach (IdentityProvider identityProvider in associatedProviders)
            {
                string ruleDescription = string.Format(CultureInfo.InvariantCulture, "Pass through all claims from '{0}'", identityProvider.Issuer.Name);
                svc.CreateRule(identityProvider.Issuer, null, null, null, null, ruleGroup, ruleDescription);
            }
            svc.SaveChangesBatch();

            Console.WriteLine("Sample successfully configured. Press ENTER to continue ...");
            Console.ReadLine();
        }
Пример #37
0
 public void Add(RelyingParty relyingParty)
 {
     NewContext.AddRelyingParty(relyingParty.ToEntity());
 }
Пример #38
0
        private IActionResult LoginResponse(Saml2Id inResponseTo, Saml2StatusCodes status, string relayState, RelyingParty relyingParty, string sessionIndex = null, IEnumerable <Claim> claims = null)
        {
            var responsebinding = new Saml2PostBinding();

            responsebinding.RelayState = relayState;

            var saml2AuthnResponse = new Saml2AuthnResponse(GetLoginSaml2Config(relyingParty))
            {
                InResponseTo = inResponseTo,
                Status       = status,
                Destination  = relyingParty.SingleSignOnDestination,
            };

            if (status == Saml2StatusCodes.Success && claims != null)
            {
                saml2AuthnResponse.SessionIndex = sessionIndex;

                var claimsIdentity = new ClaimsIdentity(claims);
                saml2AuthnResponse.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent);
                //saml2AuthnResponse.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single());
                saml2AuthnResponse.ClaimsIdentity = claimsIdentity;

                _ = saml2AuthnResponse.CreateSecurityToken(relyingParty.Issuer);
            }

            return(responsebinding.Bind(saml2AuthnResponse).ToActionResult());
        }
		/// <summary>
		/// Called when an authentication request is about to be sent.
		/// </summary>
		/// <param name="request">The request.</param>
		/// <remarks>
		/// Implementations should be prepared to be called multiple times on the same outgoing message
		/// without malfunctioning.
		/// </remarks>
		void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
			request.SpreadSregToAX(AXFormats);
		}
Пример #40
0
        private IActionResult LogoutResponse(Saml2Id inResponseTo, Saml2StatusCodes status, string relayState, string sessionIndex, RelyingParty relyingParty)
        {
            var responsebinding = new Saml2PostBinding();

            responsebinding.RelayState = relayState;

            var saml2LogoutResponse = new Saml2LogoutResponse(saml2Config)
            {
                InResponseTo = inResponseTo,
                Status       = status,
                Destination  = relyingParty.SingleLogoutResponseDestination,
                SessionIndex = sessionIndex
            };

            return(responsebinding.Bind(saml2LogoutResponse).ToActionResult());
        }
Пример #41
0
 public void Update(RelyingParty relyingParty)
 {
     NewContext.UpdateRelyingParty(relyingParty.ToEntity(relyingParty.Id));
 }