Exemplo n.º 1
0
        public void RequestClientCredentialsToken_ServiceUnavailable_ThrowsAsync()
        {
            // Arrange
            var request = new ClientCredentialsTokenRequest();

            // Assert
            Assert.ThrowsAsync <IdokladUnavailableException>(async() => await _serviceUnavailableClient.RequestClientCredentialsTokenAsync(request));
        }
 public HttpHandler(IHttpClientFactory httpClientFactory, IConfiguration config,
                    ClientCredentialsTokenRequest tokenRequest, IUnmockablesWrapper unmockablesWrapper)
 {
     _httpClientFactory  = httpClientFactory;
     _config             = config;
     _tokenRequest       = tokenRequest;
     _unmockablesWrapper = unmockablesWrapper;
 }
        private static void Main(string[] args)
        {
            var teste = new MyClass1
            {
                casa   = "teste",
                opa    = 1,
                update = DateTime.UtcNow,
                sub    = new SubClass1
                {
                    home     = "casa",
                    lastdate = DateTime.Now,
                    oxi      = 3
                }
            };


            //Bruno Lambert


            //client-credentials application
            const string CLIENT_ID     = "0fbfaafa-c74b-4da2-9307-6fdcdc5cf58b";
            const string CLIENT_SECRET = "OLGSXm1Gf0MV8QfHASnepdXOLnIaBFBvMurCTGD5XnO7n3zAy1nX7AwOQ0lOtqjDYwDK783B9mY3jpCv";
            const string SCOPE         = "peoplemgmt-ho";

            var httpClient = new HttpClient();
            var discovery  = httpClient.GetDiscoveryDocumentAsync("https://login-ho.sdasystems.org").Result;

            var clientCredentialsTokenRequest = new ClientCredentialsTokenRequest()
            {
                ClientId     = CLIENT_ID,
                ClientSecret = CLIENT_SECRET,
                Scope        = SCOPE,
                Address      = discovery.TokenEndpoint,
            };

            var tokens = httpClient.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest).Result;
            // ---------------------------------------------------------------------------------------------------------- //
            var apiConfig = new Configuration()
            {
                AccessToken = tokens.AccessToken,
                BasePath    = "http://localhost:60736/",//-dev,-ho
                //BasePath = "https://ws-peoplemgmt-ho.sdasystems.org/bra/",//-dev,-ho
            };

            //PhoneTypeTest(apiConfig);
            //LegalEntityTest(apiConfig);
            //CountryTest(apiConfig);
            //EmergencyContactTest(apiConfig);
            //AddressTest(apiConfig);
            NaturalPersonTest(apiConfig);
            //AddressTypeTest(apiConfig);
            //AllergyTypeTeste(apiConfig);
            //DisabilityTypeTeste(apiConfig);
            //ZipPostalCodeAddressTest(apiConfig);

            Console.WriteLine("-- END --");
            Console.ReadLine();
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Index()
        {
            // discover endpoints from metadata
            var client = new HttpClient();
            var disco  = await client.GetDiscoveryDocumentAsync("https://localhost:5011");

            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //_logger.LogDebug("client.GetDiscoveryDocumentAsync=>{0}", JsonConvert.SerializeObject(disco, settings));
            if (disco.IsError)
            {
                return(Json(disco.Error));
            }
            var AuthorizationCodeTokenRequest = new AuthorizationCodeTokenRequest
            {
                Address      = disco.AuthorizeEndpoint,
                ClientId     = "mvc_client",
                ClientSecret = "secret",
                RedirectUri  = "https://localhost:8001/signin-oidc"
            };
            var temp = await client.RequestAuthorizationCodeTokenAsync(AuthorizationCodeTokenRequest);

            var ClientCredentialsTokenRequest = new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId     = "client",
                ClientSecret = "secret",
                Scope        = "api1"
            };
            // request token
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(ClientCredentialsTokenRequest);

            //_logger.LogDebug("client.RequestClientCredentialsTokenAsync=>{0}", JsonConvert.SerializeObject(tokenResponse));
            if (tokenResponse.IsError)
            {
                return(Json(tokenResponse.Error));
            }
            //return Json(tokenResponse.Json);
            // call api
            var apiClient = new HttpClient();

            apiClient.SetBearerToken(tokenResponse.AccessToken);

            var response = await apiClient.GetAsync("https://localhost:6001/api/identity");

            if (!response.IsSuccessStatusCode)
            {
                return(Json(response.StatusCode));
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();

                return(Json(content));
            }
        }
 public IdentityServerClient(
     HttpClient httpClient,
     ClientCredentialsTokenRequest tokenRequest,
     ILogger <IdentityServerClient> logger)
 {
     _httpClient   = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
     _tokenRequest = tokenRequest ?? throw new ArgumentNullException(nameof(tokenRequest));
     _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
 }
        private static void Main(string[] args)
        {
            var teste = new MyClass1
            {
                casa   = "teste",
                opa    = 1,
                update = DateTime.UtcNow,
                sub    = new SubClass1
                {
                    home     = "casa",
                    lastdate = DateTime.Now,
                    oxi      = 3
                }
            };

            //client-credentials application
            const string CLIENT_ID     = "CLIENT_ID";
            const string CLIENT_SECRET = "CLIENT_SECRET";
            const string SCOPE         = "peoplemgmt";

            ;

            var httpClient = new HttpClient();
            var discovery  = httpClient.GetDiscoveryDocumentAsync("https://login-ho.sdasystems.org").Result;

            var clientCredentialsTokenRequest = new ClientCredentialsTokenRequest()
            {
                ClientId     = CLIENT_ID,
                ClientSecret = CLIENT_SECRET,
                Scope        = SCOPE,
                Address      = discovery.TokenEndpoint,
            };

            var tokens = httpClient.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest).Result;
            // ---------------------------------------------------------------------------------------------------------- //
            var apiConfig = new Configuration()
            {
                AccessToken = tokens.AccessToken,
                BasePath    = "http://localhost:60736/",//-dev,-ho
            };

            //DocumentTypeTest(apiConfig);
            //PhoneTypeTest(apiConfig);
            //LegalEntityTest(apiConfig);
            //CountryTest(apiConfig);
            //DiseaseTest(apiConfig);
            //EmergencyContactTest(apiConfig);
            AddressTest(apiConfig);
            //NaturalPersonTest(apiConfig);
            //AddressTypeTest(apiConfig);
            //AllergyTypeTeste(apiConfig);
            //DisabilityTypeTeste(apiConfig);
            //ZipPostalCodeAddressTest(apiConfig);

            Console.WriteLine("-- END --");
            Console.ReadLine();
        }
