Exemple #1
0
        private async void RequestAccessToken_ButtenClick(object sender, RoutedEventArgs e)
        {
            var userName = UserNameInput.Text;
            var password = PasswordInput.Password;

            var client = new HttpClient();

            _disco = await client.GetDiscoveryDocumentAsync("http://localhost:5001");

            if (_disco.IsError)
            {
                MessageBox.Show(_disco.Error);
                return;
            }
            var tokenRequest = await client.RequestPasswordTokenAsync(new PasswordTokenRequest {
                Address      = _disco.TokenEndpoint,
                ClientId     = "wpf client",
                ClientSecret = "wpf client",
                Scope        = "api1 openid profile email phone address",
                Password     = password,
                UserName     = userName,
            });

            if (tokenRequest.IsError)
            {
                MessageBox.Show(tokenRequest.Error);
                return;
            }
            AccessTokenTestBlock.Text = tokenRequest.AccessToken;
        }
Exemple #2
0
        /// <summary>
        /// Sign in
        /// </summary>
        /// <param name="userName">User name</param>
        /// <param name="password">Password</param>
        /// <returns>TokenResponse</returns>
        public async Task <TokenResponse> SignInAsync(string userName, string password)
        {
            // if (this.discoResponse == null)
            // {
            //     this.discoResponse = await this.discoverDocumentAsync();
            // }

            // Use Cached Discovery Document
            this.discoResponse = await this.discoverCachedDocumentAsync();


            var httpClient = this.httpClientFactory.CreateClient(HttpClientNameFactory.AuthHttpClient);

            // Wait until it is safe to enter.
            this.semaphore.WaitOne();

            TokenResponse tokenResponse = await httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = this.discoResponse.TokenEndpoint,
                ClientId     = this.clientId,
                ClientSecret = this.secret,
                UserName     = userName,
                Password     = password,
                //Scope = "MyBackendApi1 openid email" // "openid" is must if request for any IdentityResource
            });

            // Release the Mutex.
            this.semaphore.Release(1);

            return(tokenResponse);
        }
Exemple #3
0
        protected virtual async Task <TokenResponse> GetTokenResponse(
            DiscoveryDocumentResponse discoveryResponse,
            IdentityClientConfiguration configuration)
        {
            using (var httpClient = new HttpClient())
            {
                switch (configuration.GrantType)
                {
                case OidcConstants.GrantTypes.ClientCredentials:
                    return(await httpClient.RequestClientCredentialsTokenAsync(
                               await CreateClientCredentialsTokenRequestAsync(discoveryResponse, configuration),
                               CancellationTokenProvider.Token
                               ));

                case OidcConstants.GrantTypes.Password:
                    return(await httpClient.RequestPasswordTokenAsync(
                               await CreatePasswordTokenRequestAsync(discoveryResponse, configuration),
                               CancellationTokenProvider.Token
                               ));

                default:
                    throw new AbpException("Grant type was not implemented: " + configuration.GrantType);
                }
            }
        }
Exemple #4
0
        static async Task <TokenResponse> GetTokenResponse(DiscoveryDocumentResponse disco)
        {
            var client = new HttpClient();

            // request token
            var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest()
            {
                Address = disco.TokenEndpoint,

                ClientId     = _configuration["Auth0:ClientId"],
                ClientSecret = _configuration["Auth0:ClientSecret"],

                UserName = _configuration["Auth0:Username"],
                Password = _configuration["Auth0:Password"],

                Scope = "openid email profile offline_access calc:double",

                Parameters =
                {
                    { "audience", _configuration["CalculatorApi:ApiIdentifier"] }
                }
            });

            if (response.IsError)
            {
                Log.Error("Token error: {Error}\n{Description}", response.Error, response.ErrorDescription);
                throw new Exception(response.Error);
            }

            Log.Information("Access Token: {AccessToken}", response.AccessToken);
            Log.Information("Identity Token: {IdentityToken}", response.IdentityToken);
            Log.Information("Refresh Token: {RefreshToken}", response.RefreshToken);

            return(response);
        }
