static async Task Main(string[] args) { var client = new System.Net.Http.HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("https://localhost:44396"); if (disco.IsError) { Console.WriteLine(disco.Error); return; } var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "client", ClientSecret = "secret", Scope = "api1" }); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); } Console.WriteLine(disco.Error); }
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); } }
private static async Task TestOAuth2() { // discover endpoints from metadata var client = new System.Net.Http.HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001"); if (disco.IsError) { Console.WriteLine(disco.Error); return; } // request token var 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); Console.WriteLine("\n\n"); // call api var apiClient = new System.Net.Http.HttpClient(); apiClient.SetBearerToken(tokenResponse.AccessToken); var response = await apiClient.GetAsync("https://localhost:6001/identity"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); var data = System.Text.Json.JsonSerializer.Deserialize <dynamic>(content); Console.WriteLine(data); } }
public async void GetUser(ulong imei) { var clientAuth = new System.Net.Http.HttpClient(); var disco = await clientAuth.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest { Address = "http://127.0.0.1.xip.io", Policy = { RequireHttps = false } }); if (disco.IsError) { logger.Error(disco.Error); return; } // request token var tokenResponse = await clientAuth.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "DeviceIdentity", Scope = "BridgeAPI" }); if (tokenResponse.IsError) { logger.Error(tokenResponse.Error); return; } logger.Info(tokenResponse.Json); // call api var baseAddress = new Uri("https://localhost:5006"); var httpClient = WebRequest.CreateHttp(baseAddress); httpClient.KeepAlive = false; httpClient.Method = "POST"; httpClient.ContentType = "application/json"; httpClient.Headers.Add("Authorization", $"Bearer {tokenResponse.AccessToken}"); var requestStream = httpClient.GetRequestStream(); requestStream.Write(Encoding.UTF8.GetBytes(imei.ToString())); requestStream.Flush(); var response = new StreamReader(((HttpWebResponse)httpClient.GetResponse()).GetResponseStream()).ReadToEnd(); }
public async Task <ActionResult <Models.TokenResponse> > Token( [FromForm(Name = "grant_type")] string grantType, [FromForm(Name = "client_id")] string clientId, [FromForm(Name = "client_secret")] string clientSecret, [FromForm(Name = "redirect_uri")] string redirectUri, [FromForm(Name = "code")] string code) { //var endPointDiscovery = await discoveryCache.GetAsync(); using (var httpClient = new System.Net.Http.HttpClient()) { var discovery = await httpClient.GetDiscoveryDocumentAsync("https://localhost:44348"); var clientCredentialsTokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = discovery.TokenEndpoint, //Address = "https://localhost:44348", ClientId = clientId, ClientSecret = clientSecret, GrantType = grantType, Scope = "email" }); //var codeTokenResponse = await httpClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest //{ // Address = discovery.TokenEndpoint, // ClientId = clientId, // ClientSecret = clientSecret, // GrantType = grantType, // Code = code, // RedirectUri = redirectUri //}); //var tokenResponse = await httpClient.RequestTokenAsync(new TokenRequest //{ // Address = discovery.TokenEndpoint, // ClientId = clientId, // ClientSecret = clientSecret, // GrantType = grantType, //}); return(Ok(new Models.TokenResponse(clientCredentialsTokenResponse))); } }
public string GetBearerToken(string username, string password, string scope) { using (System.Net.Http.HttpClient client = CreateClient()) { DiscoveryResponse disco = client.GetDiscoveryDocumentAsync(Utils.ServerConfiguration.Identity).Result; Assert.IsFalse(disco.IsError); TokenResponse tokenResponse = client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = MockIdentityWebApplicationFactory.ClientId, ClientSecret = MockIdentityWebApplicationFactory.ClientSecret, UserName = username, Password = password, Scope = scope, }).Result; Assert.IsFalse(tokenResponse.IsError); return(tokenResponse.Json["access_token"].ToString()); } }
//[ValidateAntiForgeryToken] public async Task <IActionResult> GetOidcConfig([FromQuery] string clientId, [FromServices] IConfiguration cfg) { try { var oidcConf = cfg.GetSection(nameof(IdSrvConfig)).Get <IdSrvConfig>() ?? new IdSrvConfig(); if (string.IsNullOrEmpty(oidcConf.Authority)) { throw new Exception("OidcServerAuthority is missed."); } object ret = null; using (var client = new System.Net.Http.HttpClient()) { var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest { Address = oidcConf.Authority, Policy = { ValidateIssuerName = false, ValidateEndpoints = false, }, }); if (disco.IsError) { throw new Exception($"OidcServer Discovery error: {disco.Error}"); } ret = new { authorization_endpoint = disco.AuthorizeEndpoint, token_endpoint = disco.TokenEndpoint, logout_endpoint = disco.EndSessionEndpoint }; } return(Ok(ret)); } catch (Exception ex) { _logger.LogError(ex, "error GetOidcConfig AuthController"); return(InternalServerError(ex)); } }
public async Task <TokenInfo> GetTokenFromAuthorityAsync(AuthorityInfo authorityInfo, string secret, CancellationToken cancel = default) { using var client = new System.Net.Http.HttpClient(); var disco = await client.GetDiscoveryDocumentAsync(authorityInfo.Authority, cancel) .ConfigureAwait(false); if (disco.IsError) { _logger?.LogError($"Error during discovery document request to authority {authorityInfo.Authority}."); return(null); } //TODO: Request REFRESH token too and use that to renew the access token after expiration. // Currently the token response does not contain the refresh token, it needs to be requested. // request token var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = authorityInfo.ClientId, ClientSecret = secret, Scope = "sensenet" }, cancel); if (tokenResponse.IsError) { _logger?.LogError(tokenResponse.Exception, "Error during requesting client credentials " + $"from authority {authorityInfo.Authority}." + $"ClientId: {authorityInfo.ClientId}"); return(null); } return(tokenResponse.ToTokenInfo()); }