Exemplo n.º 7
0
 public IdentityServerClient(
     HttpClient httpClient,
     ClientCredentialsTokenRequest tokenRequest,
     ILogger <IdentityServerClient> logger)
 {
     _httpClient   = Guard.IsNotNull(httpClient, nameof(httpClient));
     _tokenRequest = Guard.IsNotNull(tokenRequest, nameof(tokenRequest));
     _logger       = Guard.IsNotNull(logger, nameof(logger));
 }
Exemplo n.º 8
0
        /// <inheritdoc />
        public virtual async Task <ClientCredentialsTokenRequest> GetClientCredentialsRequestAsync(string clientName, ClientAccessTokenParameters parameters)
        {
            ClientCredentialsTokenRequest requestDetails;

            // if a named client configuration was passed in, try to load it
            if (string.Equals(clientName, AccessTokenManagementDefaults.DefaultTokenClientName))
            {
                // if only one client configuration exists, load that
                if (_clientAccessTokenManagementOptions.Clients.Count == 1)
                {
                    _logger.LogDebug("Reading token client configuration from single configuration entry.");
                    requestDetails = _clientAccessTokenManagementOptions.Clients.First().Value;
                }
                // otherwise fall back to the scheme configuration
                else
                {
                    _logger.LogDebug("Constructing token client configuration from OpenID Connect handler.");

                    var(options, configuration) = await GetOpenIdConnectSettingsAsync(_userAccessTokenManagementOptions.SchemeName);

                    requestDetails = new ClientCredentialsTokenRequest
                    {
                        Address = configuration.TokenEndpoint,

                        ClientId     = options.ClientId,
                        ClientSecret = options.ClientSecret
                    };

                    if (!string.IsNullOrWhiteSpace(_clientAccessTokenManagementOptions.DefaultClient.Scope))
                    {
                        requestDetails.Scope = _clientAccessTokenManagementOptions.DefaultClient.Scope;
                    }

                    if (!string.IsNullOrWhiteSpace(_clientAccessTokenManagementOptions.DefaultClient.Resource))
                    {
                        requestDetails.Resource.Add(_clientAccessTokenManagementOptions.DefaultClient.Resource);
                    }

                    var assertion = await CreateAssertionAsync(clientName);

                    if (assertion != null)
                    {
                        requestDetails.ClientAssertion = assertion;
                    }
                }
            }
            else
            {
                if (!_clientAccessTokenManagementOptions.Clients.TryGetValue(clientName, out requestDetails))
                {
                    throw new InvalidOperationException($"No access token client configuration found for client: {clientName}");
                }
            }

            _logger.LogDebug("Returning token client configuration for client: {client}", clientName);
            return(requestDetails);
        }