Exemple #5
0
        private static async Task <string> GetToken()
        {
            using var client = new HttpClient();
            DiscoveryDocumentResponse disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest()
            {
                Address = "https://login.microsoftonline.com/146ab906-a33d-47df-ae47-fb16c039ef96/v2.0/",
                Policy  =
                {
                    ValidateEndpoints = false
                }
            });

            if (disco.IsError)
            {
                throw new InvalidOperationException(
                          $"No discovery document. Details: {disco.Error}");
            }

            var tokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "67dd9cfb-4344-4cc8-a2ca-573f6bb4422f",
                ClientSecret = "tlVkd6QAX-kcl.XP_4Yslh00-2kPS6G_9_",
                Scope        = "api://67dd9cfb-4344-4cc8-a2ca-573f6bb4422f/.default"
            };

            var token = await client.RequestClientCredentialsTokenAsync(tokenRequest);

            if (token.IsError)
            {
                throw new InvalidOperationException($"Couldn't gather token. Details: {token.Error}");
            }

            return($"{token.TokenType} {token.AccessToken}");
        }
        public async Task <DeviceAuthorizationResponse> RequestDeviceAuthorizationAsync()
        {
            DiscoveryDocumentResponse disco = await DiscoveryCache.GetAsync();

            if (disco.IsError)
            {
                throw new Exception(disco.Error);
            }

            DeviceAuthorizationResponse response = await AuthHttpClient.RequestDeviceAuthorizationAsync(new DeviceAuthorizationRequest
            {
                Address      = disco.DeviceAuthorizationEndpoint,
                Scope        = Configuration["Scope"],
                ClientId     = Configuration["ClientId"],
                ClientSecret = Configuration["ClientSecret"],
            });

            string           url  = $"{ response.VerificationUri}?userCode={ response.UserCode}";
            ProcessStartInfo proc = new ProcessStartInfo(url)
            {
                UseShellExecute = true
            };

            Process.Start(proc);
            return(response);
        }
Exemple #7
0
        private async void button1_Click(object sender, EventArgs e)
        {
            var username = textBox1.Text;
            var pwd      = textBox2.Text;

            //发现文档
            using var client = new HttpClient();
            disco            = await client.GetDiscoveryDocumentAsync("http://localhost:5000/");

            if (disco.IsError)
            {
                MessageBox.Show(disco.Error);
                return;
            }

            //request token
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "winform client",
                ClientSecret = "winform secret",
                UserName     = username,
                Password     = pwd,
                Scope        = "test1Api openid profile",
            });

            textBox3.Text = tokenResponse.AccessToken;
        }
Exemple #8
0
        public async Task DoStuff(string[] args)
        {
            // discover endpoints from metadata
            HttpClient client = new HttpClient();

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

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

            // request token
            tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId     = "client",
                ClientSecret = "secret",
                Scope        = "api1"
            });

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

            Console.WriteLine(tokenResponse.Json);

            //await CallApi();
            await RequestTokenPwd();
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                HttpClient client = _httpClientFactory.CreateClient();

                DiscoveryDocumentResponse discoveryDocument = await client.GetDiscoveryDocumentAsync("https://localhost:44310/");

                TokenResponse tokenResponse = await client.RequestClientCredentialsTokenAsync(
                    new ClientCredentialsTokenRequest
                {
                    Address      = discoveryDocument.TokenEndpoint,
                    ClientId     = "client_worker_id",
                    ClientSecret = "client_worker_secret",
                    Scope        = "ApiTest"
                });

                client.SetBearerToken(tokenResponse.AccessToken);
                HttpResponseMessage response = await client.GetAsync("https://localhost:44356/secret");

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



                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                _logger.LogInformation("{0} from WORKER", content);

                await Task.Delay(1000, stoppingToken);
            }
        }
        // ACCESS TOKEN REQUEST
        public static async Task <TokenResponse> RequestToken(DiscoveryDocumentResponse disco)
        {
            var tokenResponse = await HttpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId     = "client",
                ClientSecret = "secret",
                Scope        = "api1"
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                throw new Exception(disco.Error);
            }

            var idToken      = tokenResponse.IdentityToken ?? "No Id Token";
            var refreshToken = tokenResponse.RefreshToken ?? "No Refresh Token";
            var accessToken  = tokenResponse.AccessToken ?? "No Acceess Token";

            Console.WriteLine("-----------------------ID TOKEN-----------------------");
            Console.WriteLine(idToken);
            Console.WriteLine("-----------------------REFRESH TOKEN-----------------------");
            Console.WriteLine(refreshToken);
            Console.WriteLine("-----------------------ACCESS TOKEN-----------------------");
            Console.WriteLine(accessToken);

            return(tokenResponse);
        }
        public async Task <Status <DiscoveryDocumentResponse> > GetDiscoveryDocumentAsync()
        {
            var output = new Status <DiscoveryDocumentResponse>();

            if (this.discoveryDoc == null)
            {
                var httpClient = new HttpClient();

                var d = await httpClient.GetDiscoveryDocumentAsync(this.config.AuthServerAddress);

                if (d.IsError)
                {
                    output.RecordFailure(d.Error, "GetDiscoveryDocumentAsync");
                }
                else
                {
                    this.discoveryDoc = d;
                }
            }

            if (output.IsSuccessful)
            {
                output.SetData(this.discoveryDoc);
            }

            return(output);
        }
