public async Task Http_request_should_have_correct_format() { var handler = new NetworkHandler(HttpStatusCode.NotFound, "not found"); var client = new HttpClient(handler); var request = new DiscoveryDocumentRequest { Address = _endpoint }; request.Headers.Add("custom", "custom"); request.Properties.Add("custom", "custom"); var response = await client.GetDiscoveryDocumentAsync(request); var httpRequest = handler.Request; httpRequest.Method.Should().Be(HttpMethod.Get); httpRequest.RequestUri.Should().Be(new Uri(_endpoint)); httpRequest.Content.Should().BeNull(); var headers = httpRequest.Headers; headers.Count().Should().Be(2); headers.Should().Contain(h => h.Key == "custom" && h.Value.First() == "custom"); var properties = httpRequest.Properties; properties.Count.Should().Be(1); var prop = properties.First(); prop.Key.Should().Be("custom"); ((string)prop.Value).Should().Be("custom"); }
private DiscoveryDocumentResponse GetDiscoveryDocument(SecuritySettings settings) { var httpClient = _httpClientFactory.CreateClient(); var authority = settings.OpenId.Authority; if (settings.IsAzureAd) { authority = $"{settings.OpenId.Authority}/v2.0"; } var request = new DiscoveryDocumentRequest() { Address = authority, Policy = new DiscoveryPolicy() { ValidateEndpoints = settings.IsAzureAd ? false : true } }; var discoveryDocument = httpClient.GetDiscoveryDocumentAsync(request) .GetAwaiter() .GetResult(); return(discoveryDocument); }
private async Task <string> AuthenticateAsync(AppSettings.Subscription subscription) { var httpClient = _httpClientFactory.CreateClient(); var request = new DiscoveryDocumentRequest() { Address = subscription.IdentityServerUrl.ToString(), }; request.Policy.RequireHttps = false; request.Policy.ValidateIssuerName = false; var disco = await httpClient.GetDiscoveryDocumentAsync(request); if (disco.IsError) { throw new Exception(disco.Error); } // request token var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = subscription.Client.Id, ClientSecret = subscription.Client.Secret, Scope = "api" }); if (tokenResponse.IsError) { throw new Exception(tokenResponse.Error); } return(tokenResponse.AccessToken); }
/// <summary> /// 获取Token返回 /// </summary> /// <param name="account"></param> /// <param name="password"></param> /// <param name="type"></param> /// <returns></returns> public static async Task <TokenResponse> GetTokenResponseAsync(string account, string password, LoginCategory type = LoginCategory.Password) { var discoveryDocumentRequest = new DiscoveryDocumentRequest { Address = ApplicationConfig.IdentityServer.Url, Policy = new DiscoveryPolicy { RequireHttps = false } }; var client = new HttpClient(); DiscoveryResponse discoveryResponse = await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest); if (discoveryResponse.IsError) { throw new InvalidOperationException("连接认证服务器失败"); } TokenResponse tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = discoveryResponse.TokenEndpoint, ClientId = "Web", ClientSecret = ApplicationConfig.IdentityServer.Secret, UserName = account, Password = password, Scope = ApplicationConfig.IdentityServer.Scope, Parameters = { { "type", type.ToString() } } }); return(tokenResponse); }
public static async Task <ProviderInformation> GetProviderInformation() { // Discover endpoints from metadata. using var client = new HttpClient(); // Create a discovery request using var discoveryDocumentRequest = new DiscoveryDocumentRequest { Address = OcsIdentityUrl, Policy = new DiscoveryPolicy { ValidateIssuerName = false, }, }; var 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, }); }
public static async Task <string> GetTokenEndpointFromDiscoveryDocument(this HttpClient authorityHttpClient, TokenHandlerOptions options) { var discoveryRequest = new DiscoveryDocumentRequest { Address = options.Authority, Policy = options.DiscoveryPolicy, }; var discoveryResponse = await authorityHttpClient.GetDiscoveryDocumentAsync(discoveryRequest).ConfigureAwait(false); if (discoveryResponse.IsError) { if (discoveryResponse.ErrorType == ResponseErrorType.Http) { throw new InvalidOperationException($"Discovery endpoint {discoveryRequest.Address} is unavailable: {discoveryResponse.Error}"); } if (discoveryResponse.ErrorType == ResponseErrorType.PolicyViolation) { throw new InvalidOperationException($"Policy error while contacting the discovery endpoint {discoveryRequest.Address}: {discoveryResponse.Error}"); } if (discoveryResponse.ErrorType == ResponseErrorType.Exception) { throw new InvalidOperationException($"Error parsing discovery document from {discoveryRequest.Address}: {discoveryResponse.Error}"); } } return(discoveryResponse.TokenEndpoint); }
public async Task <ResultModel <UserLoginResultModel> > Login(UserLoginRequestModel requestModel) { var discoveryDocumentRequest = new DiscoveryDocumentRequest { Address = ApplicationConfig.IdentityServer.Url, Policy = new DiscoveryPolicy { RequireHttps = false } }; var client = new HttpClient(); DiscoveryResponse discoveryResponse = await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest); if (discoveryResponse.IsError) { return(ResultModel <UserLoginResultModel> .Fail("连接认证服务器失败")); } TokenResponse tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = discoveryResponse.TokenEndpoint, ClientId = ClientType.Web.ToString(), ClientSecret = ApplicationConfig.IdentityServer.Secret, UserName = requestModel.Account, Password = requestModel.Password, Scope = ApplicationConfig.IdentityServer.Scope }); if (tokenResponse.IsError) { return(ResultModel <UserLoginResultModel> .Fail(tokenResponse.ErrorDescription)); } var result = new UserLoginResultModel(tokenResponse.Raw.JsonToObject <TokenResultModel>()); return(ResultModel <UserLoginResultModel> .Success(result, "登录成功")); }
/// <summary> /// 刷新 Access Token /// </summary> /// <param name="_RefreshToken"></param> /// <param name="address"></param> /// <returns></returns> private bool RefreshToken(string _RefreshToken, string address) { HttpClient _client = new HttpClient(); DiscoveryPolicy policy = new DiscoveryPolicy { RequireHttps = false }; DiscoveryDocumentRequest request = new DiscoveryDocumentRequest(); request.Address = address; request.Policy = policy; var _discover = _client.GetDiscoveryDocumentAsync(request).Result; if (!_discover.IsError) { var rcct = new RefreshTokenRequest(); rcct.Address = _discover.TokenEndpoint; rcct.ClientId = FDConst.IS_Client; rcct.ClientSecret = FDConst.IS_ClientSecret; rcct.RefreshToken = _RefreshToken; var token = _client.RequestRefreshTokenAsync(rcct).Result; if (!token.IsError) { //Set new Access token //Commonutility.GetContext().SetValue(FDConst.IS_AuthenticationToken, token.AccessToken); //set new refresh token //Commonutility.GetContext().SetValue(FDConst.IS_AuthenticationRefreshToken, token.RefreshToken); } return(token.IsError); } return(_discover.IsError); }
private Task <UserInfoResponse> CreatTokenValidationTask(string token) { return(Task.Run <UserInfoResponse>(async() => { _logger.LogDebug("about to validate the token on remote identity server."); var client = new HttpClient(); var discoRequest = new DiscoveryDocumentRequest() { Address = this._authServerUrl, Policy = new DiscoveryPolicy() { RequireHttps = this._requireHttps } }; var disco = await client.GetDiscoveryDocumentAsync(discoRequest); client.SetBearerToken(token); var response = await client.GetUserInfoAsync(new UserInfoRequest { Address = disco.UserInfoEndpoint, Token = token }); _logger.LogDebug("get validate resonse from identity server."); return response; })); }
public async Task <DiscoveryDocumentResponse> DiscoveryDocument(string url) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException("discoveryDocument"); } try { var discoveryRequest = new DiscoveryDocumentRequest() { Address = url, Policy = new DiscoveryPolicy { ValidateEndpoints = false } }; var disco = await Client.GetDiscoveryDocumentAsync(discoveryRequest); if (disco.IsError) { throw new Exception(disco.Error); } return(disco); } catch (Exception ex) { Logger.LogError(ex, ex.Message); throw; } }
private async Task <string> GetTokenAsync(Func <HttpClient, DiscoveryDocumentResponse, Task <TokenResponse> > tokenResponseProvider) { using (var client = new HttpClient()) { var discoveryDocumentRequest = new DiscoveryDocumentRequest { Address = _authorityUri, Policy = { ValidateIssuerName = false, RequireHttps = false } }; var disco = await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest); if (disco.IsError) { throw new Exception(disco.Error); } var response = await tokenResponseProvider(client, disco); if (response.IsError) { throw new Exception(response.Error); } return(response.AccessToken); } }
public async Task <JObject> AcquireAccessToken(string identityServerIp, string usertel, string password) { var client = new HttpClient(); var discoveryClient = new DiscoveryDocumentRequest() { Address = identityServerIp, Policy = new DiscoveryPolicy { RequireHttps = false } }; var disco = await client.GetDiscoveryDocumentAsync(discoveryClient); if (disco.IsError) { this._logger.LogError(disco.Error); } var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = "client2", ClientSecret = "secret", GrantType = GrantType.ResourceOwnerPassword, UserName = usertel, Password = password }); return(tokenResponse.Json); }
public async Task <IActionResult> UserInfo() { var client = httpClientFactory.CreateClient(HttpClientNames.Identity); using var discoveryDocumentRequest = new DiscoveryDocumentRequest { Policy = new DiscoveryPolicy { RequireHttps = false }, }; var metaDataResponse = await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest); if (metaDataResponse.IsError) { throw new HttpRequestException($"DiscoveryDocumentError : {metaDataResponse.Error}"); } var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken); using var userInfoRequest = new UserInfoRequest { Address = metaDataResponse.UserInfoEndpoint, Token = accessToken, }; var userInfoResponse = await client.GetUserInfoAsync(userInfoRequest); if (userInfoResponse.IsError) { throw new HttpRequestException($"UserInfoResponse : {userInfoResponse.Error}"); } return(View(new UserInfoViewModel { UserClaims = userInfoResponse.Claims, AccessToken = accessToken })); }
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); }
static async Task Main(string[] args) { Console.ReadLine(); var client = new HttpClient(); var request = new DiscoveryDocumentRequest { Address = "http://u.ke.me/", Policy = { RequireHttps = false } }; var disco = await client.GetDiscoveryDocumentAsync(request); if (disco.IsError) { Console.WriteLine(disco.Error); Console.ReadLine(); return; } var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = "api", ClientSecret = "secret", UserName = "******", Password = "******", Scope = "api" }); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); Console.ReadLine(); return; } do { Console.ReadLine(); var apiClient = new HttpClient(); apiClient.SetBearerToken(tokenResponse.AccessToken); var response = await apiClient.GetAsync("http://localhost:5000/userservice/user/index"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } } while (true); }
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 ClaimsPrincipal GetClaimsPrincipal(string idToken, string issuer) { var client = new System.Net.Http.HttpClient(); var r = new DiscoveryDocumentRequest(); r.Policy.RequireHttps = false; r.Address = issuer; var disco = client.GetDiscoveryDocumentAsync(r).Result; if (keys is null) { keys = new List <SecurityKey>(); } foreach (var webKey in disco.KeySet.Keys) { var e = Base64Url.Decode(webKey.E); var n = Base64Url.Decode(webKey.N); var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) { KeyId = webKey.Kid }; keys.Add(key); } var parameters = new TokenValidationParameters { ValidIssuer = disco.Issuer, RequireAudience = false, ValidateAudience = false, IssuerSigningKey = keys.FirstOrDefault(), IssuerSigningKeys = keys, RequireSignedTokens = true }; var tokenHandler = new JwtSecurityTokenHandler(); try { return(tokenHandler.ValidateToken(idToken, parameters, out var _)); } catch (Exception e) { return(null); } }
public async Task <DiscoveryResponse> GetAddressesAsync(CancellationToken?cancellationToken) { if (this.discoveryResponse == null) { var request = new DiscoveryDocumentRequest() { Address = Authority, }; var result = await httpClient.GetDiscoveryDocumentAsync(request, cancellationToken ?? CancellationToken.None); this.discoveryResponse = result; } return(this.discoveryResponse); }
public async Task DiscoveryUrlShownInDiscoveryDocument_Success() { var discoveryDocumentRequest = new DiscoveryDocumentRequest { Address = IdentityServerUrl }; var discoClient = new HttpClient(IdentityTestServer.CreateHandler()); var discoDocument = await discoClient.GetDiscoveryDocumentAsync(discoveryDocumentRequest); var discoveryUri = discoDocument.TryGetValue("discovery_uri"); Assert.NotNull(discoveryUri); }
/// <summary> /// This method is used to contact an authority discovery endpoint for information for interacting with the authority. /// </summary> /// <param name="authorityUri">Contains the authority URI to contact.</param> /// <param name="cancellationToken">Contains a cancellation token.</param> /// <returns>Returns a <see cref="DiscoveryDocumentResponse"/> object when successful.</returns> protected async Task <DiscoveryDocumentResponse> RequestDiscoveryAsync(Uri authorityUri, CancellationToken cancellationToken) { DiscoveryDocumentResponse result; using (DiscoveryDocumentRequest documentRequest = new DiscoveryDocumentRequest { Address = authorityUri.ToString() }) using (HttpClient client = new HttpClient()) { result = await client.GetDiscoveryDocumentAsync(documentRequest, cancellationToken) .ConfigureAwait(false); } return(result); }
protected virtual async Task <DiscoveryDocumentResponse> GetDiscoveryResponse(IdentityClientConfiguration configuration) { using (var httpClient = HttpClientFactory.CreateClient(HttpClientName)) { var request = new DiscoveryDocumentRequest { Address = configuration.Authority, Policy = { RequireHttps = configuration.RequireHttps } }; IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request); return(await httpClient.GetDiscoveryDocumentAsync(request)); } }
public async Task <OAuthToken> Login(string login, string password) { var client = WebConnectionService.Client; var request = new DiscoveryDocumentRequest { Address = ApiSettingsService.AuthorizationHostUrl }; request.Policy.RequireHttps = false; request.Policy.ValidateIssuerName = false; var identityServer = await client.GetDiscoveryDocumentAsync(request); if (identityServer.IsError) { throw identityServer.Exception; } var tokenResponce = await client.RequestPasswordTokenAsync( new PasswordTokenRequest { Address = identityServer.TokenEndpoint, ClientId = ApiSettingsService.OAuthSettings.ClientId, ClientSecret = ApiSettingsService.OAuthSettings.ClientSecret, Password = password, UserName = login, Scope = ApiSettingsService.OAuthSettings.ResourceId }); if (tokenResponce.IsError || tokenResponce.AccessToken == null) { if (tokenResponce.ErrorType == ResponseErrorType.Protocol && tokenResponce.Error == ApiSettingsService.OAuthSettings.InvalidCredentialsErrorKey) { throw new InvalidCredentialException("Invalid Credentials", tokenResponce.Exception); } var err = $"{tokenResponce.ErrorType} > {tokenResponce.Error} > {tokenResponce.ErrorDescription}"; throw new Exception(err, tokenResponce.Exception); } return(new OAuthToken(tokenResponce.AccessToken)); }
public async Task GivenAnUserIsLoggedInWithUsernameAndPassword(Table table) { var discoveryAddress = Configuration.GetValue <string>("DiscoveryAddress"); using var client = new HttpClient(); using var discoveryDocumentRequest = new DiscoveryDocumentRequest { Policy = new DiscoveryPolicy { RequireHttps = false }, Address = discoveryAddress, }; var discoveryDocument = await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest); if (discoveryDocument.IsError) { Console.WriteLine(discoveryDocument.Error); return; } var user = table.CreateSet <UserTable>().First(); using var passwordTokenRequest = new PasswordTokenRequest { Address = discoveryDocument.TokenEndpoint, ClientId = "PasswordClient", ClientSecret = "PasswordSecret", UserName = user.Username, Password = user.Password, Scope = user.Scope, }; TokenResponse tokenResponse = await client.RequestPasswordTokenAsync(passwordTokenRequest); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } context[ScenarioContextKeys.AccessToken] = tokenResponse.AccessToken; }
public async Task <string> Authenticate(string login, string password, IEnumerable <string> scopes, CancellationToken token = default) { var discoverRequest = new DiscoveryDocumentRequest { Address = _serverSettings.Host, Policy = { RequireHttps = false, ValidateIssuerName = false, ValidateEndpoints = false } }; var disco = await _client.GetDiscoveryDocumentAsync(discoverRequest , token); if (disco.IsError) { throw new Exception(disco.Error); } var tokenResponse = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = _serverSettings.Client, ClientSecret = _serverSettings.Secret, UserName = login, Password = password, Scope = string.Join(" ", scopes ?? Enumerable.Empty <string>()) }, cancellationToken : token); if (tokenResponse.IsError) { throw new Exception(tokenResponse.Error); } return(tokenResponse.AccessToken); }
public async Task <DevicesApiBuilder> WithClientCredentials() { #if UseAuthentication using (var identityClient = new HttpClient()) { var discoveryDocument = new DiscoveryDocumentRequest { Address = GenericHelper.GetUriFromEnvironmentVariable(DefaultConstants.AuthenticationAuthority).ToString() }; discoveryDocument.Policy.RequireHttps = false; var discoveryResponse = await identityClient.GetDiscoveryDocumentAsync(discoveryDocument); if (discoveryResponse.IsError) { Assert.True(false, discoveryResponse.Error); return(this); } // request token var tokenResponse = await identityClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = discoveryResponse.TokenEndpoint, ClientId = DefaultConstants.DeviceManagerTestClient, ClientSecret = TestConstants.DeviceManagerTestClientSecret, Scope = DefaultConstants.ApiName }); if (tokenResponse.IsError) { Assert.True(false, tokenResponse.Error); return(this); } testContextFactory.Client.SetBearerToken(tokenResponse.AccessToken); } #endif return(this); }
protected virtual async Task <IdentityModelDiscoveryDocumentCacheItem> GetDiscoveryResponse(IdentityClientConfiguration configuration) { var tokenEndpointUrlCacheKey = CalculateDiscoveryDocumentCacheKey(configuration); var discoveryDocumentCacheItem = await DiscoveryDocumentCache.GetAsync(tokenEndpointUrlCacheKey); if (discoveryDocumentCacheItem == null) { DiscoveryDocumentResponse discoveryResponse; using (var httpClient = HttpClientFactory.CreateClient(HttpClientName)) { var request = new DiscoveryDocumentRequest { Address = configuration.Authority, Policy = { RequireHttps = configuration.RequireHttps } }; IdentityModelHttpRequestMessageOptions.ConfigureHttpRequestMessage?.Invoke(request); discoveryResponse = await httpClient.GetDiscoveryDocumentAsync(request); } if (discoveryResponse.IsError) { throw new AbpException($"Could not retrieve the OpenId Connect discovery document! " + $"ErrorType: {discoveryResponse.ErrorType}. Error: {discoveryResponse.Error}"); } discoveryDocumentCacheItem = new IdentityModelDiscoveryDocumentCacheItem(discoveryResponse.TokenEndpoint, discoveryResponse.DeviceAuthorizationEndpoint); await DiscoveryDocumentCache.SetAsync(tokenEndpointUrlCacheKey, discoveryDocumentCacheItem, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(configuration.CacheAbsoluteExpiration) }); } return(discoveryDocumentCacheItem); }
private async Task <DiscoveryDocumentResponse> GetDiscoveryEndpoints(HttpClient client) { var idpEndpoint = $"{_azureAdConfiguration.Instance}{_azureAdConfiguration.TenantId}/v2.0"; var discoveryDocumentRequest = new DiscoveryDocumentRequest { Address = idpEndpoint, Policy = new DiscoveryPolicy { // turned off => Azure AD uses different domains. ValidateEndpoints = false } }; var disco = await HttpClientDiscoveryExtensions .GetDiscoveryDocumentAsync(client, discoveryDocumentRequest); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } return(disco); }
public async Task <DiscoveryM> GetRemoteDiscovery() { DiscoveryM result = new DiscoveryM(); using (var client = new HttpClient()) { var discoveryDocument = new DiscoveryDocumentRequest { Address = Config.Address }; discoveryDocument.Policy.RequireHttps = false; var response = await client.GetDiscoveryDocumentAsync(discoveryDocument); if (response.IsError) { throw new Exception(response.Error); } result = Mapper.Map <DiscoveryM>(response); } return(result); }
public Func <string> GetToken( string username, string password, string authorityUrl, string clientName, string apiName, string apiSecret) { return(() => { if (null != _response) { var jwttoken = _jwthandler.ReadToken(_response.AccessToken); if (jwttoken.ValidTo > DateTime.Now) { return _response.AccessToken; } } var client = new HttpClient(); var request = new DiscoveryDocumentRequest() { Policy = { RequireHttps = false, RequireKeySet = false, ValidateEndpoints = false, ValidateIssuerName = false }, Address = authorityUrl }; return RetryPolicies.WaitAndRetryForever <Exception, string>( attemptDelay: TimeSpan.FromMilliseconds(10000), onRetry: (ex, timespan) => this.LogError($"Failed to reach auth server {authorityUrl} - [{ex}]- [{ex.InnerException}]"), doTry: () => { var disco = client.GetDiscoveryDocumentAsync(request).Result; if (disco.IsError) { throw new Exception(disco.Error); } _response = client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = clientName, ClientSecret = apiSecret, Scope = apiName, UserName = username, Password = password }).Result; if (_response.IsError) { throw new Exception("Failed to acquire token", _response.Exception); } return _response.AccessToken; } ); }); }
/// <summary> /// Sends a discovery document request /// </summary> /// <param name="client">The client.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public static async Task <DiscoveryDocumentResponse> GetDiscoveryDocumentAsync(this HttpMessageInvoker client, DiscoveryDocumentRequest request, CancellationToken cancellationToken = default) { string address; if (request.Address.IsPresent()) { address = request.Address; } else if (client is HttpClient httpClient) { address = httpClient.BaseAddress.AbsoluteUri; } else { throw new ArgumentException("An address is required."); } var parsed = DiscoveryEndpoint.ParseUrl(address, request.Policy.DiscoveryDocumentPath); var authority = parsed.Authority; var url = parsed.Url; if (request.Policy.Authority.IsMissing()) { request.Policy.Authority = authority; } var jwkUrl = ""; if (!DiscoveryEndpoint.IsSecureScheme(new Uri(url), request.Policy)) { return(ProtocolResponse.FromException <DiscoveryDocumentResponse>(new InvalidOperationException("HTTPS required"), $"Error connecting to {url}. HTTPS required.")); } try { var clone = request.Clone(); clone.Method = HttpMethod.Get; clone.Prepare(); clone.RequestUri = new Uri(url); var response = await client.SendAsync(clone, cancellationToken).ConfigureAwait(); string responseContent = null; if (response.Content != null) { responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(); } if (!response.IsSuccessStatusCode) { return(await ProtocolResponse.FromHttpResponseAsync <DiscoveryDocumentResponse>(response, $"Error connecting to {url}: {response.ReasonPhrase}").ConfigureAwait()); } var disco = await ProtocolResponse.FromHttpResponseAsync <DiscoveryDocumentResponse>(response, request.Policy).ConfigureAwait(); if (disco.IsError) { return(disco); } try { jwkUrl = disco.JwksUri; if (jwkUrl != null) { var jwkClone = request.Clone <JsonWebKeySetRequest>(); jwkClone.Method = HttpMethod.Get; jwkClone.Address = jwkUrl; jwkClone.Prepare(); var jwkResponse = await client.GetJsonWebKeySetAsync(jwkClone, cancellationToken).ConfigureAwait(); if (jwkResponse.IsError) { return(await ProtocolResponse.FromHttpResponseAsync <DiscoveryDocumentResponse>(jwkResponse.HttpResponse, $"Error connecting to {jwkUrl}: {jwkResponse.HttpErrorReason}").ConfigureAwait()); } disco.KeySet = jwkResponse.KeySet; } return(disco); } catch (Exception ex) { return(ProtocolResponse.FromException <DiscoveryDocumentResponse>(ex, $"Error connecting to {jwkUrl}. {ex.Message}.")); } } catch (Exception ex) { return(ProtocolResponse.FromException <DiscoveryDocumentResponse>(ex, $"Error connecting to {url}. {ex.Message}.")); } }