Exemplo n.º 9
0
        private async Task <string> GetAccessTokenAsync(CancellationToken cancellationToken)
        {
            if (_accessToken != null && DateTime.UtcNow < _accessTokenExpiry)
            {
                return(_accessToken);
            }

            using (HttpClient client = new HttpClient())
            {
                var discoveryRequest = new DiscoveryDocumentRequest {
                    Address = _resource + "/identity",
                    Policy  = new DiscoveryPolicy
                    {
                        Authority          = "https://identity.osisoft.com",
                        ValidateEndpoints  = false,
                        ValidateIssuerName = false
                    }
                };

                var discoveryResponse = await client.GetDiscoveryDocumentAsync(discoveryRequest, cancellationToken);

                if (discoveryResponse.IsError)
                {
                    throw new InvalidOperationException(discoveryResponse.Error);
                }

                var clientCredentialsTokenRequest = new ClientCredentialsTokenRequest
                {
                    Address      = discoveryResponse.TokenEndpoint,
                    ClientId     = _clientId,
                    ClientSecret = _clientSecret,
                    Scope        = "ocsapi"
                };

                DateTime now = DateTime.UtcNow;

                var tokenResponse = await client.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest, cancellationToken);

                if (discoveryResponse.IsError)
                {
                    throw new InvalidOperationException(tokenResponse.Error);
                }

                if (string.IsNullOrEmpty(tokenResponse.AccessToken))
                {
                    throw new InvalidOperationException("Failed to acquire Access Token");
                }

                _accessToken = tokenResponse.AccessToken;

                // Add a buffer of 30 seconds to the expiration delta.
                _accessTokenExpiry = now.AddSeconds(tokenResponse.ExpiresIn - 30);

                return(_accessToken);
            }
        }
 private void SetupClientCredentialsTokenRequest()
 {
     tokenRequest = new ClientCredentialsTokenRequest
     {
         Address      = originalAddress,
         ClientId     = clientId,
         ClientSecret = clientSecret,
         Scope        = originalScope
     };
 }
        public async Task <IActionResult> GetVersionOne()
        {
            // 1. "retrieve" our api credentials. This must be registered on Identity Server!
            var apiClientCredentials = new ClientCredentialsTokenRequest
            {
                Address = "http://localhost:5000/connect/token",

                ClientId     = "client-app",
                ClientSecret = "secret",

                // This is the scope our Protected API requires.
                Scope = "read:entity"
            };

            // creates a new HttpClient to talk to our IdentityServer (localhost:5000)
            var client = new HttpClient();

            // just checks if we can reach the Discovery document. Not 100% needed but..
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return(StatusCode(500));
            }

            // 2. Authenticates and get an access token from Identity Server
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(apiClientCredentials);

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return(StatusCode(500));
            }

            // Another HttpClient for talking now with our Protected API
            var apiClient = new HttpClient();

            // 3. Set the access_token in the request Authorization: Bearer <token>
            client.SetBearerToken(tokenResponse.AccessToken);

            // 4. Send a request to our Protected API
            var response = await client.GetAsync("http://localhost:5002/api/protected");

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
                return(StatusCode(500));
            }

            var content = await response.Content.ReadAsStringAsync();

            // All good! We have the data here
            return(Ok(content));
        }
Exemplo n.º 12
0
        /// <inheritdoc/>
        public JWTModel AuthenticateAsUser(Uri tokenUri, ClientCredentialsTokenRequest tokenRequest)
        {
            this.logger.LogDebug($"Authenticating Direct Grant as User: {tokenRequest.Username}");
            Task <IAuthModel> authenticating = this.ResourceOwnerPasswordGrant(tokenUri, tokenRequest);

            JWTModel jwtModel = (authenticating.Result as JWTModel) !;

            this.logger.LogDebug($"Finished authenticating User: {tokenRequest.Username}");

            return(jwtModel);
        }