Exemple #12
0
        private async Task <int> RevokeToken(string token, string tokenTypeHint, DiscoveryDocumentResponse disco)
        {
            Console.WriteLine($"Revoking {tokenTypeHint}...");
            var request = new TokenRevocationRequest
            {
                Address       = disco.DeviceAuthorizationEndpoint,
                ClientId      = configurationProvider.ClientId,
                Token         = token,
                TokenTypeHint = tokenTypeHint
            };

            logger.LogInformation("TokenRevocationRequest {Request}", request);

            var result = await httpClient.RevokeTokenAsync(request);

            if (result.IsError)
            {
                Console.WriteLine(result.Error);
                var ex = new Exception(result.Error);
                logger.LogError(ex, "RevokeTokenAsync {Request} {Response}", request, result);
                throw ex;
            }
            else
            {
                logger.LogInformation("RevokeTokenAsync {Request} {Response}", request, result);
            }
            Console.WriteLine($"Revoked {tokenTypeHint}...");
            return(0);
        }
        public async Task <HttpRequestMessage> GetRequestMessage()
        {
            //Wait on a semaphore to check the status, we only want to refresh the access token
            //once if multiple threads attempt to make a request when we need to refresh. This
            //will limit the throughput of this part of the function to just 1 thread at a time,
            //but the checks are pretty basic and should finish quickly. If you are seeing performance
            //problems because of this factory, this is likely why
            await refreshLocker.WaitAsync();

            try
            {
                if (discoveryClient == null)
                {
                    // discover endpoints from metadata
                    discoveryClient = await SharedHttpClientManager.SharedClient.GetDiscoveryDocumentAsync(options.IdServerHost);

                    if (discoveryClient.IsError)
                    {
                        throw new InvalidOperationException($"Error discovering endpoints from '{options.IdServerHost}' type: '{discoveryClient.ErrorType}' message: '{discoveryClient.Error}'");
                    }
                    await RefreshToken();
                }
                else if (DateTime.UtcNow > jwtExpiration)
                {
                    await RefreshToken();
                }
            }
            finally
            {
                refreshLocker.Release();
            }

            return(await next.GetRequestMessage());
        }
Exemple #14
0
        private async void btnLogin_Click(object sender, EventArgs e)
        {
            var phone = txtPhone.Text;
            var code  = txtCode.Text;

            //发现文档
            using var client = new HttpClient();
            disco            = await client.GetDiscoveryDocumentAsync("http://localhost:5000/");

            if (disco.IsError)
            {
                MessageBox.Show(disco.Error);
                return;
            }

            //request token
            var tokenResponse = await client.RequestTokenAsync(new TokenRequest
            {
                GrantType    = "phone_number",
                Address      = disco.TokenEndpoint,
                ClientId     = "phone_number_auth_client",
                ClientSecret = "phone_number_aut_secret",
                Parameters   = new Dictionary <string, string>
                {
                    { "phone", phone },
                    { "code", code }
                },
                //Scope = "test1Api openid profile",
            });

            txtAccessToken.Text = tokenResponse.AccessToken;
        }
Exemple #15
0
        private async Task <string> GetAccessToken()
        {
            var client = new HttpClient();
            DiscoveryDocumentResponse disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");

            var           tokenEndPoint = new HttpClient();
            TokenResponse response      = await tokenEndPoint.RequestTokenAsync(new TokenRequest
            {
                Address      = disco.TokenEndpoint,
                GrantType    = "client_credentials",
                ClientId     = "com.capital.bet.micro.stocks",
                ClientSecret = "731F408D-4C77-41F6-878E-06599B7C218B",
                Parameters   =
                {
                    { "scope", "capitalbet_api" }
                }
            });

            if (!response.IsError)
            {
                Token = response.AccessToken;
                return(Token);
            }
            return(null);
        }
