/// <summary>
        /// Creates the client.
        /// </summary>
        /// <param name="createClientRequest">The create client request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <CreateClientResponse> CreateClient(CreateClientRequest createClientRequest,
                                                              CancellationToken cancellationToken)
        {
            CreateClientResponse response = null;
            String requestUri             = this.BuildRequestUrl("/api/clients");

            try
            {
                String requestSerialised = JsonConvert.SerializeObject(createClientRequest);

                StringContent httpContent = new StringContent(requestSerialised, Encoding.UTF8, "application/json");

                // Add the access token to the client headers
                //this.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // Make the Http Call here
                HttpResponseMessage httpResponse = await this.HttpClient.PostAsync(requestUri, httpContent, cancellationToken);

                // Process the response
                String content = await this.HandleResponse(httpResponse, cancellationToken);

                // call was successful so now deserialise the body to the response object
                response = JsonConvert.DeserializeObject <CreateClientResponse>(content);
            }
            catch (Exception ex)
            {
                // An exception has occurred, add some additional information to the message
                Exception exception = new Exception($"Error creating client {createClientRequest.ClientId}.", ex);

                throw exception;
            }

            return(response);
        }
        public async Task GivenTheFollowingClientsExist(Table table)
        {
            foreach (TableRow tableRow in table.Rows)
            {
                String clientId          = SpecflowTableHelper.GetStringRowValue(tableRow, "ClientId");
                String clientName        = SpecflowTableHelper.GetStringRowValue(tableRow, "ClientName");
                String secret            = SpecflowTableHelper.GetStringRowValue(tableRow, "Secret");
                String allowedScopes     = SpecflowTableHelper.GetStringRowValue(tableRow, "AllowedScopes");
                String allowedGrantTypes = SpecflowTableHelper.GetStringRowValue(tableRow, "AllowedGrantTypes");

                List <String> splitAllowedScopes     = allowedScopes.Split(",").ToList();
                List <String> splitAllowedGrantTypes = allowedGrantTypes.Split(",").ToList();

                CreateClientRequest createClientRequest = new CreateClientRequest
                {
                    Secret            = secret,
                    AllowedGrantTypes = new List <String>(),
                    AllowedScopes     = new List <String>(),
                    ClientDescription = String.Empty,
                    ClientId          = clientId,
                    ClientName        = clientName
                };

                splitAllowedScopes.ForEach(a => { createClientRequest.AllowedScopes.Add(a.Trim()); });
                splitAllowedGrantTypes.ForEach(a => { createClientRequest.AllowedGrantTypes.Add(a.Trim()); });

                CreateClientResponse createClientResponse = await this.TestingContext.DockerHelper.SecurityServiceClient
                                                            .CreateClient(createClientRequest, CancellationToken.None).ConfigureAwait(false);

                createClientResponse.ClientId.ShouldBe(clientId);

                this.TestingContext.AddClientDetails(clientId, secret, allowedGrantTypes);
            }
        }
Exemple #3
0
        public CreateClientResponse CreateClient(CreateClientRequest clientRequest)
        {
            CreateClientResponse rtn = new CreateClientResponse();

            _client         = new RestClient($"{_settings.Url}{XeroUrl.Contacts}");
            _client.Timeout = -1;

            var request = new RestRequest(Method.POST);

            request.AddHeader("xero-tenant-id", _settings.TenandId);
            request.AddHeader("Authorization", "Bearer " + _settings.AccessToken);
            request.AddHeader("Accept", "application/json");
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json,application/json", JsonConvert.SerializeObject(clientRequest), ParameterType.RequestBody);
            var response = _client.Execute <XeroCreateContactResponse>(request);

            rtn.HttpStatusCode = response.StatusCode;
            if (rtn.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                rtn.HttpStatusCode = System.Net.HttpStatusCode.Created;
            }

            rtn.Status = response.StatusCode == System.Net.HttpStatusCode.Created ? PSC.Common.Enums.ResponseStatus.Success : PSC.Common.Enums.ResponseStatus.Failed;
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                rtn.Contacts = response.Data.Contacts;
            }
            else
            {
                rtn.Message = response.Content;
            }

            return(rtn);
        }