Exemplo n.º 13
0
        static async Task Main(string[] args)
        {
            var client = new HttpClient();
            var discovery = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
            if (discovery.IsError)
            {
                Console.WriteLine(discovery.Error);
                return;
            }

            var request = new ClientCredentialsTokenRequest()
            {
                Address = discovery.TokenEndpoint,
                ClientId = "restClient",
                ClientSecret = "secret",
                Scope = "SearchApi",
            };

            var userPwdRequest = new PasswordTokenRequest()
            {
                Address = discovery.TokenEndpoint,
                ClientId = "ApiClient",
                ClientSecret = "secret",

                UserName = "******",
                Password = "******",
                Scope = "SearchApi",
            };

            var tokenResponse = await client.RequestClientCredentialsTokenAsync(request);
            // var tokenResponse = await client.RequestPasswordTokenAsync(userPwdRequest);
            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            var apiClient = new HttpClient();
            apiClient.SetBearerToken(tokenResponse.AccessToken);

            var response = await apiClient.GetAsync("http://localhost:5001/identity");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JArray.Parse(content));
            }
        }
Exemplo n.º 14
0
    /// <summary>
    /// Sends a token request using the client_credentials grant type.
    /// </summary>
    /// <param name="scope">The scope (space separated string).</param>
    /// <param name="parameters">Extra parameters.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns></returns>
    public Task <TokenResponse> RequestClientCredentialsTokenAsync(string scope = null, Parameters parameters = null, CancellationToken cancellationToken = default)
    {
        var request = new ClientCredentialsTokenRequest
        {
            Scope = scope
        };

        ApplyRequestParameters(request, parameters);

        return(_client().RequestClientCredentialsTokenAsync(request, cancellationToken));
    }
Exemplo n.º 15
0
        private static async Task <TokenResponse> GetClientCredentialToken(ClientCredentialsTokenRequest request)
        {
            TokenResponse response = null;

            if (request != null)
            {
                response = await new HttpClient().RequestClientCredentialsTokenAsync(request);
            }

            return(response);
        }
Exemplo n.º 16
0
        /// <inheritdoc/>
        public JWTModel AuthenticateAsSystem(Uri tokenUri, ClientCredentialsTokenRequest tokenRequest)
        {
            this.logger.LogDebug($"Authenticating Service... {tokenRequest.ClientId}");
            Task <IAuthModel> authenticating = this.ClientCredentialsGrant(tokenUri, tokenRequest);

            JWTModel jwtModel = (authenticating.Result as JWTModel) !;

            this.logger.LogDebug($"Finished authenticating Service. {tokenRequest.ClientId}");

            return(jwtModel);
        }
Exemplo n.º 17
0
        protected override void ExecuteRequest(HttpContext context)
        {
            if (Request == null || string.IsNullOrWhiteSpace(Request.PasswordHash) ||
                (string.IsNullOrWhiteSpace(Request.Login) && string.IsNullOrWhiteSpace(Request.EmailAddress)))
            {
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                return;
            }

            if (!_userRepository.CanSignIn(Request).GetAwaiter().GetResult())
            {
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                return;
            }

            Dbo.User user;
            if (!string.IsNullOrEmpty(Request.EmailAddress))
            {
                user = _userRepository.GetUserByLoginOrEmail(null, Request.EmailAddress).GetAwaiter().GetResult();

                if (user != null)
                {
                    Request.Login = user.Login;
                }
            }
            else
            {
                user = _userRepository.GetUserByLoginOrEmail(Request.Login, null).GetAwaiter().GetResult();
            }

            string fullAddress = $"{HTTP}{address}:{port}";
            var    client      = new HttpClient();
            DiscoveryDocumentResponse     discoDoc = client.GetDiscoveryDocumentAsync(fullAddress).GetAwaiter().GetResult();
            ClientCredentialsTokenRequest clientCredentialsTokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = discoDoc.TokenEndpoint,
                ClientId     = Request.Login,
                ClientSecret = Request.PasswordHash,
                Scope        = "api1"
            };
            TokenResponse tokenResponse = client.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest).GetAwaiter().GetResult();

            string jsonAsString = tokenResponse.Json.ToString();

            context.Response.StatusCode = (int)tokenResponse.HttpStatusCode;
            if (context.Response.StatusCode == StatusCodes.Status200OK)
            {
                user.LastLoginDate = DateTime.Now;
                _userRepository.Update(user);
            }

            context.Response.WriteAsync(jsonAsString).GetAwaiter().GetResult();
        }