Exemple #16
0
        private async ValueTask <DiscoveryDocumentResponse> GetDiscoAsync()
        {
            if (_disco != null)
            {
                return(_disco);
            }

            var discoveryRequest = new DiscoveryDocumentRequest()
            {
                Address = _issuerUrl,
                Policy  = new DiscoveryPolicy
                {
                    ValidateEndpoints = false, // okta has this issue
                }
            };

            using var client = _httpClientFactory.CreateClient();

            var disco = await client.GetDiscoveryDocumentAsync(discoveryRequest);

            if (disco.IsError)
            {
                throw new Exception(disco.Error);
            }

            _disco = disco;
            return(disco);
        }
        private async void RequestAccessToken_ButtonClick(object sender, RoutedEventArgs e)
        {
            //get user info
            var userName = UserNameInput.Text;
            var pwd      = PasswordInput.Password;

            // request access token
            var client = new HttpClient();

            _disco = await client.GetDiscoveryDocumentAsync(IdsConstants.Authority);

            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = _disco.TokenEndpoint,
                ClientId     = IdsConstants.ClientId,
                ClientSecret = IdsConstants.ClientSecret,
                UserName     = userName,
                Password     = pwd,
                Scope        = "Sample openid profile"
            });

            if (tokenResponse.IsError)
            {
                MessageBox.Show(tokenResponse.Error);
                return;
            }

            AccessToken = tokenResponse.AccessToken;
            AccessTokenTextBlock.Text = tokenResponse.Json.ToString();
        }
Exemple #18
0
        public async Task <(Result Result, Token Tokens)> PostRegisterLoginAsync(string userName,
                                                                                 string password,
                                                                                 CancellationToken cancellationToken)
        {
            logger.LogInformation("Starting login in {userName}", userName);

            DiscoveryDocumentResponse discoveryDocument = await httpClient.GetDiscoveryDocumentAsync(
                clientIdentity.Authority,
                cancellationToken);

            TokenResponse tokenResponse =
                await RequestTokenAsync(userName, password, discoveryDocument.TokenEndpoint, cancellationToken);

            if (tokenResponse.IsError)
            {
                Result result = Result.Failure(new InnerError(ErrorTarget.Token, tokenResponse.Error));

                logger.LogInformation("Error on login in {userName}. Errors: {@message}", userName, result.Errors);

                return(result, (Token)null);
            }

            logger.LogInformation("Successfully login in {userName}", userName);

            return(Result.Success(),
                   new Token(tokenResponse.AccessToken, tokenResponse.RefreshToken, tokenResponse.ExpiresIn));
        }
        public async Task <TokenResponse> RequestPasswordTokenAsync(string userName, string password)
        {
            DiscoveryDocumentResponse disco = await AuthHttpClient.GetDiscoveryDocumentAsync(DiscoveryDocument);

            if (disco.IsError)
            {
                throw new Exception(disco.Error);
            }
            TokenResponse response = await AuthHttpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = disco.TokenEndpoint,
                Scope        = Configuration["Scope"],
                GrantType    = Configuration["GrantType"],
                ClientId     = Configuration["ClientId"],
                ClientSecret = Configuration["ClientSecret"],

                UserName = userName,
                Password = password,
            });

            if (response.IsError)
            {
                throw new Exception(response.Error);
            }
            return(HttpToken = response);
        }
        public static async Task <ProviderInformation> GetProviderInformation()
        {
            // Discover endpoints from metadata.
            using HttpClient client = new ();

            // Create a discovery request
            using DiscoveryDocumentRequest discoveryDocumentRequest = new ()
                  {
                      Address = AdhIdentityUrl,
                      Policy  = new DiscoveryPolicy
                      {
                          ValidateIssuerName = false,
                      },
                  };

            DiscoveryDocumentResponse discoveryResponse =
                await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest).ConfigureAwait(false);

            return(discoveryResponse.IsError
                ? throw new Exception($"Error while getting the discovery document: {discoveryResponse.Error}")
                : new ProviderInformation()
            {
                IssuerName = discoveryResponse.Issuer,
                KeySet = discoveryResponse.KeySet,
                AuthorizeEndpoint = discoveryResponse.AuthorizeEndpoint,
                TokenEndpoint = discoveryResponse.TokenEndpoint,
                EndSessionEndpoint = discoveryResponse.EndSessionEndpoint,
                UserInfoEndpoint = discoveryResponse.UserInfoEndpoint,
                TokenEndPointAuthenticationMethods =
                    discoveryResponse.TokenEndpointAuthenticationMethodsSupported,
            });
        }
