static void Main(string[] args) { _oauth2 = new OAuth2Client( new Uri(Constants.TokenEndpoint), "roclient", "secret"); var response = RequestToken(); ShowResponse(response); Console.ReadLine(); var refresh_token = response.RefreshToken; while (true) { response = RefreshToken(refresh_token); ShowResponse(response); Console.ReadLine(); CallService(response.AccessToken); if (response.RefreshToken != refresh_token) { refresh_token = response.RefreshToken; } } }
private static TokenResponse GetToken(string tokenUrl) { var client = new OAuth2Client( new Uri(tokenUrl)); return client.RequestResourceOwnerPasswordAsync("cw", "cw").Result; }
private void btnLogin_Click(object sender, RoutedEventArgs e) { // for reference: if you ever need to get the correct callbackUri // for your app // var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); var client = new OAuth2Client( new Uri(ExpenseTrackerConstants.IdSrvAuthorize)); string nonce = Guid.NewGuid().ToString() + DateTime.Now.Ticks.ToString(); var startUrl = client.CreateAuthorizeUrl( "native", "id_token token", "openid roles", ExpenseTrackerConstants.ExpenseTrackerMobile, "state", nonce); WebAuthenticationBroker.AuthenticateAndContinue ( new Uri(startUrl), new Uri(ExpenseTrackerConstants.ExpenseTrackerMobile), null, WebAuthenticationOptions.None); }
private void btnLogin_Click(object sender, RoutedEventArgs e) { // for reference: if you ever need to get the correct callbackUri // for your app // var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); var client = new OAuth2Client( new Uri(ExpenseTrackerConstants.IdSrvAuthorizeWp)); string nonce = Guid.NewGuid().ToString() + DateTime.Now.Ticks.ToString(); var startUrl = client.CreateAuthorizeUrl( "native", //this client corresponds to client config on id srv level "id_token token", //Request an id token + access token "openid roles expensetrackerapi", //the access token should contain the id and roles scope //will call the user info end point for this //We no longer use the authorization code as this does not belong to the implicit flow //The WP client isn't a confidential client... //If you do ask for the authorization code, this flow will fail. //Ask for the expensetrackerapi scope to get it included in the access token ExpenseTrackerConstants.ExpenseTrackerMobile, "state", //With state you can pass through values nonce); //Number only used once, this is used by the STS to prevent replay attacks WebAuthenticationBroker.AuthenticateAndContinue ( new Uri(startUrl), new Uri(ExpenseTrackerConstants.ExpenseTrackerMobile), null, WebAuthenticationOptions.None); }
static void Main(string[] args) { System.Diagnostics.Debugger.Launch(); var p = new CodeFlow(); // Handle Arguments var authcoderesponse = args.SkipWhile(a => a != "authresponse").Skip(1).FirstOrDefault(); var authclient = new OAuth2Client( new Uri(Constant.TokenEndpointAuthorize), Constant.CodeClientId, Constant.CodeClientSecret); if (authcoderesponse != null) { ReceiveAuthorizationCode(authcoderesponse); } else { // Request Authorization code, open URL in browser System.Diagnostics.Process.Start(p.CreateAuthUrl(authclient)); } Console.Read(); }
public async Task<ActionResult> GetToken() { var client = new OAuth2Client( new Uri(Constants.TokenEndpoint), "codeclient", "secret"); var code = Request.QueryString["code"]; var response = await client.RequestAuthorizationCodeAsync( code, "https://localhost:44312/callback"); ValidateResponseAndSignIn(response); if (!string.IsNullOrEmpty(response.IdentityToken)) { ViewBag.IdentityTokenParsed = ParseJwt(response.IdentityToken); } if (!string.IsNullOrEmpty(response.AccessToken)) { ViewBag.AccessTokenParsed = ParseJwt(response.AccessToken); } return View("Token", response); }
private static void ClientCredentialFlow() { Console.WriteLine("Processing client credential flow" + Environment.NewLine); var client = new OAuth2Client(new Uri(Endpoint + "/issue/oidc/token"), ClientId, ClientSecret); var taks = client.RequestClientCredentialsAsync(Scope); taks.Wait(); var tokenResponse = taks.Result; Console.WriteLine("Access token received .. " + Environment.NewLine); Console.WriteLine(tokenResponse.AccessToken + Environment.NewLine); Console.WriteLine("Calling refresh token endpoint" + Environment.NewLine); Task<TokenResponse> refreshTokenResponse = client.RequestRefreshTokenAsync(tokenResponse.RefreshToken); refreshTokenResponse.Wait(); tokenResponse = refreshTokenResponse.Result; Console.WriteLine("Access token received using refresh token .. " + Environment.NewLine); Console.WriteLine(tokenResponse.AccessToken + Environment.NewLine); RevokeToken(tokenResponse.AccessToken, "access_token"); }
private static TokenResponse RequestToken() { "Requesting token.".ConsoleYellow(); var client = new OAuth2Client( new Uri(Constants.AS.OAuth2TokenEndpoint), Constants.Clients.ResourceOwnerClient, Constants.Clients.ResourceOwnerClientSecret); TokenResponse response = null; try { response = client.RequestResourceOwnerPasswordAsync("pibline.authorization", "letmein","read").Result; client.RequestClientCredentialsAsync(); Console.WriteLine(" access token"); response.AccessToken.ConsoleGreen(); Console.WriteLine("\n refresh token"); response.RefreshToken.ConsoleGreen(); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine(ex); } return response; }
private static TokenResponse GetToken() { var client = new OAuth2Client( new Uri("http://localhost:2727/token")); return client.RequestResourceOwnerPasswordAsync("bob", "bob").Result; }
public async static Task<AuthorizeResponse> DoImplicitFlowAsync(Uri endpoint, string clientId, string scope, Uri callbackUri) { var client = new OAuth2Client(endpoint); var startUri = client.CreateImplicitFlowUrl( clientId, scope, callbackUri.AbsoluteUri); try { var result = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(startUri)); switch (result.ResponseStatus) { case WebAuthenticationStatus.Success: return new AuthorizeResponse(result.ResponseData); case WebAuthenticationStatus.UserCancel: throw new Exception("User cancelled authentication"); case WebAuthenticationStatus.ErrorHttp: throw new Exception("HTTP Error returned by AuthenticateAsync() : " + result.ResponseErrorDetail.ToString()); default: throw new Exception("Error returned by AuthenticateAsync() : " + result.ResponseStatus.ToString()); } } catch { // Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here. throw; } }
public void Configuration(IAppBuilder app) { AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub"; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = "hybridclient", Authority = IdServBaseUri, RedirectUri = ClientUri, PostLogoutRedirectUri = ClientUri, ResponseType = "code id_token token", Scope = "openid profile email roles offline_access", SignInAsAuthenticationType = "Cookies", Notifications = new OpenIdConnectAuthenticationNotifications { AuthorizationCodeReceived = async n => { var identity = n.AuthenticationTicket.Identity; var nIdentity = new ClaimsIdentity(identity.AuthenticationType, "email", "role"); var userInfoClient = new UserInfoClient( new Uri(UserInfoEndpoint), n.ProtocolMessage.AccessToken); var userInfo = await userInfoClient.GetAsync(); userInfo.Claims.ToList().ForEach(x => nIdentity.AddClaim(new Claim(x.Item1, x.Item2))); var tokenClient = new OAuth2Client(new Uri(TokenEndpoint), "hybridclient", "idsrv3test"); var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); nIdentity.AddClaim(new Claim("access_token", response.AccessToken)); nIdentity.AddClaim( new Claim("expires_at", DateTime.UtcNow.AddSeconds(response.ExpiresIn).ToLocalTime().ToString(CultureInfo.InvariantCulture))); nIdentity.AddClaim(new Claim("refresh_token", response.RefreshToken)); nIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); n.AuthenticationTicket = new AuthenticationTicket( nIdentity, n.AuthenticationTicket.Properties); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value; n.ProtocolMessage.IdTokenHint = idTokenHint; } } } }); }
static TokenResponse RequestToken() { var client = new OAuth2Client( new Uri(Constants.TokenEndpoint), "roclient", "secret"); return client.RequestResourceOwnerPasswordAsync("bob", "bob", "read write").Result; }
static TokenResponse GetUserToken() { var client = new OAuth2Client( new Uri(ApplicationConstants.TokenEndpoint), ApplicationConstants.ClientIdConsoleApp, ApplicationConstants.ClientSecretConsoleApp); return client.RequestResourceOwnerPasswordAsync("itua.synergy", "asdfasdf", ApplicationScopes.ConsoleApp).Result; }
static TokenResponse RefreshToken(string refreshToken) { var client = new OAuth2Client( new Uri("https://HFL0100:44333/connect/token"), "carbon", "21B5F798-BE55-42BC-8AA8-0025B903DC3B"); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; return client.RequestRefreshTokenAsync(refreshToken).Result; }
static TokenResponse GetUserTokenLock() { var client = new OAuth2Client( new Uri("https://HFL0100:44333/connect/token"), "carbon", "21B5F798-BE55-42BC-8AA8-0025B903DC3B",OAuth2Client.ClientAuthenticationStyle.PostValues); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; return client.RequestResourceOwnerPasswordAsync("Davidao", "Davide1981!1", "api1").Result; }
private async Task<TokenResponse> GetTokenAsync() { var client = new OAuth2Client( new Uri("https://localhost:44319/identity/connect/token"), "mvc_service", "secret"); return await client.RequestClientCredentialsAsync("sampleApi"); }
private static TokenResponse GetUserToken(String username, String password) { var client = new OAuth2Client( new Uri(ApplicationConstants.TokenEndpoint), ApplicationConstants.ConsoleAppClientId, ApplicationConstants.ConsoleAppClientSecret); return client.RequestResourceOwnerPasswordAsync(username, password, ApplicationScopes.ConsoleApp).Result; }
static TokenResponse GetUserToken() { var client = new OAuth2Client( new Uri(Constants.AuthorizationUrl + "/connect/token"), "MyAppClientId", "21B5F798-BE55-42BC-8AA8-0025B903DC3B"); return client.RequestResourceOwnerPasswordAsync("testUser", "testPwd", "api1").Result; }
public async static Task<TokenResponse> RefreshToken(TokenResponse token) { var client = new OAuth2Client( new Uri(Constant.TokenEndpoint), Constant.CodeClientId, Constant.CodeClientSecret); return await client.RequestRefreshTokenAsync(token.RefreshToken); }
static TokenResponse GetUserToken() { var client = new OAuth2Client( new Uri("https://localhost:44333/connect/token"), "carbon", "21B5F798-BE55-42BC-8AA8-0025B903DC3B"); return client.RequestResourceOwnerPasswordAsync("bob", "secret", "api1").Result; }
static TokenResponse GetClientToken() { var client = new OAuth2Client( new Uri("https://localhost:44333/connect/token"), "silicon", "F621F470-9731-4A25-80EF-67A6F7C5F4B8"); return client.RequestClientCredentialsAsync("api1").Result; }
static TokenResponse RequestToken() { var client = new OAuth2Client( new Uri(Constants.TokenEndpoint), "client", "secret"); return client.RequestClientCredentialsAsync("read write").Result; }
private static void ResourceOwnerFlow() { Console.WriteLine("Processing Resource owner password flow"); Console.WriteLine(""); Console.WriteLine(""); var client = new OAuth2Client(new Uri(Endpoint + "/issue/oidc/token"), ClientId, APIKey); var taks = client.RequestResourceOwnerPasswordAsync(UserName, Password, Scopes); taks.Wait(new TimeSpan(1, 0, 0)); var tokenResponse = taks.Result; Console.WriteLine("Access token received .. "); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(tokenResponse.AccessToken); Console.WriteLine("Calling user info endpoint"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); var httpClient = new HttpClient { BaseAddress = new Uri(Endpoint + "/issue/oidc/userinfo") }; httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken); var response = httpClient.GetAsync("").Result; response.EnsureSuccessStatusCode(); var dictionary = response.Content.ReadAsAsync<Dictionary<string, string>>().Result; foreach (var pair in dictionary) { Console.WriteLine(pair.Key + " ----> " + pair.Value); } Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Calling refresh token endpoint"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); Task<TokenResponse> refreshTokenResponse = client.RequestRefreshTokenAsync(tokenResponse.RefreshToken); refreshTokenResponse.Wait(); tokenResponse = refreshTokenResponse.Result; Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Access token received using refresh token .. "); Console.WriteLine(""); Console.WriteLine(tokenResponse.AccessToken); Console.WriteLine(""); Console.WriteLine(""); RevokeToken(tokenResponse.AccessToken, "access_token"); Console.WriteLine(""); }
private static TokenResponse RefreshToken(string refreshToken) { var client = new OAuth2Client( new Uri("http://localhost:2727/token"), "client1", "secret"); var response = client.RequestRefreshTokenAsync(refreshToken).Result; return response; }
public async Task<ActionResult> RenewToken(string refreshToken) { var client = new OAuth2Client( new Uri(Constants.AS.OAuth2TokenEndpoint), Constants.Clients.CodeClient, Constants.Clients.CodeClientSecret); var response = await client.RequestRefreshTokenAsync(refreshToken); return View("Postback", response); }
/// <summary> /// Get a token using Thinktecture OAuth2Client /// </summary> /// <returns></returns> public static string GetToken() { var client = new OAuth2Client( new Uri(ConfigurationManager.AppSettings["Authority"] + "/connect/token"), _clientId, _clientSecret); var response = client.RequestClientCredentialsAsync("bimtoolkitapi").Result; return response.AccessToken; }
private async static Task ResourceOwnerFlow() { var oauthClient = new OAuth2Client(new Uri("http://localhost:1642/token")); var tokenResponse = oauthClient.RequestResourceOwnerPasswordAsync("cecil", "cecil").Result; var client = new HttpClient(); client.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetStringAsync(new Uri("http://localhost:1642/api/secure/data")); Console.WriteLine(response); }
public ActionResult Index(string scopes) { var client = new OAuth2Client(new Uri(Constants.AuthorizeEndpoint)); var url = client.CreateCodeFlowUrl( "codeclient", scopes, "https://localhost:44312/callback", "123"); return Redirect(url); }
public async Task Should_Validate_And_Issue_Access_Token_When_Resource_Owner_Credentials_Are_Correct() { using (TestServer server = TestServer.Create<Startup>()) { OAuth2Client client = new OAuth2Client(new Uri("http://whatever:5000/token"), server.Handler); TokenResponse tokenResponse = await client.RequestResourceOwnerPasswordAsync("bob", "bob"); Assert.NotNull(tokenResponse); Assert.NotNull(tokenResponse.AccessToken); } }
public void ShouldSetBaseAddress() { // Arrange var factory = new OAuthHttpClientFactory(); var oAuth2Client = new OAuth2Client(new Uri("http://test/oauth")); var tokenStore = A.Fake<ITokenStore>(); // Act var httpClient = factory.CreateClient("http://test/", "test", tokenStore, oAuth2Client); // Assert httpClient.BaseAddress.Should().Be("http://test/"); }
async Task <TokenResponse> GetGFSTokenAsync() { var uri = new Uri(@"https://identity.justshoutgfs.com/connect/token"); var client = new Thinktecture.IdentityModel.Client.OAuth2Client( uri, P4MConsts.GfsClientId, P4MConsts.GfsClientSecret); var tokenResponse = await client.RequestClientCredentialsAsync("read checkout-api"); if (tokenResponse == null || tokenResponse.AccessToken == null) { throw new Exception("Request for client credentials denied"); } //Response.Cookies["gfsCheckoutToken"].Value = token; //Response.Cookies["gfsCheckoutToken"].Expires = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn); return(tokenResponse); }