コード例 #1
0
        public async Task <ClientScope> AddClientScope(ClientScope scope)
        {
            _context.ClientScopes.Add(scope);
            await _context.SaveChangesAsync();

            return(scope);
        }
コード例 #2
0
        public int Add(ClientScope toAdd)
        {
            toAdd.Id = FakeDataBase.Instance.ClientsScopes.Count > 0 ? FakeDataBase.Instance.ClientsScopes.Max(u => u.Id) + 1 : 1;

            FakeDataBase.Instance.ClientsScopes.Add(toAdd);
            return(toAdd.Id);
        }
コード例 #3
0
        public void Create(ClientVm clientVm)
        {
            var client = _passportContext.Set <Client>()
                         .FirstOrDefault(x => x.Code == clientVm.ClientId);

            _passportContext.Set <ClientScope>()
            .DeleteMany(x => x.ClientId == client.Id);

            _passportContext.SaveChanges();

            foreach (var scopeName in clientVm.AllowedScopes)
            {
                var scope = _passportContext.Set <Scope>()
                            .FirstOrDefault(x => x.Name == scopeName);

                var clientScope = new ClientScope
                {
                    ClientId = client.Id,
                    ScopeId  = scope.Id
                };

                _passportContext.Set <ClientScope>().Add(clientScope);
            }

            _passportContext.SaveChanges();
        }
コード例 #4
0
        public async Task <bool> CreateClientScopeAsync(string realm, ClientScope clientScope)
        {
            var response = await GetBaseUrl(realm)
                           .AppendPathSegment($"/admin/realms/{realm}/client-scopes")
                           .PostJsonAsync(clientScope)
                           .ConfigureAwait(false);

            return(response.IsSuccessStatusCode);
        }
コード例 #5
0
        public void Delete(ClientScope toDelete)
        {
            var cs = FakeDataBase.Instance.ClientsScopes.FirstOrDefault(r => r.Id.Equals(toDelete.Id));

            if (cs != null)
            {
                FakeDataBase.Instance.ClientsScopes.Remove(cs);
            }
        }
コード例 #6
0
        /// <summary>
        /// Returns an API Client from the underlying connection
        /// </summary>
        /// <param name="scope">The scope from which to retrieve the client. Supported scopes are Server, Collection</param>
        /// <param name="parameters">If specified, the values in this parameter will override the values originally supplied to the this</param>
        /// <typeparam name="T">The type of the API client</typeparam>
        /// <returns>An instance of the requested API client</returns>
        private protected virtual T GetClient <T>(ClientScope scope = ClientScope.Collection, ParameterDictionary parameters = null)
            where T : VssHttpClientBase
        {
            var pd = new ParameterDictionary(parameters)
            {
                ["ConnectionType"] = scope
            };

            return(Provider.GetDataService <Models.Connection>(this, pd).GetItem().GetClient <T>());
        }
コード例 #7
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);
     }
 }
コード例 #8
0
        public async Task <ClientScope> BuildClientScope(int ClientId, string scope)
        {
            ClientScope result = null;
            await Task.Run(() => {
                result = new ClientScope {
                    ClientId = ClientId,
                    Scope    = scope
                };
            });

            return(result);
        }
コード例 #9
0
        /// <summary>
        /// Create ClientScope
        /// </summary>
        /// <param name="dto"></param>
        /// <returns>ClientScope</returns>
        public ClientScope BuildClientScope(ClientScopeBindingDto dto)
        {
            //JB. Get juts the client ID (int)
            var clientId = _ctx.Clients.Where(a => a.ClientId == dto.Client_Id).FirstOrDefault();
            var scope    = new ClientScope
            {
                Scope    = dto.Scope,
                ClientId = clientId.Id
            };

            return(scope);
        }
コード例 #10
0
        protected TClient GetClient <TClient>(ClientScope scope = ClientScope.Collection, ParameterDictionary parameters = null)
            where TClient : VssHttpClientBase
        {
            var pd = new ParameterDictionary(parameters)
            {
                ["ConnectionType"] = scope
            };

            var conn = Provider.GetDataService <Models.Connection>(Cmdlet, pd).GetItem();

            if (conn == null)
            {
                throw new ArgumentException($"No TFS connection information available. Either supply a valid -{scope} argument or use one of the Connect-Tfs* cmdlets prior to invoking this cmdlet.");
            }

            return(conn.GetClient <TClient>());
        }
コード例 #11
0
        public Task DoWith(IPipe<ClientContext> clientPipe, CancellationToken cancellationToken)
        {
            ClientScope newScope = null;
            ClientScope existingScope;

            lock (_scopeLock)
            {
                existingScope = _scope;
                if (existingScope == null)
                {
                    newScope = new ClientScope(_cacheTaskScope);
                    _scope = newScope;
                }
            }
            if (existingScope != null)
                return SendUsingExistingClient(clientPipe, existingScope, cancellationToken);

            return SendUsingNewClient(clientPipe, newScope, cancellationToken);
        }