Exemple #21
0
        static async Task <TokenResponse> RefreshTokenResponse(DiscoveryDocumentResponse disco, string refreshToken)
        {
            var client = new HttpClient();

            // request token
            var response = await client.RequestRefreshTokenAsync(new RefreshTokenRequest()
            {
                Address = disco.TokenEndpoint,

                ClientId     = _configuration["Auth0:ClientId"],
                ClientSecret = _configuration["Auth0:ClientSecret"],

                RefreshToken = refreshToken
            });

            if (response.IsError)
            {
                Log.Error("Token error: {Error}\n{Description}", response.Error, response.ErrorDescription);
                throw new Exception(response.Error);
            }

            Log.Information("Access Token: {AccessToken}", response.AccessToken);
            Log.Information("Identity Token: {IdentityToken}", response.IdentityToken);
            Log.Information("Refresh Token: {RefreshToken}", response.RefreshToken);

            return(response);
        }
Exemple #22
0
        public async Task <IActionResult> Logout()
        {
            DiscoveryCache discoveryCache = (DiscoveryCache)HttpContext
                                            .RequestServices.GetService(typeof(IDiscoveryCache));
            DiscoveryDocumentResponse discovery = await discoveryCache.GetAsync();

            if (!discovery.IsError)
            {
                return(Redirect(discovery.EndSessionEndpoint));
            }
            else
            {
                _logger.Warning(discovery.Error);
            }

            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            await HttpContext.SignOutAsync("oidc");

            foreach (var cookie in Request.Cookies)
            {
                Response.Cookies.Delete(cookie.Key);
            }

            string url = _appSettings.Authorization.AuthorizationService.MainTrim;

            url += "/Home/Index";
            return(Redirect(url));
        }
Exemple #23
0
        private async Task ConfigRequestClientCredentials(HttpClient httpClient, ClientCredentials client)
        {
            // Less than zero t1 is earlier than t2.
            Boolean isTokenExpired = DateTime.Compare(this.TokenExpiration, DateTime.Now) < 0;

            if (this._token == null || isTokenExpired)
            {
                DiscoveryDocumentResponse disco = await httpClient.GetDiscoveryDocumentAsync(client.BaseAuthUrl);

                this._token = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
                {
                    ClientId     = client.ClientId,
                    ClientSecret = client.ClientSecret,
                    Address      = disco.TokenEndpoint,
                    Scope        = client.Scope
                });

                this.TokenExpiration = DateTime.Now.AddSeconds((this._token.ExpiresIn - 60));
            }

            string authorizationHeader = "Authorization";

            if (httpClient.DefaultRequestHeaders.Contains(authorizationHeader))
            {
                httpClient.DefaultRequestHeaders.Remove(authorizationHeader);
            }

            httpClient.DefaultRequestHeaders.TryAddWithoutValidation(authorizationHeader, $"Bearer {this._token.AccessToken}");
        }
Exemple #24
0
        public async Task <AuthenticationCredentials> Authenticate(UserCredential userCredentials)
        {
            string identityServerURL = configurationApp.GetValue <string>(APP_CONFIG_KEY_IDSERVER_URL);

            HttpClient httpClient = new HttpClient();

            DiscoveryDocumentResponse idServerDocument = await httpClient.GetDiscoveryDocumentAsync(identityServerURL);

            if (idServerDocument.IsError)
            {
                throw new Exception(idServerDocument.Error);
            }

            TokenResponse tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest()
            {
                Address      = idServerDocument.TokenEndpoint,
                ClientId     = userCredentials.UserName,
                ClientSecret = userCredentials.Password,
                Scope        = API_SCOPE
            });

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

            return(new AuthenticationCredentials()
            {
                CredentialToken = tokenResponse.AccessToken
            });
        }