Exemplo n.º 18
0
        public void ShouldErrorIfNoAuthToken()
        {
            // Setup

            // Input Parameters
            string phn = "9735361219";

            // Setup Configuration
            string endpoint = "https://test-endpoint";
            Uri    tokenUri = new Uri("https://localhost");
            ClientCredentialsTokenRequest tokenRequest = new ClientCredentialsTokenRequest()
            {
                ClientId     = "TEST_CLIENTID",
                ClientSecret = "TEST_CLIENT_SECRET",
                Password     = "******",
                Username     = "******",
            };
            Dictionary <string, string> configurationParams = new Dictionary <string, string>
            {
                { "Salesforce:Endpoint", endpoint },
                { "Salesforce:TokenUri", tokenUri.ToString() },
                { "Salesforce:ClientAuthentication:ClientId", tokenRequest.ClientId },
                { "Salesforce:ClientAuthentication:ClientSecret", tokenRequest.ClientSecret },
                { "Salesforce:ClientAuthentication:Username", tokenRequest.Username },
                { "Salesforce:ClientAuthentication:Password", tokenRequest.Password },
            };
            IConfiguration configuration = CreateConfiguration(configurationParams);

            // Setup Authentication
            Mock <IAuthenticationDelegate> mockAuthenticationDelegate = new Mock <IAuthenticationDelegate>();

            mockAuthenticationDelegate
            .Setup(s => s.AuthenticateAsUser(
                       It.Is <Uri>(x => x.ToString() == tokenUri.ToString()),
                       It.Is <ClientCredentialsTokenRequest>(x => x.ClientId == tokenRequest.ClientId)))
            .Returns(() => new JWTModel());

            // Setup class to be tested
            IMedicationRequestDelegate medDelegate = new SalesforeceDelegate(
                CreateLogger(),
                new Mock <IHttpClientService>().Object,
                configuration,
                mockAuthenticationDelegate.Object);

            // Test
            RequestResult <IList <MedicationRequest> > response = Task.Run(async() => await medDelegate.GetMedicationRequestsAsync(phn).ConfigureAwait(true)).Result;

            // Verify
            Assert.Equal(Common.Constants.ResultType.Error, response.ResultStatus);
            Assert.NotNull(response.ResultError);
            Assert.NotNull(response.ResultError?.ErrorCode);
        }
Exemplo n.º 19
0
        private static async Task <string> GetAccessTokenAsync(string scope)
        {
            WriteLine();
            SetTextColorTo(Yellow);
            WriteLine($"IDENTITYSERVER4 HOST Response for '{scope}':-");

            //Create HTTP client instance.
            var httpClient = new HttpClient();

            //Get the discovery document by calling the extension method
            //present in HttpClientDiscoveryExtensions(namespace: IdentityModel.Client)
            var discoveryDoc = await httpClient.GetDiscoveryDocumentAsync(_Authority);

            if (discoveryDoc.IsError)
            {
                SetTextColorTo(Red);
                WriteLine("Error occurred while fetching discovery document.");
                WriteLine();
                WriteLine($"Error: {discoveryDoc.Error}");

                return(null);
            }

            //Create token request model
            var tokenRequestModel = new ClientCredentialsTokenRequest
            {
                Address      = discoveryDoc.TokenEndpoint,
                ClientId     = _ClientId,
                ClientSecret = _ClientSecret,

                //If Scope is not defined, all scopes are returned from the IdentityServer.
                Scope = scope
            };

            //Since we are using ClientCredential for machine-to-machine interaction.
            var response = await httpClient.RequestClientCredentialsTokenAsync(tokenRequestModel);

            if (response.IsError)
            {
                SetTextColorTo(Red);
                WriteLine("Error occurred while requesting client credential token.");
                WriteLine();
                WriteLine($"Error: {response.Error}");

                return(null);
            }

            SetTextColorTo(Green);
            WriteLine(response.Json);

            return(response.AccessToken);
        }
