public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = SubscriptionId.GetHashCode();
         hashCode = (hashCode * 397) ^ (TenantId != null ? TenantId.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ResourceGroup != null ? ResourceGroup.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (WebApp != null ? WebApp.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Hosts != null ? Hosts.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Email != null ? Email.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ ClientId.GetHashCode();
         hashCode = (hashCode * 397) ^ (ClientSecret != null ? ClientSecret.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ServicePlanResourceGroup != null ? ServicePlanResourceGroup.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (SiteSlotName != null ? SiteSlotName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ UseIpBasedSsl.GetHashCode();
         hashCode = (hashCode * 397) ^ RsaKeyLength;
         hashCode = (hashCode * 397) ^ (AcmeBaseUri != null ? AcmeBaseUri.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ RenewXNumberOfDaysBeforeExpiration;
         hashCode = (hashCode * 397) ^ (AuthenticationUri != null ? AuthenticationUri.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (AzureTokenAudience != null ? AzureTokenAudience.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (AzureManagementEndpoint != null ? AzureManagementEndpoint.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (AzureDefaultWebsiteDomainName != null ? AzureDefaultWebsiteDomainName.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #2
0
        public async Task <bool> Handle(SaveClientSecretCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return(false);
            }

            var client = await _clientRepository.FindByClientIdAsync(request.ClientId);

            if (client == null)
            {
                await _bus.RaiseEvent(new DomainNotification("key_not_found", $"Client named {request.ClientId} not found"));

                return(false);
            }

            var secret = new ClientSecret
            {
                Client      = client,
                Description = request.Description,
                Expiration  = request.Expiration,
                Type        = request.Type,
                Value       = request.GetHashValue()
            };
            await _clientSecretRepository.AddAsync(secret);

            if (Commit())
            {
                await _bus.RaiseEvent(new ClientSecretAddedEvent(request.ClientId, secret.Id, secret.Value, secret.Type, secret.Description));

                return(true);
            }
            return(false);
        }
Пример #3
0
        public async Task <AccessToken?> RequestTokenAsync(
            IConsoleOutput output,
            CancellationToken cancellationToken)
        {
            if (Token.HasValue())
            {
                string?scheme = null;

                if (!NoScheme.HasValue())
                {
                    scheme = Scheme.HasValue() ? Scheme.Value() !.Trim() : _defaultScheme;
                }

                return(new AccessToken(
                           Token.Value() !.Trim(),
                           scheme));
            }

            if (TokenEndpoint.HasValue() || ClientId.HasValue() || ClientSecret.HasValue())
            {
                using IActivity activity = output.WriteActivity("Request token");
                ValidateOAuthArguments(activity);
                IEnumerable <string> scopes = Scopes.HasValue()
                    ? Enumerable.Empty <string>()
                    : Scopes.Values.Where(t => t is { }).OfType <string>();
Пример #4
0
        public async Task <IActionResult> AddClientSecret([FromRoute] string clientId, [FromBody] CreateSecretRequest request)
        {
            var client = await _configurationDbContext.Clients.SingleOrDefaultAsync(x => x.ClientId == clientId);

            if (client == null)
            {
                return(NotFound());
            }
            var newSecret = new ClientSecret {
                Description = request.Description,
                Value       = request.Value.ToSha256(),
                Expiration  = request.Expiration,
                Type        = IdentityServerConstants.SecretTypes.SharedSecret,
                ClientId    = client.Id
            };

            client.ClientSecrets = new List <ClientSecret> {
                newSecret
            };
            await _configurationDbContext.SaveChangesAsync();

            return(CreatedAtAction(string.Empty, new SecretInfo {
                Id = newSecret.Id,
                Description = newSecret.Description,
                Expiration = newSecret.Expiration,
                Type = newSecret.Type,
                Value = GetClientSecretValue(newSecret)
            }));
        }
        public async Task <ClientSecretGenerateCommandResult> Handle(ClientSecretGenerateCommand request, CancellationToken cancellationToken)
        {
            var secret = Guid.NewGuid().ToString().Replace("-", "");

            var clientSecret = new ClientSecret
            {
                Value       = secret,
                Description = request.Description,
                Created     = DateTime.UtcNow,
                Expiration  = request.ExpirationDateUtc
            };

            var client = await _context.Clients.FirstOrDefaultAsync(x => x.ClientId.Equals(request.ClientId, StringComparison.OrdinalIgnoreCase));

            if (client == default)
            {
                throw new ApplicationException($"Client with the ClientId [{request.ClientId}] cannot be found.");
            }

            client.ClientSecrets.Add(clientSecret);
            await _context.SaveChangesAsync(cancellationToken);


            return(new ClientSecretGenerateCommandResult
            {
                Secret = secret
            });
        }
Пример #6
0
        public void AddClientSecret(ClientSecretDto clientPropertyDto)
        {
            ClientSecret clientProperty = clientPropertyDto.ToEntity();

            this.Session.Save(clientProperty);
            this.Session.Flush();
        }
Пример #7
0
        /// <summary>
        /// Merges the explicitly provided values with the extra object
        /// </summary>
        /// <param name="explicitValues">The explicit values.</param>
        /// <param name="extra">The extra.</param>
        /// <returns></returns>
        public Dictionary <string, string> Merge(Dictionary <string, string> explicitValues, object extra = null)
        {
            var merged = explicitValues;

            if (AuthenticationStyle == AuthenticationStyle.PostValues)
            {
                merged.Add(OidcConstants.TokenRequest.ClientId, ClientId);

                if (ClientSecret.IsPresent())
                {
                    merged.Add(OidcConstants.TokenRequest.ClientSecret, ClientSecret);
                }
            }

            var additionalValues = ValuesHelper.ObjectToDictionary(extra);

            if (additionalValues != null)
            {
                merged =
                    explicitValues.Concat(additionalValues.Where(add => !explicitValues.ContainsKey(add.Key)))
                    .ToDictionary(final => final.Key, final => final.Value);
            }

            return(merged);
        }
Пример #8
0
 public async Task <int> DeleteClientSecretAsync(ClientSecret clientSecret)
 {
     using (var dbContext = ConnectionDatabase.Get(_configuration))
     {
         return(await dbContext.ExecuteAsync("delete from ClientSecrets where id=@Id", new { clientSecret.Id }));
     }
 }
Пример #9
0
        public async Task Handle(SaveClientSecretCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return;
            }

            var savedClient = await _clientRepository.GetByClientId(request.ClientId);

            if (savedClient == null)
            {
                await Bus.RaiseEvent(new DomainNotification("1", "Client not found"));

                return;
            }

            var secret = new ClientSecret
            {
                Client      = savedClient,
                Description = request.Description,
                Expiration  = request.Expiration,
                Type        = request.Type,
                Value       = request.GetValue()
            };

            _clientSecretRepository.Add(secret);

            if (Commit())
            {
                await Bus.RaiseEvent(new NewClientSecretEvent(request.Id, request.ClientId, secret.Type, secret.Description));
            }
        }
Пример #10
0
        private void AddOrUpdateClientSecret(Client currentClient, string modelClientSecretDescription)
        {
            // Ensure the client secrets collection is not null
            if (currentClient.ClientSecrets == null)
            {
                currentClient.ClientSecrets = new List <ClientSecret>();
            }

            // Currently, the api works with only one client secret.
            ClientSecret currentClientSecret = currentClient.ClientSecrets.FirstOrDefault();

            // Add new secret
            if ((currentClientSecret != null && currentClientSecret.Description != modelClientSecretDescription) ||
                currentClientSecret == null)
            {
                // Remove all secrets as we may have only one valid.
                currentClient.ClientSecrets.Clear();

                currentClient.ClientSecrets.Add(new ClientSecret()
                {
                    Client      = currentClient,
                    Value       = modelClientSecretDescription.Sha256(),
                    Type        = IdentityServerConstants.ParsedSecretTypes.SharedSecret,
                    Description = modelClientSecretDescription
                });
            }
        }
        public virtual IEnumerable <string> GetValidationErrors()
        {
            if (Authority.IsMissing() && TokenEndpoint.IsMissing())
            {
                yield return($"You must either set {nameof(Authority)} or {nameof(TokenEndpoint)}.");
            }

            if (ClientId.IsMissing())
            {
                yield return($"You must set {nameof(ClientId)}.");
            }

            if (ClientSecret.IsMissing())
            {
                yield return($"You must set {nameof(ClientSecret)}.");
            }

            if (AuthorityHttpClientName.IsMissing())
            {
                yield return($"You must set {nameof(AuthorityHttpClientName)}.");
            }

            if (Events == null)
            {
                yield return($"You must set {nameof(Events)}.");
            }
        }
Пример #12
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,ClientId,Description,Expiration,Type,Value")] ClientSecret clientSecret)
        {
            if (id != clientSecret.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    clientSecret.Value = clientSecret.Value.Sha256();

                    _context.Update(clientSecret);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClientSecretExists(clientSecret.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index"));
            }
            ViewData["ClientId"] = new SelectList(_context.Clients, "Id", "ClientId", clientSecret.ClientId);
            return(View(clientSecret));
        }
Пример #13
0
        public override async Task <ActionResult <InsertClientSecretResponse> > HandleAsync(InsertClientSecretRequest request,
                                                                                            CancellationToken cancellationToken = default)
        {
            var toaster    = new ToasterEvent(nameof(ClientSecret), ToasterType.Success, ToasterVerbs.Created);
            var validation =
                await _validator.ValidateAsync <InsertClientSecretRequest, InsertClientSecretResponse, InsertRequestValidator>
                    (request, toaster, cancellationToken);

            if (validation.Failed)
            {
                return(validation.Response);
            }

            if (_repository.Query().Any(e => e.Value == request.Value && e.Type != AppConstants.SecretTypes.VisibleOneTime))
            {
                return(AspExtensions.GetBadRequestWithError <InsertClientSecretResponse>("This client secret already exists."));
            }

            var entity = new ClientSecret
            {
                Created     = DateTime.UtcNow,
                Description = request.Description,
                Type        = request.Type,
                Expiration  = request.Expiration,
                Value       = request.Value.Stamp(),
                ClientId    = request.OwnerId
            };

            await _repository.InsertAsync(entity);

            await _repository.SaveAsync(toaster);

            return(validation.Response);
        }
Пример #14
0
        public async Task <ClientSecret> AddClientSecret(ClientSecret secret)
        {
            _context.ClientSecrets.Add(secret);
            await _context.SaveChangesAsync();

            return(secret);
        }
Пример #15
0
 public async Task OnGetAsync(int apiResourceId, int id)
 {
     TenantId = _sessionTenantAccessor.TenantId;
     ClientId = apiResourceId;
     SecretId = id;
     Secret   = await _adminServices.GetClientSecretByIdAsync(TenantId, ClientId, SecretId);
 }
 public static ClientSecret Copy(this ClientSecret clientSecret)
 {
     return(new ClientSecret
     {
         Type = clientSecret.Type,
         Value = clientSecret.Value
     });
 }
        /// <summary>
        /// Creates the secret.
        /// </summary>
        /// <returns></returns>
        /// 创建人:李允智
        /// 创建时间:2016/1/29
        /// 描述:生成APP ID APP Secret
        public string CreateSecret()
        {
            ClientSecret clientSecret = new ClientSecret();

            clientSecret.clientid     = ComHelper.GetGuid();
            clientSecret.clientsecret = ComHelper.GetSecret();
            return(JsonHelper.SerializeObject(clientSecret));
        }
Пример #18
0
 public override int GetHashCode()
 {
     return(Username.GetHashCode() ^
            Password.GetHashCode() ^
            ClientId.GetHashCode() ^
            ClientSecret.GetHashCode() ^
            UserAgent.GetHashCode());
 }
Пример #19
0
        public virtual async Task <int> DeleteClientSecretAsync(ClientSecret clientSecret)
        {
            var secretToDelete = await DbContext.ClientSecrets.Where(x => x.Id == clientSecret.Id).SingleOrDefaultAsync();

            DbContext.ClientSecrets.Remove(secretToDelete);

            return(await AutoSaveChangesAsync());
        }
 public ClientSecretViewModel(ClientSecret clientSecret)
 {
     this.Id          = clientSecret.Id;
     this.Description = clientSecret.Description;
     this.Expiration  = clientSecret.Expiration;
     this.Type        = clientSecret.Type;
     this.DateCreated = clientSecret.Created;
 }
Пример #21
0
        public async Task <IActionResult> AddClientSecret(string clientId, [FromForm] ClientSecret clientSecret)
        {
            clientSecret.Value = clientSecret.Value.ToSha512();

            await adminClientStore.AddClientSecretAsync(clientId, clientSecret);

            return(View("ClientSecrets", await adminClientStore.FindClientByIdAsync(clientId)));
        }
Пример #22
0
        /// <summary>
        /// Initializes the Authentication Provider
        /// </summary>
        /// <param name="options">The options to use</param>
        internal override void Init(PnPCoreAuthenticationCredentialConfigurationOptions options)
        {
            // We need the OnBehalfOf options
            if (options.OnBehalfOf == null)
            {
                throw new ConfigurationErrorsException(
                          PnPCoreAuthResources.OnBehalfOfAuthenticationProvider_InvalidConfiguration);
            }

            // We need the certificate thumbprint
            if (string.IsNullOrEmpty(options.OnBehalfOf.ClientSecret) && string.IsNullOrEmpty(options.OnBehalfOf.Thumbprint))
            {
                throw new ConfigurationErrorsException(PnPCoreAuthResources.OnBehalfOfAuthenticationProvider_InvalidClientSecretOrCertificate);
            }

            ClientId = !string.IsNullOrEmpty(options.ClientId) ? options.ClientId : AuthGlobals.DefaultClientId;
            TenantId = !string.IsNullOrEmpty(options.TenantId) ? options.TenantId : AuthGlobals.OrganizationsTenantId;
            if (!string.IsNullOrEmpty(options.OnBehalfOf.Thumbprint))
            {
                // We prioritize the X.509 certificate, if any
                Certificate = X509CertificateUtility.LoadCertificate(
                    options.OnBehalfOf.StoreName,
                    options.OnBehalfOf.StoreLocation,
                    options.OnBehalfOf.Thumbprint);
            }
            else if (!string.IsNullOrEmpty(options.OnBehalfOf.ClientSecret))
            {
                // Otherwise we fallback to the client secret
                ClientSecret = options.OnBehalfOf.ClientSecret.ToSecureString();
            }

            if (Certificate != null)
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(ClientId)
                                                .WithCertificate(Certificate)
                                                .WithPnPAdditionalAuthenticationSettings(
                    options.OnBehalfOf.AuthorityUri,
                    options.OnBehalfOf.RedirectUri,
                    TenantId)
                                                .Build();
            }
            else
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(ClientId)
                                                .WithClientSecret(ClientSecret.ToInsecureString())
                                                .WithPnPAdditionalAuthenticationSettings(
                    options.OnBehalfOf.AuthorityUri,
                    options.OnBehalfOf.RedirectUri,
                    TenantId)
                                                .Build();
            }

            // Log the initialization information
            Log?.LogInformation(PnPCoreAuthResources.OnBehalfOfAuthenticationProvider_LogInit);
        }
Пример #23
0
        /// <summary>
        /// Retrieves the hash code for the credential.
        /// </summary>
        ///
        /// <returns>
        /// The hash code for the credential.
        /// </returns>
        public override int GetHashCode()
        {
            if (string.IsNullOrWhiteSpace(ClientId) || string.IsNullOrWhiteSpace(ClientSecret))
            {
                return(base.GetHashCode());
            }

            return(unchecked (ClientId.GetHashCode() ^ ClientSecret.GetHashCode()));
        }
Пример #24
0
        public async Task GiveMeAName()
        {
            // Arrange
            const string WebHostUrl = "http://localhost:3501";

            const string ClientId     = "ClientId";
            const string ClientSecret = "secret";
            const string Scope        = "Resource";


            var env = Environment.Setup(e =>
            {
                e.GenericHost(h =>
                {
                    h.IdSvr4();
                });
            });
            await env.StartAsync();

            await using (var configId = await env.ConfigureAsync(c =>
            {
                c.IdSvr4(i =>
                {
                    i.Client(cl =>
                    {
                        cl.ClientId = ClientId;
                        cl.AllowedGrantTypes = IdentityServer4.Models.GrantTypes.ClientCredentials;
                        cl.Secret(ClientSecret.Sha256());
                        cl.AccessTokenType = AccessTokenType.Jwt;
                        cl.Scope(Scope);
                    });
                    i.ApiResource(new ApiResource(Scope, Scope));
                });
            }))
            {
                var verifier = await env.VerifyAsync(c =>
                                                     c.Expect(
                                                         c.IdSvr4().EventOccurred <ClientAuthenticationSuccessEvent>(e => e.ClientId == ClientId),
                                                         e => e.MustOccurWithin(TimeSpan.FromMilliseconds(500))));

                var idSvr4Client = env.IdSvr4Client();

                await idSvr4Client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
                {
                    ClientId     = ClientId,
                    ClientSecret = ClientSecret,
                    Scope        = Scope
                });

                var verificationResult = await verifier.VerifyAsync();

                Assert.That(verificationResult.ExpectationsMet, Is.True);
            }

            await env.StopAsync();
        }
Пример #25
0
        public virtual async Task <int> AddClientSecretAsync(int clientId, ClientSecret clientSecret)
        {
            var client = await DbContext.Clients.Where(x => x.Id == clientId).SingleOrDefaultAsync();

            clientSecret.Client = client;

            await DbContext.ClientSecrets.AddAsync(clientSecret);

            return(await AutoSaveChangesAsync());
        }
Пример #26
0
        public static JObject ToDto(this ClientSecret clientSecret)
        {
            var result = new JObject
            {
                { "type", Enum.GetName(typeof(ClientSecretTypes), clientSecret.Type).ToLowerInvariant() },
                { "value", clientSecret.Value }
            };

            return(result);
        }
Пример #27
0
 public static IdentityServer4.Models.Secret ConvertToIdsModel(this ClientSecret secret)
 {
     return(new IdentityServer4.Models.Secret
     {
         Description = secret.Description,
         Expiration = secret.Expiration.Value.DateTime,
         Type = secret.Type,
         Value = secret.Value
     });
 }
Пример #28
0
        public void DeleteClientSecret(int id)
        {
            ClientSecret clientProperty = this.Session.Get <ClientSecret>(id);

            if (clientProperty == null)
            {
                return;
            }
            this.Session.Delete(clientProperty);
            this.Session.Flush();
        }
Пример #29
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = (Authority != null ? Authority.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ClientId != null ? ClientId.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ClientSecret != null ? ClientSecret.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Resource != null ? Resource.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #30
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ (IdentityServer != null ? IdentityServer.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ClientScope != null ? ClientScope.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ClientSecret != null ? ClientSecret.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #31
0
        public Tokens GetTokens(Client client, ClientSecret clientSecret, Token token, string redirectUri)
        {
            var tokenCache = new TokenCache();

            var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache);
            var clientCredential = new ClientCredential(client, clientSecret);

            var result = authenticationContext.AcquireTokenByAuthorizationCode(token, new Uri(redirectUri), clientCredential);
            var tokens = new Tokens
            {
                AccessToken = result.AccessToken,
                RefreshToken = result.RefreshToken,
                ExpiresOn = result.ExpiresOn
            };
            return tokens;
        }