Exemple #25
0
        private async void RequestAccessToken_ButtonClick(object sender, RoutedEventArgs e)
        {
            var userName = UsernameInput.Text;
            var password = PasswordInput.Password;


            //request access token
            var client = new HttpClient();

            var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001/");

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

            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "wpf client",
                ClientSecret = "wpf secret",
                Scope        = "scope1 openid profile address phone email",
                UserName     = userName,
                Password     = password
            });

            if (tokenResponse.IsError)
            {
                MessageBox.Show(tokenResponse.Error);
                return;
            }
            _accessToken = tokenResponse.AccessToken;
            AccessTokenTextBlock.Text = tokenResponse.Json.ToString();
        }
        private HttpRequestMessage GetTokenRequestMessage(DiscoveryDocumentResponse disco,
                                                          string authorizationCode, string codeVerifier)
        {
            var tokenUrl = disco.TokenEndpoint;

            var parameters = new List <KeyValuePair <string, string> > {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("code", authorizationCode),
                new KeyValuePair <string, string>("code_verifier", codeVerifier),
                new KeyValuePair <string, string>("client_id", _oidcOptions.ClientId),
                new KeyValuePair <string, string>("redirect_uri", _oidcOptions.RedirectUri)
            };

            if (_oidcOptions.ClientSecret != null)
            {
                parameters.Add(new KeyValuePair <string, string>("client_secret", _oidcOptions.ClientSecret));
            }

            var msg = new HttpRequestMessage()
            {
                Content    = new FormUrlEncodedContent(parameters),
                Method     = HttpMethod.Post,
                RequestUri = new Uri(tokenUrl)
            };

            return(msg);
        }
Exemple #27
0
        private async Task <DiscoveryDocumentResponse> discoverDocumentAsync()
        {
            var httpClient = this.httpClientFactory.CreateClient(HttpClientNameFactory.AuthHttpClient);
            DiscoveryDocumentResponse discoResponse = null;

            if (this.remoteServiceBaseUrl.StartsWith("https"))
            {
                discoResponse = await httpClient.GetDiscoveryDocumentAsync(this.remoteServiceBaseUrl);
            }
            else
            {
                discoResponse = await httpClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
                {
                    Address = this.remoteServiceBaseUrl,
                    Policy  =
                    {
                        RequireHttps = false // default: true
                    }
                });
            }

            if (discoResponse.IsError)
            {
                throw new Exception(discoResponse.Error);
            }

            return(discoResponse);
        }
        public async Task <IActionResult> Index()
        {
            //retrieve access token
            HttpClient client = _httpClientFactory.CreateClient();
            DiscoveryDocumentResponse discoveryDocument = await client.GetDiscoveryDocumentAsync("https://localhost:44310/");

            TokenResponse tokenResponse = await client.RequestClientCredentialsTokenAsync(
                new ClientCredentialsTokenRequest
            {
                Address      = discoveryDocument.TokenEndpoint,
                ClientId     = "client_id",
                ClientSecret = "client_secret",
                Scope        = "ApiTest"
            });

            client.SetBearerToken(tokenResponse.AccessToken);
            HttpResponseMessage response = await client.GetAsync("https://localhost:44356/secret");

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

            return(Ok(new
            {
                access_token = tokenResponse.AccessToken,
                message = content
            }));
        }
 public TokenService()
 {
     using (var client = new HttpClient())
     {
         _discDocument = client.GetDiscoveryDocumentAsync("https://localhost:44322/.well-known/openid-configuration").Result;
     }
 }
Exemple #30
0
        private static async Task <string> GetToken()
        {
            using var client = new HttpClient();

            DiscoveryDocumentResponse disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest()
            {
                Address = "https://login.microsoftonline.com/146ab906-a33d-47df-ae47-fb16c039ef96/v2.0/",
                Policy  =
                {
                    ValidateEndpoints = false
                }
            });

            if (disco.IsError)
            {
                throw new InvalidOperationException(
                          $"No discovery document. Details: {disco.Error}");
            }

            var tokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "fce95216-40e5-4a34-b041-f287e46532be",
                ClientSecret = "XWGsyzt9uM-Ia2SA8WE7~gvUJ~4og-U_1p",
                Scope        = "api://fce95216-40e5-4a34-b041-f287e46532be/.default"
            };
            var token = await client.RequestClientCredentialsTokenAsync(tokenRequest);

            if (token.IsError)
            {
                throw new InvalidOperationException($"Couldn't gather token. Details: {token.Error}");
            }

            return(token.AccessToken);
        }