コード例 #12
0
        public async Task <IActionResult> AddScope([FromBody] ClientScope clientScope)
        {
            var client = await _clientStore.FindEnabledClientByIdAsync(clientScope.Client);

            if (client == null)
            {
                return(BadRequest(new ApiResult()
                {
                    Data = null, Error_Code = 400, Msg = $"{clientScope.Client}不存在或不可用", Request = "Post /api/client/scope"
                }));
            }
            var scope = await _resourceStore.FindApiResourceAsync(clientScope.Scope);

            if (scope == null)
            {
                return(BadRequest(new ApiResult()
                {
                    Data = null, Error_Code = 400, Msg = $"{clientScope.Scope}不存在或不可用", Request = "Post /api/client/scope"
                }));
            }

            var currentClient = _configurationDbContext.Clients.Include(c => c.AllowedScopes).FirstOrDefault(c => c.ClientId == clientScope.Client);

            currentClient.AllowedScopes.Add(new IdentityServer4.EntityFramework.Entities.ClientScope()
            {
                Scope = clientScope.Scope
            });

            try
            {
                _configurationDbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.InnerException.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            return(Ok(new ApiResult()
            {
                Data = null, Error_Code = 0, Msg = $"{clientScope.Client}添加{clientScope.Scope}成功", Request = "Post /api/client/scope"
            }));
        }
コード例 #13
0
        async Task SendUsingNewClient(IPipe<ClientContext> clientPipe, ClientScope scope, CancellationToken cancellationToken)
        {
            try
            {
                var client = new HttpClient();
                var clientContext = new HttpClientContext(client, _receivePipe, _cacheTaskScope);

                scope.Created(clientContext);
            }
            catch (Exception ex)
            {
                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.CreateFaulted(ex);

                throw;
            }

            await SendUsingExistingClient(clientPipe, scope, cancellationToken).ConfigureAwait(false);
        }
コード例 #14
0
        async Task SendUsingNewClient(IPipe <ClientContext> clientPipe, ClientScope scope, CancellationToken cancellationToken)
        {
            try
            {
                var client        = new HttpClient();
                var clientContext = new HttpClientContext(client, _receivePipe, _cacheTaskScope);

                scope.Created(clientContext);
            }
            catch (Exception ex)
            {
                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.CreateFaulted(ex);

                throw;
            }

            await SendUsingExistingClient(clientPipe, scope, cancellationToken).ConfigureAwait(false);
        }
コード例 #15
0
        public Task DoWith(IPipe <ClientContext> clientPipe, CancellationToken cancellationToken)
        {
            ClientScope newScope = null;
            ClientScope existingScope;

            lock (_scopeLock)
            {
                existingScope = _scope;
                if (existingScope == null)
                {
                    newScope = new ClientScope(_cacheTaskScope);
                    _scope   = newScope;
                }
            }
            if (existingScope != null)
            {
                return(SendUsingExistingClient(clientPipe, existingScope, cancellationToken));
            }

            return(SendUsingNewClient(clientPipe, newScope, cancellationToken));
        }
コード例 #16
0
        async Task SendUsingExistingClient(IPipe <ClientContext> clientPipe, ClientScope scope, CancellationToken cancellationToken)
        {
            try
            {
                using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    await clientPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                if (_log.IsDebugEnabled)
                {
                    _log.Debug("The client usage threw an exception", exception);
                }

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.CreateFaulted(exception);

                throw;
            }
        }
コード例 #17
0
        /// <summary>
        /// JB. Creates a Client Socpe when a new Client is created in the Database.
        /// </summary>
        /// <param name="scope">ClientScope Type</param>
        /// <returns>String Result</returns>
        public async Task <string> CreateClientScope(ClientScope scope)
        {
            string result = "";

            try
            {
                await Task.Run(() =>
                {
                    using (ctx)
                    {
                        ctx.ClientScopes.Add(scope);
                        ctx.SaveChanges();
                        var id = scope.Id;
                        result = "Scope added for client Id " + id.ToString();
                    }
                });
            }
            catch (Exception ex)
            {
                result = ex.Message.ToString();
            }

            return(result);
        }
コード例 #18
0
 public void Update(ClientScope toUpdate)
 {
     throw new NotImplementedException();
 }
コード例 #19
0
ファイル: ManageController.cs プロジェクト: detmach/Teknik
        public IActionResult EditClient(EditClientModel model, [FromServices] ConfigurationDbContext configContext)
        {
            // Validate it's an actual client
            var foundClient = configContext.Clients.Where(c => c.ClientId == model.ClientId).FirstOrDefault();

            if (foundClient != null)
            {
                foundClient.ClientName = model.Name;
                foundClient.ClientUri  = model.HomepageUrl;
                foundClient.LogoUri    = model.LogoUrl;
                foundClient.Updated    = DateTime.Now;
                configContext.Entry(foundClient).State = EntityState.Modified;

                // Update the redirect URL for this client
                var results = configContext.Set <ClientRedirectUri>().Where(c => c.ClientId == foundClient.Id).ToList();
                if (results != null)
                {
                    configContext.RemoveRange(results);
                }
                var newUri = new ClientRedirectUri();
                newUri.Client      = foundClient;
                newUri.ClientId    = foundClient.Id;
                newUri.RedirectUri = model.CallbackUrl;
                configContext.Add(newUri);

                // Generate the origin for the callback
                Uri    redirect = new Uri(model.CallbackUrl);
                string origin   = redirect.Scheme + "://" + redirect.Host;

                // Update the allowed origin for this client
                var corsOrigins = configContext.Set <ClientCorsOrigin>().Where(c => c.ClientId == foundClient.Id).ToList();
                if (corsOrigins != null)
                {
                    configContext.RemoveRange(corsOrigins);
                }
                var newOrigin = new ClientCorsOrigin();
                newOrigin.Client   = foundClient;
                newOrigin.ClientId = foundClient.Id;
                newOrigin.Origin   = origin;
                configContext.Add(newUri);

                // Update their allowed grants
                var curGrants = configContext.Set <ClientGrantType>().Where(c => c.ClientId == foundClient.Id).ToList();
                if (curGrants != null)
                {
                    configContext.RemoveRange(curGrants);
                }
                foreach (var grantType in model.AllowedGrants)
                {
                    var newGrant = new ClientGrantType();
                    newGrant.Client    = foundClient;
                    newGrant.ClientId  = foundClient.Id;
                    newGrant.GrantType = grantType;
                    configContext.Add(newGrant);
                }

                // Update their allowed scopes
                var curScopes = configContext.Set <ClientScope>().Where(c => c.ClientId == foundClient.Id).ToList();
                if (curScopes != null)
                {
                    configContext.RemoveRange(curScopes);
                }
                foreach (var scope in model.AllowedScopes)
                {
                    var newScope = new ClientScope();
                    newScope.Client   = foundClient;
                    newScope.ClientId = foundClient.Id;
                    newScope.Scope    = scope;
                    configContext.Add(newScope);
                }

                // Save all the changed
                configContext.SaveChanges();

                // Clear the client cache
                RemoveCachedClient(model.ClientId);

                return(new JsonResult(new { success = true }));
            }

            return(new JsonResult(new { success = false, message = "Client does not exist." }));
        }
コード例 #20
0
        public async Task <bool> UpdateAsync(Core.Common.Models.Client client)
        {
            using (var translation = _context.Database.BeginTransaction())
            {
                try
                {
                    var grantTypes = client.GrantTypes == null
                        ? string.Empty
                        : ConcatListOfIntegers(client.GrantTypes.Select(k => (int)k).ToList());
                    var responseTypes = client.ResponseTypes == null
                        ? string.Empty
                        : ConcatListOfIntegers(client.ResponseTypes.Select(r => (int)r).ToList());
                    var connectedClient = await _context.Clients
                                          .Include(c => c.ClientScopes)
                                          .FirstOrDefaultAsync(c => c.ClientId == client.ClientId)
                                          .ConfigureAwait(false);

                    connectedClient.ClientName                  = client.ClientName;
                    connectedClient.ClientUri                   = client.ClientUri;
                    connectedClient.Contacts                    = ConcatListOfStrings(client.Contacts);
                    connectedClient.DefaultAcrValues            = client.DefaultAcrValues;
                    connectedClient.DefaultMaxAge               = client.DefaultMaxAge;
                    connectedClient.GrantTypes                  = grantTypes;
                    connectedClient.IdTokenEncryptedResponseAlg = client.IdTokenEncryptedResponseAlg;
                    connectedClient.IdTokenEncryptedResponseEnc = client.IdTokenEncryptedResponseEnc;
                    connectedClient.IdTokenSignedResponseAlg    = client.IdTokenSignedResponseAlg;
                    connectedClient.InitiateLoginUri            = client.InitiateLoginUri;
                    connectedClient.JwksUri                     = client.JwksUri;
                    connectedClient.LogoUri                     = client.LogoUri;
                    connectedClient.PolicyUri                   = client.PolicyUri;
                    connectedClient.RedirectionUrls             = ConcatListOfStrings(client.RedirectionUrls);
                    connectedClient.RequestObjectEncryptionAlg  = client.RequestObjectEncryptionAlg;
                    connectedClient.RequestObjectEncryptionEnc  = client.RequestObjectEncryptionEnc;
                    connectedClient.RequestObjectSigningAlg     = client.RequestObjectSigningAlg;
                    connectedClient.RequestUris                 = ConcatListOfStrings(client.RequestUris);
                    connectedClient.PostLogoutRedirectUris      = ConcatListOfStrings(client.PostLogoutRedirectUris);
                    connectedClient.RequireAuthTime             = client.RequireAuthTime;
                    connectedClient.ResponseTypes               = responseTypes;
                    connectedClient.SectorIdentifierUri         = client.SectorIdentifierUri;
                    connectedClient.SubjectType                 = client.SubjectType;
                    connectedClient.TokenEndPointAuthMethod     = (TokenEndPointAuthenticationMethods)client.TokenEndPointAuthMethod;
                    connectedClient.TokenEndPointAuthSigningAlg = client.TokenEndPointAuthSigningAlg;
                    connectedClient.TosUri = client.TosUri;
                    connectedClient.UserInfoEncryptedResponseAlg = client.UserInfoEncryptedResponseAlg;
                    connectedClient.UserInfoEncryptedResponseEnc = client.UserInfoEncryptedResponseEnc;
                    connectedClient.UserInfoSignedResponseAlg    = client.UserInfoSignedResponseAlg;
                    connectedClient.ScimProfile    = client.ScimProfile;
                    connectedClient.UpdateDateTime = DateTime.UtcNow;
                    var scopesNotToBeDeleted = new List <string>();
                    if (client.AllowedScopes != null)
                    {
                        foreach (var scope in client.AllowedScopes)
                        {
                            var record = connectedClient.ClientScopes.FirstOrDefault(c => c.ScopeName == scope.Name);
                            if (record == null)
                            {
                                record = new ClientScope
                                {
                                    ClientId  = connectedClient.ClientId,
                                    ScopeName = scope.Name
                                };
                                connectedClient.ClientScopes.Add(record);
                            }

                            scopesNotToBeDeleted.Add(record.ScopeName);
                        }
                    }

                    var scopeNames = connectedClient.ClientScopes.Select(o => o.ScopeName).ToList();
                    foreach (var scopeName in scopeNames.Where(id => !scopesNotToBeDeleted.Contains(id)))
                    {
                        connectedClient.ClientScopes.Remove(connectedClient.ClientScopes.First(s => s.ScopeName == scopeName));
                    }

                    await _context.SaveChangesAsync();

                    translation.Commit();
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    translation.Rollback();
                    return(false);
                }
            }

            return(true);
        }
コード例 #21
0
 public async Task <int> StoreClientScope(ClientScope scope) =>
 await connection.SingleAsync <int>("StoreClientScope", scope)
 .ConfigureAwait(false);
コード例 #22
0
        public Result <int> Update(ClientModel model, int id)
        {
            try
            {
                var result         = new Result <int>();
                var existingClient = clientContext.Clients
                                     .Where(x => x.Id == id)
                                     .Include(x => x.AllowedScopes)
                                     .Include(x => x.ClientSecrets)
                                     .Include(x => x.RedirectUris)
                                     .Include(x => x.PostLogoutRedirectUris)
                                     .Include(x => x.AllowedCorsOrigins)
                                     .Include(x => x.IdentityProviderRestrictions)
                                     .Include(x => x.Claims)
                                     .Include(x => x.AllowedCustomGrantTypes)
                                     .SingleOrDefault();


                if (existingClient == null)
                {
                    result.Exists = false;
                    return(result);
                }

                var duplicateClientId = clientContext.Clients
                                        .Where(x => x.ClientId == model.ClientId)
                                        .FirstOrDefault();

                if (duplicateClientId != null && duplicateClientId.Id != id)
                {
                    throw new Exception("pre-existing clientid");
                }

                clientContext.Entry(existingClient).CurrentValues.SetValues(model); // copy all values from object

                #region Update related properties


                var exRedirectUris = existingClient.RedirectUris.ToList();
                //delete redirect uri's that have been removed
                foreach (var item in exRedirectUris)
                {
                    if (!model.RedirectUris.Any(x => x.Id == item.Id))
                    {
                        existingClient.RedirectUris.Remove(item);
                    }
                }
                if (model.RedirectUris != null && model.RedirectUris.Any())
                {
                    //update and add new uris
                    foreach (var item in model.RedirectUris)
                    {
                        var exRedirectUri = existingClient.RedirectUris.FirstOrDefault(x => x.Id == item.Id);
                        if (exRedirectUri != null)
                        {
                            clientContext.Entry(exRedirectUri).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var redirectUri = new ClientRedirectUri
                            {
                                Uri = item.Uri,
                            };
                            existingClient.RedirectUris.Add(redirectUri);
                        }
                    }
                }


                //delete post redirect uri's that have been removed

                var exPostRedirectUris = existingClient.PostLogoutRedirectUris.ToList();
                foreach (var item in exPostRedirectUris)
                {
                    if (!model.PostLogoutRedirectUris.Any(x => x.Id == item.Id))
                    {
                        existingClient.PostLogoutRedirectUris.Remove(item);
                    }
                }

                if (model.PostLogoutRedirectUris != null && model.PostLogoutRedirectUris.Any())
                {
                    foreach (var item in model.PostLogoutRedirectUris)
                    {
                        var exPostRedirectUri = existingClient.PostLogoutRedirectUris.FirstOrDefault(x => x.Id == item.Id);
                        if (exPostRedirectUri != null)
                        {
                            clientContext.Entry(exPostRedirectUri).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var postRedirectUri = new ClientPostLogoutRedirectUri
                            {
                                Uri = item.Uri,
                            };
                            existingClient.PostLogoutRedirectUris.Add(postRedirectUri);
                        }
                    }
                }
                //update and add new post redirect uris



                var exIdProvRestrictions = existingClient.IdentityProviderRestrictions.ToList();
                foreach (var item in exIdProvRestrictions)
                {
                    if (!model.IdentityProviderRestrictions.Any(x => x.Id == item.Id))
                    {
                        existingClient.IdentityProviderRestrictions.Remove(item);
                    }
                }

                if (model.IdentityProviderRestrictions != null && model.IdentityProviderRestrictions.Any())
                {
                    foreach (var item in model.IdentityProviderRestrictions)
                    {
                        var exIdProvRestriction = existingClient.IdentityProviderRestrictions.FirstOrDefault(x => x.Id == item.Id);
                        if (exIdProvRestriction != null)
                        {
                            clientContext.Entry(exIdProvRestriction).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var IdentityProvRestriction = new ClientIdPRestriction
                            {
                                Provider = item.Provider,
                            };
                            existingClient.IdentityProviderRestrictions.Add(exIdProvRestriction);
                        }
                    }
                }
                //update and add new post redirect uris



                //delete post redirect uri's that have been removed


                //delete allowed scopes that have been removed

                var exScopes = existingClient.AllowedScopes.ToList();
                foreach (var item in exScopes)
                {
                    if (!model.AllowedScopes.Any(x => x.Id == item.Id))
                    {
                        existingClient.AllowedScopes.Remove(item);
                    }
                }

                if (model.AllowedScopes != null && model.AllowedScopes.Any())
                {
                    foreach (var item in model.AllowedScopes)
                    {
                        var exScope = existingClient.AllowedScopes.FirstOrDefault(x => x.Id == item.Id);
                        if (exScope != null)
                        {
                            clientContext.Entry(exScope).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var newScope = new ClientScope
                            {
                                Scope = item.Scope,
                            };
                            existingClient.AllowedScopes.Add(newScope);
                        }
                    }
                }



                //delete client claims that have been removed
                var exClaims = existingClient.Claims.ToList();
                foreach (var item in exClaims)
                {
                    if (!model.Claims.Any(x => x.Id == item.Id))
                    {
                        existingClient.Claims.Remove(item);
                    }
                }

                if (model.Claims != null && model.Claims.Any())
                {
                    //update and add new post redirect uris
                    foreach (var item in model.Claims)
                    {
                        var exClaim = existingClient.Claims.FirstOrDefault(x => x.Id == item.Id);
                        if (exClaim != null)
                        {
                            clientContext.Entry(exClaim).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var newClaim = new ClientClaim
                            {
                                Type  = item.Type,
                                Value = item.Value
                            };
                            existingClient.Claims.Add(newClaim);
                        }
                    }
                }

                //delete client claims that have been removed

                var exAllowedCors = existingClient.AllowedCorsOrigins.ToList();
                foreach (var item in exAllowedCors)
                {
                    if (!model.AllowedCorsOrigins.Any(x => x.Id == item.Id))
                    {
                        existingClient.AllowedCorsOrigins.Remove(item);
                    }
                }

                if (model.AllowedCorsOrigins != null && model.AllowedCorsOrigins.Any())
                {
                    //update and add new post redirect uris
                    foreach (var item in model.AllowedCorsOrigins)
                    {
                        var exAllowedCor = existingClient.AllowedCorsOrigins.FirstOrDefault(x => x.Id == item.Id);
                        if (exAllowedCor != null)
                        {
                            clientContext.Entry(exAllowedCor).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var newClientCor = new ClientCorsOrigin
                            {
                                Origin = item.Origin
                            };
                            existingClient.AllowedCorsOrigins.Add(newClientCor);
                        }
                    }
                }



                //delete custom grant types that have been removed

                var exCustomGrants = existingClient.AllowedCustomGrantTypes.ToList();
                foreach (var item in exCustomGrants)
                {
                    if (!model.AllowedCustomGrantTypes.Any(x => x.Id == item.Id))
                    {
                        existingClient.AllowedCustomGrantTypes.Remove(item);
                    }
                }

                if (model.AllowedCustomGrantTypes != null && model.AllowedCustomGrantTypes.Any())
                {
                    //update and add new post redirect uris
                    foreach (var item in model.AllowedCustomGrantTypes)
                    {
                        var exCustomGrant = existingClient.AllowedCustomGrantTypes.FirstOrDefault(x => x.Id == item.Id);
                        if (exCustomGrant != null)
                        {
                            clientContext.Entry(exCustomGrant).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var newCustomGrant = new ClientCustomGrantType
                            {
                                GrantType = item.GrantType
                            };
                            existingClient.AllowedCustomGrantTypes.Add(newCustomGrant);
                        }
                    }
                }



                //delete custom grant types that have been removed

                var exSecrets = existingClient.ClientSecrets.ToList();
                foreach (var item in exSecrets)
                {
                    if (!model.ClientSecrets.Any(x => x.Id == item.Id))
                    {
                        existingClient.ClientSecrets.Remove(item);
                    }
                }

                if (model.ClientSecrets != null && model.ClientSecrets.Any())
                {
                    //update and add new post redirect uris
                    foreach (var item in model.ClientSecrets)
                    {
                        var exSecret = existingClient.ClientSecrets.FirstOrDefault(x => x.Id == item.Id);
                        if (exSecret != null)
                        {
                            exSecret.Value = exSecret.Value;
                            clientContext.Entry(exSecret).CurrentValues.SetValues(item);
                        }
                        else
                        {
                            var newSecret = new ClientSecret
                            {
                                Type        = item.Type,
                                Value       = item.Value.Sha256(),
                                Expiration  = item.Expiration,
                                Description = item.Description,
                            };
                            existingClient.ClientSecrets.Add(newSecret);
                        }
                    }
                }


                #endregion


                clientContext.SaveChanges();
                result.Exists      = true;
                result.Response    = existingClient.Id;
                result.CustomValue = existingClient.ClientName;
                return(result);
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
                throw;
            }
        }
コード例 #23
0
        async Task SendUsingExistingClient(IPipe<ClientContext> clientPipe, ClientScope scope, CancellationToken cancellationToken)
        {
            try
            {
                using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    await clientPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The client usage threw an exception", exception);

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.CreateFaulted(exception);

                throw;
            }
        }
コード例 #24
0
        public async Task OnPostAsync()
        {
            // Arrange
            const string scope1OriginalScope = "Original Scope";
            const string scope1EditedScope   = "Edited Scope";
            const string newScopeScope       = "New Scope";
            var          databaseName        = $"{DatabaseNamePrefix}.{nameof(OnPostAsync)}";
            var          options             = new DbContextOptionsBuilder <IdentityServerDbContext>()
                                               .UseInMemoryDatabase(databaseName)
                                               .Options;
            ScopesModel   scopes;
            IActionResult post;
            var           scope1 = new ClientScope
            {
                Id    = Random.Next(),
                Scope = scope1OriginalScope
            };
            var scope2 = new ClientScope {
                Id = Random.Next()
            };
            var clientId = Random.Next();
            var client   = new Client
            {
                Id            = clientId,
                AllowedScopes = new List <ClientScope>
                {
                    scope1,
                    scope2
                }
            };

            using (var context = new IdentityServerDbContext(options, _configurationStoreOptions.Object, _operationalStoreOptions.Object))
            {
                context.Add(client);
                await context.SaveChangesAsync().ConfigureAwait(false);
            }

            // Act
            using (var context = new IdentityServerDbContext(options, _configurationStoreOptions.Object, _operationalStoreOptions.Object))
            {
                scopes = new ScopesModel(context)
                {
                    Client = new Client
                    {
                        Id            = clientId,
                        AllowedScopes = new List <ClientScope>
                        {
                            new ClientScope
                            {
                                Id    = scope1.Id,
                                Scope = scope1EditedScope
                            },
                            new ClientScope {
                                Scope = newScopeScope
                            }
                        }
                    }
                };
                post = await scopes.OnPostAsync().ConfigureAwait(false);
            }

            // Assert
            using (var context = new IdentityServerDbContext(options, _configurationStoreOptions.Object, _operationalStoreOptions.Object))
            {
                client = await context.Clients
                         .Include(x => x.AllowedScopes)
                         .SingleOrDefaultAsync(x => x.Id.Equals(clientId))
                         .ConfigureAwait(false);

                scope1 = client.AllowedScopes.SingleOrDefault(x => x.Id.Equals(scope1.Id));
                scope2 = client.AllowedScopes.SingleOrDefault(x => x.Id.Equals(scope2.Id));
                var newScope = client.AllowedScopes.SingleOrDefault(x => x.Scope.Equals(newScopeScope));

                Assert.NotNull(scope1);
                Assert.Equal(scope1EditedScope, scope1.Scope);
                Assert.Null(scope2);
                Assert.NotNull(newScope);
            }

            var result = Assert.IsType <RedirectToPageResult>(post);

            Assert.Equal("../Details/Scopes", result.PageName);
            Assert.Collection(result.RouteValues, routeValue =>
            {
                var(key, value) = routeValue;
                Assert.Equal(nameof(Client.Id), key);
                Assert.Equal(scopes.Client.Id, value);
            });
        }
コード例 #25
0
        private void AddClients(Client ct)
        {
            var client = new Client <Guid>()
            {
                AbsoluteRefreshTokenLifetime = ct.AbsoluteRefreshTokenLifetime,
                AccessTokenLifetime          = ct.AccessTokenLifetime,
                AccessTokenType            = ct.AccessTokenType,
                AllowAccessToAllGrantTypes = ct.AllowAccessToAllCustomGrantTypes,
                AllowAccessToAllScopes     = ct.AllowAccessToAllScopes,
                AllowClientCredentialsOnly = ct.AllowClientCredentialsOnly,
                AllowPromptNone            = ct.AllowPromptNone,
                AllowRememberConsent       = ct.AllowRememberConsent,
                AlwaysSendClientClaims     = ct.AlwaysSendClientClaims,
                AuthorizationCodeLifetime  = ct.AuthorizationCodeLifetime,
                ClientId                    = ct.ClientId,
                ClientName                  = ct.ClientName,
                ClientUri                   = ct.ClientUri,
                EnableLocalLogin            = ct.EnableLocalLogin,
                Enabled                     = ct.Enabled,
                Flow                        = ct.Flow,
                IdentityTokenLifetime       = ct.IdentityTokenLifetime,
                IncludeJwtId                = ct.IncludeJwtId,
                LogoUri                     = ct.LogoUri,
                LogoutSessionRequired       = ct.LogoutSessionRequired,
                LogoutUri                   = ct.LogoutUri,
                PrefixClientClaims          = ct.PrefixClientClaims,
                RefreshTokenExpiration      = ct.RefreshTokenExpiration,
                RefreshTokenUsage           = ct.RefreshTokenUsage,
                RequireConsent              = ct.RequireConsent, //设置为true会有问题?
                SlidingRefreshTokenLifetime = ct.SlidingRefreshTokenLifetime,
                UpdateAccessTokenOnRefresh  = ct.UpdateAccessTokenClaimsOnRefresh
            };

            client.ClientSecrets = new List <ClientSecret <Guid> >();
            client.AllowedScopes = new List <ClientScope <Guid> >();
            client.RedirectUris  = new List <ClientRedirectUri <Guid> >();
            client.IdentityProviderRestrictions = new List <ClientProviderRestriction <Guid> >();
            client.PostLogoutRedirectUris       = new List <ClientPostLogoutRedirectUri <Guid> >();
            client.AllowedCustomGrantTypes      = new List <ClientCustomGrantType <Guid> >();
            client.Claims             = new List <ClientClaim <Guid> >();
            client.AllowedCorsOrigins = new List <ClientCorsOrigin <Guid> >();

            //Add Secrets
            foreach (var secret in ct.ClientSecrets)
            {
                var clientSecret = new ClientSecret <Guid>()
                {
                    Description = secret.Description,
                    Expiration  = secret.Expiration.HasValue ? (DateTime?)secret.Expiration.Value.DateTime : null,
                    Type        = secret.Type,
                    Value       = secret.Value
                };
                client.ClientSecrets.Add(clientSecret);
            }
            //Add Scopes
            foreach (var scope in ct.AllowedScopes)
            {
                var allowedScope = new ClientScope <Guid>()
                {
                    Scope = scope
                };
                client.AllowedScopes.Add(allowedScope);
            }

            //Add RedirectUris
            foreach (var redirectUri in ct.RedirectUris)
            {
                var clientRedirectUri = new ClientRedirectUri <Guid>()
                {
                    Uri = redirectUri
                };
                client.RedirectUris.Add(clientRedirectUri);
            }
            //Add ProviderRestrictions
            foreach (var provider in ct.IdentityProviderRestrictions)
            {
                var clientProviderRestriction = new ClientProviderRestriction <Guid>()
                {
                    Provider = provider
                };
                client.IdentityProviderRestrictions.Add(clientProviderRestriction);
            }
            //Add ClientPostLogoutRedirectUri
            foreach (var postLogoutRedirectUri in ct.PostLogoutRedirectUris)
            {
                var clientPostLogoutRedirectUri = new ClientPostLogoutRedirectUri <Guid>()
                {
                    Uri = postLogoutRedirectUri
                };
                client.PostLogoutRedirectUris.Add(clientPostLogoutRedirectUri);
            }
            //Add ClientCustomGrantTypes
            foreach (var customGrantType in ct.AllowedCustomGrantTypes)
            {
                var clientCustomerGrantType = new ClientCustomGrantType <Guid>()
                {
                    GrantType = customGrantType
                };
                client.AllowedCustomGrantTypes.Add(clientCustomerGrantType);
            }
            //Add ClientClaims
            foreach (var claim in ct.Claims)
            {
                var clientClaim = new ClientClaim <Guid>()
                {
                    Type  = claim.Type,
                    Value = claim.Value
                };
                client.Claims.Add(clientClaim);
            }
            //Add ClientCorsOrigins
            foreach (var corsOrigin in ct.AllowedCorsOrigins)
            {
                var clientCorsOrigin = new ClientCorsOrigin <Guid>()
                {
                    Origin = corsOrigin
                };
                client.AllowedCorsOrigins.Add(clientCorsOrigin);
            }
            _clientContext.Clients.Add(client);
            _clientContext.SaveChanges();
        }
コード例 #26
0
        public async Task <(bool Succeeded, string ErrorMsg)> UpdateAsync(string userId, string clientId, string clientName, string redirectUrl, string postLogoutRedirectUrl, bool requireConsent, string allowedScope)
        {
            bool succeeded = false;

            string errorMsg = string.Empty;

            var userXClient = await _userXClientRepository.SingleOrDefaultAsync(x => x.UserId == userId && x.ClientId == clientId);

            if (userXClient != null)
            {
                var client = _configurationDbContext.Clients.SingleOrDefault(x => x.ClientId == clientId);

                if (client != null)
                {
                    //update redirectUri
                    var redirectUri = await _clientRedirectUriRepository.SingleOrDefaultAsync(x => x.ClientId == client.Id);

                    if (redirectUri != null)
                    {
                        redirectUri.RedirectUri = redirectUrl;

                        await _clientRedirectUriRepository.UpdateAsync(redirectUri);
                    }

                    //update allowedScope
                    var scope = await _clientScopeRepository.SingleOrDefaultAsync(x => !AllowedScopes.Contains(x.Scope) && x.ClientId == client.Id);

                    if (scope == null)
                    {
                        scope = new ClientScope
                        {
                            ClientId = client.Id,
                            Scope    = allowedScope
                        };

                        await _clientScopeRepository.InsertAsync(scope);
                    }
                    else
                    {
                        scope.Scope = allowedScope;

                        await _clientScopeRepository.UpdateAsync(scope);
                    }

                    //update client
                    client.ClientName     = clientName;
                    client.RequireConsent = requireConsent;

                    _configurationDbContext.Clients.Update(client);

                    await _configurationDbContext.SaveChangesAsync();

                    succeeded = true;
                }
            }
            else
            {
                errorMsg = "你没有权限更新";
            }

            return(succeeded, errorMsg);
        }
コード例 #27
0
        protected void gOAuthClientEdit_SaveClick(object sender, EventArgs e)
        {
            divErrors.Visible = false;
            if (String.IsNullOrEmpty(tbClientName.Text))
            {
                divErrors.InnerText = "A valid Client Name must be provided.";
                divErrors.Visible   = true;
                return;
            }
            if (tbApiKey.Text.AsGuidOrNull() == null)
            {
                divErrors.InnerText = "A valid GUID must be provided for the API Key.";
                divErrors.Visible   = true;
                return;
            }
            if (tbApiSecret.Text.AsGuidOrNull() == null)
            {
                divErrors.InnerText = "A valid GUID must be provided for the API Secret.";
                divErrors.Visible   = true;
                return;
            }
            if (string.IsNullOrEmpty(tbCallbackUrl.Text))
            {
                divErrors.InnerText = "A valid Callback URL must be provided.";
                divErrors.Visible   = true;
                return;
            }
            ClientScopeService clientScopeService = new ClientScopeService(OAuthContext);
            ClientService      clientService      = new ClientService(OAuthContext);
            Client             client             = null;

            if (hfClientId.Value.AsIntegerOrNull().HasValue)
            {
                client = clientService.Get(hfClientId.Value.AsInteger());
            }
            else
            {
                client = new Client();
                clientService.Add(client);
            }

            client.ClientName  = tbClientName.Text;
            client.ApiKey      = tbApiKey.Text.AsGuid();
            client.ApiSecret   = tbApiSecret.Text.AsGuid();
            client.CallbackUrl = tbCallbackUrl.Text;
            client.Active      = cbActive.Checked;

            foreach (System.Web.UI.WebControls.ListItem item in cblClientScopes.Items)
            {
                int         scopeId     = item.Value.AsInteger();
                ClientScope clientScope = clientScopeService.Queryable().Where(cs => cs.ClientId == client.Id && cs.ScopeId == scopeId).FirstOrDefault();
                if (clientScope != null)
                {
                    clientScope.Active = item.Selected;
                }
                else if (item.Selected)
                {
                    clientScope          = new ClientScope();
                    clientScope.ClientId = client.Id;
                    clientScope.ScopeId  = item.Value.AsInteger();
                    clientScope.Active   = item.Selected;
                    clientScopeService.Add(clientScope);
                }
            }
            OAuthContext.SaveChanges();
            OAuthContext = new OAuthContext();
            gOAuthClients_Bind(sender, e);
            gOAuthClientEdit.Hide();
        }
コード例 #28
0
        public void UpdateClientBasic(int id, ClientDto clientDto)
        {
            Client client = this.Session.Get <Client>(id);

            if (client == null)
            {
                throw new FluentValidationException($"客户端{id}不存在。");
            }
            client.Description                 = clientDto.Description;
            client.ProtocolType                = clientDto.ProtocolType;
            client.RequireClientSecret         = clientDto.RequireClientSecret;
            client.RequirePkce                 = clientDto.RequirePkce;
            client.AllowPlainTextPkce          = clientDto.AllowPlainTextPkce;
            client.AllowOfflineAccess          = clientDto.AllowOfflineAccess;
            client.AllowAccessTokensViaBrowser = clientDto.AllowAccessTokensViaBrowser;
            client.Enabled = clientDto.Enabled;

            var transaction = this.Session.BeginTransaction();

            try
            {
                this.Session.Update(client);

                this.Session.CreateQuery("delete from ClientScope where ClientId=:ClientId")
                .SetInt32("ClientId", id)
                .ExecuteUpdate();

                clientDto.AllowedScopes.ForEach(scope =>
                {
                    ClientScope clientScope = new ClientScope();
                    clientScope.ClientId    = client.Id;
                    clientScope.Scope       = scope;
                    this.Session.Save(clientScope);
                });


                this.Session.CreateQuery("delete from ClientRedirectUri where ClientId=:ClientId")
                .SetInt32("ClientId", id)
                .ExecuteUpdate();

                clientDto.RedirectUris.ForEach(redirectUri =>
                {
                    ClientRedirectUri clientRedirectUri = new ClientRedirectUri();
                    clientRedirectUri.ClientId          = client.Id;
                    clientRedirectUri.RedirectUri       = redirectUri;
                    this.Session.Save(clientRedirectUri);
                });

                this.Session.CreateQuery("delete from ClientGrantType where ClientId=:ClientId")
                .SetInt32("ClientId", id)
                .ExecuteUpdate();

                clientDto.AllowedGrantTypes.ForEach(grantType =>
                {
                    ClientGrantType clientGrantType = new ClientGrantType();
                    clientGrantType.ClientId        = client.Id;
                    clientGrantType.GrantType       = grantType;
                    this.Session.Save(clientGrantType);
                });

                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw;
            }
        }