Exemple #4
0
        public async Task ShouldCreate_A_Client()
        {
            string name     = "Vader";
            Guid   clientId = Guid.NewGuid();

            var request = new CreateClientCommand {
                Name = name
            };
            var expected = new CreateClientResponse {
                Name = name, Id = clientId
            };

            var mapper         = PetShopMappingConfiguration.GetPetShopMappings();
            var mockRepository = new Mock <IClientRepository>();

            mockRepository.Setup(p => p.Add(It.Is <Client>(c => c.Name == name)))
            .Returns((Client client) => Task.Run(() =>
            {
                client.Id = clientId;
            }));

            var handler = new CreateClientCommandHandler(mapper, mockRepository.Object);

            var result = await handler.Handle(request, CancellationToken.None);

            result.Data.Should().BeEquivalentTo(expected);
            result.Message.Should().BeEquivalentTo("Client Created");
            mockRepository.Verify(m => m.Add(It.IsAny <Client>()), Times.Once());
        }
Exemple #5
0
        private async Task <CreateClientResponse> CreateClient(CreateClientRequest createClientRequest,
                                                               CancellationToken cancellationToken)
        {
            CreateClientResponse createClientResponse = await this.TestingContext.DockerHelper.SecurityServiceClient.CreateClient(createClientRequest, cancellationToken).ConfigureAwait(false);

            return(createClientResponse);
        }
        public async Task GivenICreateTheFollowingClients(Table table)
        {
            foreach (TableRow tableRow in table.Rows)
            {
                // Get the scopes
                String scopes = SpecflowTableHelper.GetStringRowValue(tableRow, "Scopes");
                // Get the grant types
                String grantTypes = SpecflowTableHelper.GetStringRowValue(tableRow, "GrantTypes");
                // Get the redirect uris
                String redirectUris = SpecflowTableHelper.GetStringRowValue(tableRow, "RedirectUris");
                // Get the post logout redirect uris
                String postLogoutRedirectUris = SpecflowTableHelper.GetStringRowValue(tableRow, "PostLogoutRedirectUris");

                CreateClientRequest createClientRequest = new CreateClientRequest
                {
                    ClientId                     = SpecflowTableHelper.GetStringRowValue(tableRow, "ClientId"),
                    Secret                       = SpecflowTableHelper.GetStringRowValue(tableRow, "Secret"),
                    ClientName                   = SpecflowTableHelper.GetStringRowValue(tableRow, "Name"),
                    AllowedScopes                = string.IsNullOrEmpty(scopes) ? null : scopes.Split(",").ToList(),
                    AllowedGrantTypes            = string.IsNullOrEmpty(grantTypes) ? null : grantTypes.Split(",").ToList(),
                    ClientRedirectUris           = string.IsNullOrEmpty(redirectUris) ? null : redirectUris.Split(",").ToList(),
                    ClientPostLogoutRedirectUris = string.IsNullOrEmpty(postLogoutRedirectUris) ? null : postLogoutRedirectUris.Split(",").ToList(),
                    ClientDescription            = SpecflowTableHelper.GetStringRowValue(tableRow, "Description"),
                    RequireConsent               = SpecflowTableHelper.GetBooleanValue(tableRow, "RequireConsent")
                };

                CreateClientResponse createClientResponse = await this.CreateClient(createClientRequest, CancellationToken.None).ConfigureAwait(false);

                createClientResponse.ShouldNotBeNull();
                createClientResponse.ClientId.ShouldNotBeNullOrEmpty();

                this.TestingContext.Clients.Add(createClientResponse.ClientId);
            }
        }
        public async Task <IActionResult> Create([FromBody] CreateClientRequest request)
        {
            var clientId = (request.UserId + "client_id_" + request.ApplicationName).Sha256();
            int i        = 0;

            Console.WriteLine("clientId = " + clientId);
            while (true)
            {
                Console.WriteLine("IndexOf + = " + (clientId.IndexOf('+') >= 0).ToString());
                if (clientId.IndexOf('+') >= 0)
                {
                    clientId = (request.UserId + "client_id_" + request.ApplicationName + "_" + i).Sha256();
                    Console.WriteLine("clientId = " + clientId);
                    i++;
                }
                else
                {
                    break;
                }
            }
            var clientSecret = ("client_secret_" + request.ApplicationName).Sha256();

            request.RedirectUris.Add("http://localhost:7030/Auth/AuthorizationGrantCode");
            IdentityServer4.Models.Client client = new IdentityServer4.Models.Client
            {
                ClientName    = request.ApplicationName,
                ClientId      = clientId,
                ClientSecrets =
                {
                    new IdentityServer4.Models.Secret(clientSecret.Sha256())
                },
                AllowedGrantTypes      = { GrantType.AuthorizationCode, GrantType.ClientCredentials },
                RedirectUris           = request.RedirectUris,
                AllowedScopes          = request.Scopes,
                RequireConsent         = true,
                AlwaysSendClientClaims = true
            };
            var entry = await _configurationDbContext.Clients.AddAsync(client.ToEntity());

            if (await _configurationDbContext.SaveChangesAsync() > 0)
            {
                List <string> scopes = new List <string>();
                foreach (var item in entry.Entity.AllowedScopes)
                {
                    scopes.Add(item.Scope);
                }
                var response = new CreateClientResponse
                {
                    ClientId        = entry.Entity.ClientId,
                    ClientSecret    = clientSecret,
                    RedirectUris    = entry.Entity.RedirectUris.Select(x => x.RedirectUri).ToList(),
                    ApplicationName = request.ApplicationName,
                    Scopes          = entry.Entity.AllowedScopes.Select(x => x.Scope).Join(",")
                };
                return(await Task.FromResult(Ok(response)));
            }
            return(BadRequest());
        }
        public override async Task <ActionResult <CreateClientResponse> > HandleAsync(CreateClientRequest request, CancellationToken cancellationToken)
        {
            var response = new CreateClientResponse(request.CorrelationId);

            var toAdd = _mapper.Map <Client>(request);

            toAdd = await _repository.AddAsync(toAdd);

            var dto = _mapper.Map <ClientDto>(toAdd);

            response.Client = dto;

            return(Ok(response));
        }
        public async Task GivenTheFollowingClientsExist(Table table)
        {
            foreach (TableRow tableRow in table.Rows)
            {
                String clientId          = SpecflowTableHelper.GetStringRowValue(tableRow, "ClientId");
                String clientName        = SpecflowTableHelper.GetStringRowValue(tableRow, "ClientName");
                String secret            = SpecflowTableHelper.GetStringRowValue(tableRow, "Secret");
                String allowedScopes     = SpecflowTableHelper.GetStringRowValue(tableRow, "AllowedScopes");
                String allowedGrantTypes = SpecflowTableHelper.GetStringRowValue(tableRow, "AllowedGrantTypes");

                List <String> splitAllowedScopes     = allowedScopes.Split(',').ToList();
                List <String> splitAllowedGrantTypes = allowedGrantTypes.Split(',').ToList();

                CreateClientRequest createClientRequest = new CreateClientRequest
                {
                    Secret            = secret,
                    AllowedGrantTypes = new List <String>(),
                    AllowedScopes     = new List <String>(),
                    ClientDescription = String.Empty,
                    ClientId          = clientId,
                    ClientName        = clientName
                };

                splitAllowedScopes.ForEach(a => { createClientRequest.AllowedScopes.Add(a.Trim()); });
                splitAllowedGrantTypes.ForEach(a => { createClientRequest.AllowedGrantTypes.Add(a.Trim()); });

                CreateClientResponse createClientResponse = await this.TestingContext.DockerHelper.SecurityServiceClient
                                                            .CreateClient(createClientRequest, CancellationToken.None).ConfigureAwait(false);

                createClientResponse.ClientId.ShouldBe(clientId);

                this.TestingContext.AddClientDetails(clientId, secret, allowedGrantTypes);
            }

            var merchantClient = this.TestingContext.GetClientDetails("merchantClient");

            // TODO: Handle local test running
            String securityService         = this.TestingContext.DockerHelper.SecurityServiceBaseAddress;
            String transactionProcessorAcl = this.TestingContext.DockerHelper.TransactionProcessorACLBaseAddress;

            Console.WriteLine($"securityService [{securityService}]");
            Console.WriteLine($"transactionProcessorAcl [{transactionProcessorAcl}]");

            AppManager.SetConfiguration(merchantClient.ClientId, merchantClient.ClientSecret,
                                        securityService, transactionProcessorAcl);
        }
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            CreateClientResponse response = new CreateClientResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("ClientArn", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.ClientArn = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
        public async Task <IActionResult> Save([FromBody] SaveClientRequest request)
        {
            request.RedirectUris.Add("http://localhost:7030/Auth/AuthorizationGrantCode");
            var clientEntity = await _configurationDbContext.Clients.Include(x => x.RedirectUris).SingleOrDefaultAsync(x => x.ClientId == request.ClientId);

            var oldRedirectUriList = clientEntity.RedirectUris.ToList();
            var newRedirectUriList = new List <ClientRedirectUri>();

            foreach (var item in oldRedirectUriList)
            {
                if (!request.RedirectUris.Contains(item.RedirectUri))
                {
                    clientEntity.RedirectUris.Remove(item);
                }
            }

            foreach (var item in request.RedirectUris)
            {
                if (!clientEntity.RedirectUris.Any(x => x.RedirectUri == item))
                {
                    clientEntity.RedirectUris.Add(new ClientRedirectUri {
                        RedirectUri = item
                    });
                }
            }
            var entry  = _configurationDbContext.Clients.Update(clientEntity);
            var result = await _configurationDbContext.SaveChangesAsync();

            if (result > 0)
            {
                var response = new CreateClientResponse
                {
                    ClientId     = entry.Entity.ClientId,
                    RedirectUris = entry.Entity.RedirectUris.Select(x => x.RedirectUri).ToList()
                };
                return(await Task.FromResult(Ok(response)));
            }
            return(BadRequest());
        }
        //GET : /api/UserProfile
        public async Task <Object> AddApplication(AddApplicationModel input)
        {
            var    result = 0;
            var    createClientResponse = new CreateClientResponse();
            string userId = User.Claims.First(c => c.Type == "UserID").Value;

            input.UserId = userId;
            var user = await _userManager.FindByIdAsync(userId);

            HttpClientHandler clientHandler = new HttpClientHandler();

            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return(true); };

            // Pass the handler to httpclient(from you are calling api)
            #region Create Client Id, Secret From Identity Server
            using (var _httpClient = new HttpClient(clientHandler))
            {
                string message      = JsonConvert.SerializeObject(input);
                byte[] messageBytes = Encoding.UTF8.GetBytes(message);
                var    content      = new ByteArrayContent(messageBytes);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                HttpRequestMessage requestMessage = new HttpRequestMessage()
                {
                    RequestUri = new Uri(_configuration["RackleUrls:IdentityServer"].ToString() + "/api/Client/Create"),
                    Method     = HttpMethod.Post,
                    Content    = content
                };

                Console.WriteLine("RCL Identity URL: " + _configuration["RackleUrls:IdentityServer"].ToString() + "/api/Client/Create");
                var response = await _httpClient.SendAsync(requestMessage);

                var data = response.Content.ReadAsStringAsync().Result;
                createClientResponse = string.IsNullOrEmpty(data) ? null : JsonConvert.DeserializeObject <CreateClientResponse>(data);
            }
            #endregion

            UserApplications UserApplicationEntity = new UserApplications();
            if (!string.IsNullOrWhiteSpace(createClientResponse?.ClientId) && !string.IsNullOrWhiteSpace(createClientResponse?.ClientSecret)) // Identity Create Request atılacak response'una göre kayıt atılacak
            {
                var UserApplicationContext         = _dataContext.Set <UserApplications>();
                var ApplicationRedirectUrisContext = _dataContext.Set <ApplicationRedirectUris>();
                var ApplicationScopesContext       = _dataContext.Set <ApplicationScopes>();

                UserApplicationEntity.Id = Guid.NewGuid();
                UserApplicationEntity.ApplicationName = input.ApplicationName;
                UserApplicationEntity.ClientId        = createClientResponse?.ClientId;
                UserApplicationEntity.Secret          = createClientResponse?.ClientSecret;
                UserApplicationEntity.UserId          = user.Id;

                UserApplicationContext.Add(UserApplicationEntity);

                if (input.RedirectUris?.Count > 0)
                {
                    var RedirectUriEntityList = new List <ApplicationRedirectUris>();
                    RedirectUriEntityList = input.RedirectUris.Select(x => new ApplicationRedirectUris
                    {
                        Id            = Guid.NewGuid(),
                        ApplicationId = UserApplicationEntity.Id,
                        RedirectUri   = x
                    }).ToList();
                    ApplicationRedirectUrisContext.AddRange(RedirectUriEntityList);
                }
                if (input.Scopes?.Count > 0)
                {
                    var ScopeEntityList = new List <ApplicationScopes>();
                    ScopeEntityList = input.Scopes.Select(x => new ApplicationScopes
                    {
                        Id            = Guid.NewGuid(),
                        ApplicationId = UserApplicationEntity.Id,
                        Scope         = x
                    }).ToList();
                    ApplicationScopesContext.AddRange(ScopeEntityList);
                }
                result = await _dataContext.SaveChangesAsync();
            }
            if (result > 0 && !string.IsNullOrWhiteSpace(createClientResponse?.ClientId) && !string.IsNullOrWhiteSpace(createClientResponse?.ClientSecret))
            {
                return
                    (new {
                    Success = true,
                    UserApplication = new {
                        ApplicationName = UserApplicationEntity.ApplicationName,
                        ClientId = UserApplicationEntity.ClientId,
                        RedirectUris = UserApplicationEntity.RedirectUris.Select(x => x.RedirectUri).ToList(),
                        Scopes = UserApplicationEntity.Scopes.Select(x => x.Scope).ToList(),
                        Secret = UserApplicationEntity.Secret
                    }
                });
            }
            return(new { Success = false });
        }
        //GET : /api/UserProfile
        public async Task <Object> SaveApplication(SaveApplicationModel input)
        {
            var    result = 0;
            var    createClientResponse = new CreateClientResponse();
            string userId = User.Claims.First(c => c.Type == "UserID").Value;

            input.UserId = userId;
            var user = await _userManager.FindByIdAsync(userId);

            #region Create Client Id, Secret From Identity Server
            using (var _httpClient = new HttpClient())
            {
                string message      = JsonConvert.SerializeObject(input);
                byte[] messageBytes = Encoding.UTF8.GetBytes(message);
                var    content      = new ByteArrayContent(messageBytes);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                HttpRequestMessage requestMessage = new HttpRequestMessage()
                {
                    RequestUri = new Uri(_configuration["RackleUrls:IdentityServer"].ToString() + "/api/Client/Save"),
                    Method     = HttpMethod.Post,
                    Content    = content
                };

                var response = await _httpClient.SendAsync(requestMessage);

                var data = response.Content.ReadAsStringAsync().Result;
                createClientResponse = string.IsNullOrEmpty(data) ? null : JsonConvert.DeserializeObject <CreateClientResponse>(data);
            }
            #endregion

            var UserApplicationContext         = _dataContext.Set <UserApplications>();
            var ApplicationRedirectUrisContext = _dataContext.Set <ApplicationRedirectUris>();
            var ApplicationScopesContext       = _dataContext.Set <ApplicationScopes>();

            UserApplications UserApplicationEntity = new UserApplications();
            if (!string.IsNullOrWhiteSpace(createClientResponse?.ClientId)) // Identity Create Request atılacak response'una göre kayıt atılacak
            {
                var applicationEntity = await UserApplicationContext.Include(x => x.RedirectUris).SingleOrDefaultAsync(x => x.ClientId == input.ClientId);

                var redirectURiList = await ApplicationRedirectUrisContext.Where(x => x.ApplicationId == applicationEntity.Id).ToListAsync();

                foreach (var item in redirectURiList)
                {
                    if (!input.RedirectUris.Contains(item.RedirectUri))
                    {
                        ApplicationRedirectUrisContext.Remove(item);
                    }
                }
                foreach (var item in input.RedirectUris)
                {
                    if (!redirectURiList.Any(x => x.RedirectUri == item))
                    {
                        ApplicationRedirectUrisContext.Add(new ApplicationRedirectUris
                        {
                            Id            = Guid.NewGuid(),
                            RedirectUri   = item,
                            ApplicationId = applicationEntity.Id
                        });
                    }
                }
                result = await _dataContext.SaveChangesAsync();
            }
            if (result > 0 && !string.IsNullOrWhiteSpace(createClientResponse?.ClientId))
            {
                UserApplicationEntity = await UserApplicationContext.Include(x => x.RedirectUris).SingleOrDefaultAsync(x => x.ClientId == input.ClientId);

                return
                    (new
                {
                    Success = true,
                    UserApplication = new
                    {
                        ApplicationName = UserApplicationEntity.ApplicationName,
                        ClientId = UserApplicationEntity.ClientId,
                        RedirectUris = UserApplicationEntity.RedirectUris.Select(x => x.RedirectUri).ToList(),
                        Scopes = UserApplicationEntity.Scopes.Select(x => x.Scope).ToList(),
                        Secret = UserApplicationEntity.Secret
                    }
                });
            }
            return(new { Success = false });
        }