Exemplo n.º 20
0
        public async Task <string> GetAccessToken()
        {
            var auth0Client  = new AuthenticationApiClient(_authSettings.Domain);
            var tokenRequest = new ClientCredentialsTokenRequest()
            {
                ClientId     = _authSettings.ClientId,
                ClientSecret = _authSettings.ClientSecret,
                Audience     = _authSettings.Audience
            };
            var tokenResponse = await auth0Client.GetTokenAsync(tokenRequest);

            return(tokenResponse.AccessToken);
        }
        async Task <string> GetAccessToken()
        {
            var auth0Client  = new AuthenticationApiClient(auth0Settings["Domain"]);
            var tokenRequest = new ClientCredentialsTokenRequest()
            {
                ClientId     = auth0Settings["ClientId"],
                ClientSecret = auth0Settings["ClientSecret"],
                Audience     = auth0Settings["Audience"]
            };
            var tokenResponse = await auth0Client.GetTokenAsync(tokenRequest);

            return(tokenResponse.AccessToken);
        }
Exemplo n.º 22
0
        public async Task <HttpRequestMessage> Create(HttpMethod httpMethod, Uri uri, string requestScope)
        {
            var tokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = _tokenUrl,
                ClientId     = _clientId,
                ClientSecret = _secret,
                Scope        = requestScope
            };
            var response = await _httpClient.RequestClientCredentialsTokenAsync(tokenRequest).ConfigureAwait(false);

            return(CreateWithAccessToken(httpMethod, uri, response.AccessToken));
        }
Exemplo n.º 23
0
        async Task <TokenResponse> GetAccessTokenUsinClientCredentials(DiscoveryDocumentResponse disco)
        {
            var tokenClient = new HttpClient();
            var clientReq   = new ClientCredentialsTokenRequest
            {
                ClientId     = "consoleApp",
                ClientSecret = "Console_App",
                Address      = disco.TokenEndpoint,
                Scope        = "accountApi"
            };

            return(await tokenClient.RequestClientCredentialsTokenAsync(clientReq));
        }
Exemplo n.º 24
0
        private static async Task Main()
        {
            // discover endpoints from metadata
            var client = new HttpClient();

            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // request token
            var tokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "client",
                ClientSecret = "secret",
                Scope        = "api1"
            };
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(tokenRequest);

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }
            Console.WriteLine("================================================== tokenResponse.Json");
            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            // call api
            var apiClient = new HttpClient();

            apiClient.SetBearerToken(tokenResponse.AccessToken);

            var apiUrl   = "http://localhost:9000/identity";
            var response = await apiClient.GetAsync(apiUrl);

            Console.WriteLine("API: " + apiUrl);
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
                return;
            }
            var content = await response.Content.ReadAsStringAsync();

            Console.WriteLine("================================================== content");
            Console.WriteLine(JArray.Parse(content));
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            var serverBaseUrl = "http://integration-8-ugs-api.flycowdev.com";

            IBrandApiClient client = new BrandApiClient(serverBaseUrl);

            var clientCredentials = new ClientCredentialsTokenRequest()
            {
                client_id = "BRAND_3",
                client_secret = "w0jdfZGyDB3gWFJqGsBCTO3E7liTDgYoVrCaP7t13JMzryNIuKA3G2",
                grant_type = "client_credentials",
                scope = "playerapi"
            };

            TokenResponse brandTokenResponse = null;

            var task = Task.Run(async () =>
            {
                Console.WriteLine("Getting brand authorization token....");
                brandTokenResponse = await client.GetTokenAsync(clientCredentials);
                System.Console.WriteLine(JsonConvert.SerializeObject(brandTokenResponse));
            });

            task.Wait();

            // Authorize a player

            var request = new AuthorizePlayerRequest()
            {
                ipaddress = "184.70.137.34",
                username  = "******",
                userid    = "1234567891",
                tag       = "{\"aff\": \"123\"}",
                lang      = "zh-CN",
                cur       = "RMB",
                betlimitid = 1,
                loginurl  = "http://ugslobby.com/login",
                cashierurl = "http://ugslobby.com/cashier",
                termsurl = "http://ugslobby.com/terms",
                helpurl = "http://ugslobby.com/help"
            };

            task = Task.Run(async () =>
            {
                Console.WriteLine("Authorizing player....");
                var playerAuthResponse = await client.AuthorizePlayerAsync(request, brandTokenResponse.access_token);
                System.Console.WriteLine(JsonConvert.SerializeObject(playerAuthResponse));
            });

            task.Wait();
        }
