internal async Task <DeviceAuthorizationResponse> BeginLogin() { var client = _clientFactory.CreateClient(); var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(client, _authConfigurations.Value.StsServer); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } var deviceAuthorizationRequest = new DeviceAuthorizationRequest { Address = disco.DeviceAuthorizationEndpoint, ClientId = "deviceFlowWebClient" }; deviceAuthorizationRequest.Scope = "email profile openid"; var response = await client.RequestDeviceAuthorizationAsync(deviceAuthorizationRequest); if (response.IsError) { throw new Exception(response.Error); } return(response); }
public async Task <string> GetAccessTockenAsync() { var identityServerAddress = config["IdentityServer:URL"]; try { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(httpClient, identityServerAddress); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } var tokenResponse = await HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync(httpClient, new ClientCredentialsTokenRequest { Scope = config["ClientIdentity:Scope"], ClientSecret = config["ClientIdentity:ClientSecret"], Address = disco.TokenEndpoint, ClientId = config["ClientIdentity:ClientId"] }); if (tokenResponse.IsError) { throw new ApplicationException($"Status code: {tokenResponse.IsError}, Error: {tokenResponse.Error}"); } return(tokenResponse.AccessToken); } catch (Exception e) { throw new ApplicationException($"Exception {e}"); } }
public async Task <string> GetAccessTokenAsync() { try { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(_tokenclient, stsServer); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } var tokenResponse = await HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync(_tokenclient, new ClientCredentialsTokenRequest { Scope = "grpc_protected_scope", ClientSecret = "grpc_protected_secret", Address = disco.TokenEndpoint, ClientId = "ProtectedGrpc" }); if (tokenResponse.IsError) { throw new ApplicationException($"Status code: {tokenResponse.IsError}, Error: {tokenResponse.Error}"); } return(tokenResponse.AccessToken); //throw new ApplicationException($"Status code: {response.StatusCode}, Error: {response.ReasonPhrase}"); } catch (Exception e) { throw new ApplicationException($"Exception {e}"); } }
private async Task <AccessTokenItem> RequestNewToken(string clientName, string apiScope, string secret) { try { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(_httpClient, "http://localhost:5000"); if (disco.IsError) { throw new ApplicationException($"Error: {disco.Error}"); } var tokenResponse = await HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync(_httpClient, new ClientCredentialsTokenRequest { Scope = apiScope, ClientId = clientName, ClientSecret = secret, Address = disco.TokenEndpoint }); if (tokenResponse.IsError) { throw new ApplicationException($"Error: {tokenResponse.Error}"); } return(new AccessTokenItem { AccessToken = tokenResponse.AccessToken, Expiry = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn) }); } catch (Exception ex) { throw new ApplicationException($"Exceptions: {ex}"); } }
public async Task <IActionResult> RenewTokens() { var tokenclient = _clientFactory.CreateClient(); var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( tokenclient, _optionsAuthConfiguration.StsServerIdentityUrl); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } var rt = await HttpContext.GetTokenAsync("refresh_token"); var tokenResult = await HttpClientTokenRequestExtensions.RequestRefreshTokenAsync(tokenclient, new RefreshTokenRequest { ClientSecret = "secret", Address = disco.TokenEndpoint, ClientId = "mvc.hybrid.backchannel", RefreshToken = rt }); if (!tokenResult.IsError) { var old_id_token = await HttpContext.GetTokenAsync("id_token"); var new_access_token = tokenResult.AccessToken; var new_refresh_token = tokenResult.RefreshToken; var tokens = new List <AuthenticationToken> { new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token }, new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token }, new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token } }; var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn); tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) }); var info = await HttpContext.AuthenticateAsync("Cookies"); info.Properties.StoreTokens(tokens); await HttpContext.SignInAsync("Cookies", info.Principal, info.Properties); return(Redirect("~/Home/Secure")); } ViewData["Error"] = tokenResult.Error; return(View("Error")); }
private async Task <DiscoveryDocumentResponse> GetDiscoveryEndpoints(HttpClient client) { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( client, _authConfigurations.StsServer); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } return(disco); }
private async Task <string> RequestToken() { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(_httpClient, "http://localhost:5000"); var tokenResponse = await HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync(_httpClient, new ClientCredentialsTokenRequest { Scope = "blazorcontracts-api", ClientSecret = "secret", Address = disco.TokenEndpoint, ClientId = "blazorcontracts-web" }); return(tokenResponse.AccessToken); }
public async Task <JArray> GetApiDataAsync() { try { var tokenclient = _clientFactory.CreateClient(); var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(tokenclient, _authConfigurations.Value.StsServer); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } var tokenResponse = await HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync(tokenclient, new ClientCredentialsTokenRequest { Scope = "scope_used_for_api_in_protected_zone", ClientSecret = "api_in_protected_zone_secret", Address = disco.TokenEndpoint, ClientId = "ProtectedApi" }); if (tokenResponse.IsError) { throw new ApplicationException($"Status code: {tokenResponse.IsError}, Error: {tokenResponse.Error}"); } var client = _clientFactory.CreateClient(); client.BaseAddress = new Uri(_authConfigurations.Value.ProtectedApiUrl); client.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetAsync("api/values"); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); var data = JArray.Parse(responseContent); return(data); } throw new ApplicationException($"Status code: {response.StatusCode}, Error: {response.ReasonPhrase}"); } catch (Exception e) { throw new ApplicationException($"Exception {e}"); } }
public static async Task <TokenResponse> LoginAsync(string user, string password) { Console.Title = "Console ResourceOwner Flow RefreshToken"; _disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( _httpClient, _stsUrl); if (_disco.IsError) { throw new ApplicationException($"Status code: {_disco.IsError}, Error: {_disco.Error}"); } return(await RequestTokenAsync(user, password)); }
internal async Task <TokenResponse> RequestTokenAsync(string deviceCode, int interval) { var client = _clientFactory.CreateClient(); var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(client, _authConfigurations.Value.StsServer); if (disco.IsError) { throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } while (true) { if (!string.IsNullOrWhiteSpace(deviceCode)) { var response = await client.RequestDeviceTokenAsync(new DeviceTokenRequest { Address = disco.TokenEndpoint, ClientId = "deviceFlowWebClient", DeviceCode = deviceCode }); if (response.IsError) { if (response.Error == "authorization_pending" || response.Error == "slow_down") { Console.WriteLine($"{response.Error}...waiting."); await Task.Delay(interval * 1000); } else { throw new Exception(response.Error); } } else { return(response); } } else { await Task.Delay(interval * 1000); } } }
private async Task <ClaimsPrincipal> ValidateJwt(string jwt) { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( _httpClient, _optionsAuthConfiguration.StsServerIdentityUrl); var keys = new List <SecurityKey>(); foreach (var webKey in disco.KeySet.Keys) { var key = new JsonWebKey() { Kty = webKey.Kty, Alg = webKey.Alg, Kid = webKey.Kid, X = webKey.X, Y = webKey.Y, Crv = webKey.Crv, E = webKey.E, N = webKey.N, }; keys.Add(key); } var parameters = new TokenValidationParameters { ValidIssuer = disco.Issuer, ValidAudience = _optionsAuthConfiguration.Audience, IssuerSigningKeys = keys, NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role }; var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var user = handler.ValidateToken(jwt, parameters, out var _); return(user); }
private async Task <AccessTokenItem> getApiToken(string api_name, string api_scope, string secret) { try { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( _httpClient, _authConfigurations.Value.StsServer); if (disco.IsError) { _logger.LogError($"disco error Status code: {disco.IsError}, Error: {disco.Error}"); throw new ApplicationException($"Status code: {disco.IsError}, Error: {disco.Error}"); } var tokenResponse = await HttpClientTokenRequestExtensions.RequestClientCredentialsTokenAsync(_httpClient, new ClientCredentialsTokenRequest { Scope = api_scope, ClientSecret = secret, Address = disco.TokenEndpoint, ClientId = api_name }); if (tokenResponse.IsError) { _logger.LogError($"tokenResponse.IsError Status code: {tokenResponse.IsError}, Error: {tokenResponse.Error}"); throw new ApplicationException($"Status code: {tokenResponse.IsError}, Error: {tokenResponse.Error}"); } return(new AccessTokenItem { ExpiresIn = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn), AccessToken = tokenResponse.AccessToken }); } catch (Exception e) { _logger.LogError($"Exception {e}"); throw new ApplicationException($"Exception {e}"); } }
private async Task <ClaimsPrincipal> ValidateJwt(string jwt) { var disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( _httpClient, _optionsAuthConfiguration.StsServerIdentityUrl); var 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, ValidAudience = _optionsAuthConfiguration.Audience, IssuerSigningKeys = keys, NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role }; var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var user = handler.ValidateToken(jwt, parameters, out var _); return(user); }
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); }
private async Task <AccessTokenItem> RequestNewToken(string clientId, string scope, string secret) { try { var discovery = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync( _client, "http://localhost:5010"); if (discovery.IsError) { throw new InvalidOperationException($"Error: {discovery.Error}"); } var tokenResponse = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Scope = scope, ClientSecret = secret, Address = discovery.TokenEndpoint, ClientId = clientId }); if (tokenResponse.IsError) { throw new InvalidOperationException($"Error: {tokenResponse.Error}"); } return(new AccessTokenItem { Expiry = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn), AccessToken = tokenResponse.AccessToken }); } catch (Exception e) { throw new InvalidOperationException($"Exception {e}"); } }
public Task <DiscoveryDocumentResponse> GetDiscoveryDocumentAsync(HttpClient client, string url) { return(string.IsNullOrEmpty(url)? null: HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(client, url)); }