Exemplo n.º 26
0
        //static TokenResponse GetClientTokenAsync()
        //{
        //    var client = new TokenClient(
        //        "http://localhost:5000/connect/token",
        //        "silicon",
        //        "F621F470-9731-4A25-80EF-67A6F7C5F4B8");
        //    return client.RequestClientCredentialsAsync("api1").Result;
        //}

        //static TokenResponse GetClientTokenAsync()
        //{
        //    var client = new TokenClient(
        //        "http://localhost:5000/connect/token",
        //        "silicon",
        //        "F621F470-9731-4A25-80EF-67A6F7C5F4B8");
        //    return client.RequestClientCredentialsAsync("api1").Result;
        //}

        static async Task <TokenResponse> GetClientTokenAsync()
        {
            var client = new HttpClient();
            var clientCredentialsTokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = "http://localhost:5000/connect/token",
                ClientId     = "silicon",
                ClientSecret = "F621F470-9731-4A25-80EF-67A6F7C5F4B8",
                Scope        = "api1"
            };
            var response = await client.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest);

            return(response);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Request an Access Token using the Client Credentials Grant flow.
 /// </summary>
 /// <param name="request">The <see cref="ClientCredentialsTokenRequest"/> containing the information of the request.</param>
 /// <returns>An <see cref="AccessTokenResponse"/> containing the token information</returns>
 public Task <AccessTokenResponse> GetTokenAsync(ClientCredentialsTokenRequest request)
 {
     return(Connection.PostAsync <AccessTokenResponse>("oauth/token", null, new Dictionary <string, object>
     {
         { "grant_type", "client_credentials" },
         { "client_id", request.ClientId },
         { "client_secret", request.ClientSecret },
         { "audience", request.Audience }
     },
                                                       null,
                                                       null,
                                                       null,
                                                       null));
 }
Exemplo n.º 28
0
        public async Task <string> GetAccessToken(Auth0ConfigModel objAuth0ConfigModel)
        {
            string auth0Domain = objAuth0ConfigModel.Domain;
            AuthenticationApiClient       authAPiclient = new AuthenticationApiClient(auth0Domain);
            ClientCredentialsTokenRequest tokenRequest  = new ClientCredentialsTokenRequest {
                Audience     = "https://dev-8todrv-h.au.auth0.com/api/v2/",
                ClientId     = objAuth0ConfigModel.ClientId,
                ClientSecret = objAuth0ConfigModel.ClientSecret
            };
            var tokenResponse =
                await authAPiclient.GetTokenAsync(tokenRequest);

            return(tokenResponse.AccessToken);
        }
        public async Task GetClientCredentialsToken_NullClient_ReturnsTokenResponse()
        {
            //Arrange
            var wrapper      = new UnmockablesWrapper();
            var tokenRequest = new ClientCredentialsTokenRequest();

            //Act
            var result = wrapper.RequestClientCredentialsTokenAsync(null, tokenRequest);

            //Assert
            Assert.NotNull(result);
            var response = await result as TokenResponse;

            Assert.NotNull(response);
        }
Exemplo n.º 30
0
        protected virtual Task <ClientCredentialsTokenRequest> CreateClientCredentialsTokenRequestAsync(
            DiscoveryDocumentResponse discoveryResponse,
            IdentityClientConfiguration configuration)
        {
            var request = new ClientCredentialsTokenRequest {
                Address      = discoveryResponse.TokenEndpoint,
                Scope        = configuration.Scope,
                ClientId     = configuration.ClientId,
                ClientSecret = configuration.ClientSecret
            };

            AddParametersToRequestAsync(configuration, request);

            return(Task.FromResult(request));
        }
        private async Task <TokenResponse> GetTokenResponse(HttpClient client,
                                                            ClientCredentialsTokenRequest tokenRequest)
        {
            TokenResponse tokenResponse;

            try
            {
                return(await _unmockablesWrapper
                       .RequestClientCredentialsTokenAsync(client, _tokenRequest));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Exemplo n.º 32
0
        private void btnGetOAuthToken_Click(object sender, EventArgs e)
        {
            var clientCredentials = new ClientCredentialsTokenRequest()
            {
                client_id = txtClientId.Text,
                client_secret = txtClientSecret.Text,
                grant_type = cboGrantType.Text,
                scope = cboScope.Text
            };

            TokenResponse brandTokenResponse = null;

            try
            {

                var task = Task.Run(async () =>
                {
                    brandTokenResponse = await _apiClient.GetTokenAsync(clientCredentials);
                });

                task.Wait();

                txtAccessToken.Text = brandTokenResponse.access_token;
                txtResponse.Text = JsonConvert.SerializeObject(brandTokenResponse);
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }