public void testGetAuthUrl() { Dictionary <String, String> configurationMap = new Dictionary <string, string>(); string clientId = "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd"; string clientSecret = "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX"; configurationMap.Add("mode", "sandbox"); APIContext apiContext = new APIContext(); apiContext.Config = configurationMap; List <string> scopelist = new List <string>(); scopelist.Add("openid"); scopelist.Add("email"); string redirectURI = "https://devtools-paypal.com"; string redirectURL = Session.GetRedirectURL(clientId, redirectURI, scopelist, apiContext); Console.WriteLine(redirectURL); CreateFromAuthorizationCodeParameters param = new CreateFromAuthorizationCodeParameters(); param.setClientId(clientId); param.setClientSecret(clientSecret); // code you will get back as part of the url after redirection param.setCode("VxirnJHENB8k5slnoqZOdmjQcCMJRvbI-ispixwWHke-gsOh6XJaWQNJuTCTp3n3o6ttQs3VoNX1De3HOVpmH2PLN53PPedZcTujzLqYrlTS-CqKHYb5wb0NT2joumArOdEy51D4HgoCa46dxuPMm79nX40RQXRP8J0OQsgrEbhf_Kna"); Tokeninfo info = Tokeninfo.CreateFromAuthorizationCode(apiContext, param); UserinfoParameters userinfoParams = new UserinfoParameters(); userinfoParams.setAccessToken(info.access_token); Userinfo userinfo = Userinfo.GetUserinfo(apiContext, userinfoParams); Console.WriteLine("Email" + userinfo.email); }
/// <summary> /// Token request object initilization to retreive user information /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public object GetTokenInfo(string accessToken) { Oauth2Service.TokeninfoRequest tokeninfoRequest = new Oauth2Service().Tokeninfo(); Google.Apis.Discovery.Parameter accessType = new Google.Apis.Discovery.Parameter { DefaultValue = GoogleReqestParameters.offline.ToString(), Name = GoogleReqestParameters.access_type.ToString() }; tokeninfoRequest.RequestParameters.Add("AccessType", accessType); tokeninfoRequest.AccessToken = accessToken; Tokeninfo tokeninfo = tokeninfoRequest.Execute(); return(tokeninfo); }
public void ShouldHaveAllPermissions() { Tokeninfo tokeninfo = GW2Api.V2().TokenInfo.Get(TestData.FullAccessAccountToken); Assert.IsTrue(tokeninfo.Permission.Account); Assert.IsTrue(tokeninfo.Permission.Builds); Assert.IsTrue(tokeninfo.Permission.Characters); Assert.IsTrue(tokeninfo.Permission.Inventories); Assert.IsTrue(tokeninfo.Permission.Pvp); Assert.IsTrue(tokeninfo.Permission.Tradingpost); Assert.IsTrue(tokeninfo.Permission.Unlocks); Assert.IsTrue(tokeninfo.Permission.Wallet); }
public void TestCreateFromRefreshTokenDynamic() { Dictionary <string, string> configurationMap = new Dictionary <string, string>(); configurationMap.Add("clientId", ""); configurationMap.Add("clientSecret", ""); configurationMap.Add("mode", "live"); APIContext apiContext = new APIContext(); apiContext.Config = configurationMap; CreateFromRefreshTokenParameters param = new CreateFromRefreshTokenParameters(); info = info.CreateFromRefreshToken(apiContext, param); Assert.AreEqual(info.access_token != null, true); }
protected string GetAccessToken(Guid accountId) { var encodedRefreshToken = _accountDao.GetPayPalEncryptedRefreshToken(accountId); if (!encodedRefreshToken.HasValue()) { throw new ArgumentNullException(string.Format("Refresh token not found for account: {0}", accountId)); } var tokenInfo = new Tokeninfo { refresh_token = CryptoService.Decrypt(encodedRefreshToken) }; var tokenResult = tokenInfo.CreateFromRefreshToken(GetAPIContext(), new CreateFromRefreshTokenParameters()); return(string.Format("{0} {1}", tokenResult.token_type, tokenResult.access_token)); }
public void TestCreateFromAuthorizationCodeDynamic() { Dictionary <string, string> configurationMap = new Dictionary <string, string>(); configurationMap.Add("clientId", ""); configurationMap.Add("clientSecret", ""); configurationMap.Add("mode", "live"); APIContext apiContext = new APIContext(); apiContext.Config = configurationMap; CreateFromAuthorizationCodeParameters param = new CreateFromAuthorizationCodeParameters(); // code you will get back as part of the url after redirection param.SetCode("xxxx"); info = Tokeninfo.CreateFromAuthorizationCode(apiContext, param); Assert.AreEqual(true, info.access_token != null); }
public BasePaymentResponse LinkAccount(Guid accountId, string authCode) { try { var account = _accountDao.FindById(accountId); if (account == null) { throw new Exception("Account not found."); } var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters(); authorizationCodeParameters.setClientId(GetClientId()); authorizationCodeParameters.setClientSecret(GetSecret()); authorizationCodeParameters.SetCode(authCode); // Get refresh and access tokens var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(GetAPIContext(), authorizationCodeParameters); // Store access token securely _commandBus.Send(new LinkPayPalAccount { AccountId = accountId, EncryptedRefreshToken = CryptoService.Encrypt(tokenInfo.refresh_token) }); return(new BasePaymentResponse { IsSuccessful = true, Message = "Success" }); } catch (Exception e) { _logger.LogMessage("PayPal: LinkAccount error"); _logger.LogError(e); return(new BasePaymentResponse { IsSuccessful = false, Message = e.Message }); } }
public void UserInfoGetUserInfoWithRefreshTokenTest() { try { var config = ConfigManager.Instance.GetProperties(); config[BaseConstants.ClientId] = "AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS"; config[BaseConstants.ClientSecret] = "EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL"; var apiContext = new APIContext() { Config = config }; // Using the refresh token, first get an access token. var tokenInfo = new Tokeninfo { refresh_token = "W1JmxG-Cogm-4aSc5Vlen37XaQTj74aQcQiTtXax5UgY7M_AJ--kLX8xNVk8LtCpmueFfcYlRK6UgQLJ-XHsxpw6kZzPpKKccRQeC4z2ldTMfXdIWajZ6CHuebs" }; var refreshTokenParameters = new CreateFromRefreshTokenParameters(); var token = tokenInfo.CreateFromRefreshToken(apiContext, refreshTokenParameters); this.RecordConnectionDetails(); var userInfoParameters = new UserinfoParameters(); userInfoParameters.SetAccessToken(token.access_token); // Get the user information. var userInfo = PayPal.Api.OpenIdConnect.Userinfo.GetUserinfo(userInfoParameters); this.RecordConnectionDetails(); Assert.AreEqual("account", userInfo.family_name); Assert.AreEqual("facilitator account", userInfo.name); Assert.AreEqual("facilitator", userInfo.given_name); Assert.AreEqual("BUSINESS", userInfo.account_type); Assert.AreEqual("https://www.paypal.com/webapps/auth/identity/user/jWZav5QbA94DNm5FzsNOsq88y4QYrRvu4KLfUydcJqU", userInfo.user_id); Assert.IsTrue(userInfo.verified_account.Value); Assert.AreEqual("en_US", userInfo.locale); } catch (ConnectionException) { this.RecordConnectionDetails(false); throw; } }
/// <summary> /// Is token expired or not /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public bool IsTokenExpired(string accessToken) { Tokeninfo tokeninfo = null; Oauth2Service.TokeninfoRequest tokeninfoRequest = new Oauth2Service().Tokeninfo(); Google.Apis.Discovery.Parameter accessType = new Google.Apis.Discovery.Parameter { DefaultValue = GoogleReqestParameters.offline.ToString(), Name = GoogleReqestParameters.access_type.ToString() }; tokeninfoRequest.RequestParameters.Add("AccessType", accessType); tokeninfoRequest.AccessToken = accessToken; try { tokeninfo = tokeninfoRequest.Execute(); } catch (Exception) { // ignored } return(tokeninfo == null); }
/// <summary> /// Delete contact group created by dot align project. /// </summary> /// <param name="Lead411UserInfo"></param> /// <param name="reqType"></param> public async Task <bool> DeleteContactFolder(Lead411UserInfo Lead411UserInfo, RequestType reqType) { bool result = false; // Retrieving the contact group is required in order to get the Etag. try { GoogleValidationResponse googleValidationResponse = new GoogleValidationResponse(); //Get new access token if (Authentication.IsTokenExpired(Lead411UserInfo.AccessToken)) { googleValidationResponse = (GoogleValidationResponse)Authentication.GetAccessTokenByRefreshToken(Lead411UserInfo.RefreshToken, reqType); //Save new access token to db _iAccount.SaveRefreshToken(Lead411UserInfo.RefreshToken, Lead411UserInfo.AccessToken, Lead411UserInfo.Email, AccountType.Gmail); } else { googleValidationResponse.access_token = Lead411UserInfo.AccessToken; } if (googleValidationResponse.access_token != null) { Lead411UserInfo.AccessToken = googleValidationResponse.access_token; //Get Userinfo Tokeninfo tokeninfo = (Tokeninfo)Authentication.GetUserProfile(Lead411UserInfo.AccessToken); UserCredential userCredential = (UserCredential)Authentication.CreateAutherizationServiceObject(tokeninfo.Scope, tokeninfo.ExpiresIn, tokeninfo.UserId, Lead411UserInfo.AccessToken, Lead411UserInfo.RefreshToken); ContactsRequest contactRequest = (ContactsRequest)Authentication.ContactsRequest(Lead411UserInfo.AccessToken, Lead411UserInfo.RefreshToken); result = await Operation.DeleteContactFolder(contactRequest); } } catch //(GDataVersionConflictException e) { // Etags mismatch: handle the exception. } return(result); }
public void TestCreateFromRefreshTokenDynamic() { Dictionary<string, string> configurationMap = new Dictionary<string, string>(); configurationMap.Add("clientId", ""); configurationMap.Add("clientSecret", ""); configurationMap.Add("mode", "live"); APIContext apiContext = new APIContext(); apiContext.Config = configurationMap; CreateFromRefreshTokenParameters param = new CreateFromRefreshTokenParameters(); info = info.CreateFromRefreshToken(apiContext, param); Assert.AreEqual(info.access_token != null, true); }
public void TestCreateFromAuthorizationCodeDynamic() { Dictionary<string, string> configurationMap = new Dictionary<string, string>(); configurationMap.Add("clientId", ""); configurationMap.Add("clientSecret", ""); configurationMap.Add("mode", "live"); APIContext apiContext = new APIContext(); apiContext.Config = configurationMap; CreateFromAuthorizationCodeParameters param = new CreateFromAuthorizationCodeParameters(); // code you will get back as part of the url after redirection param.SetCode("xxxx"); info = Tokeninfo.CreateFromAuthorizationCode(apiContext, param); Assert.AreEqual(true, info.access_token != null); }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.EndsWith("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.EndsWith("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // Create an authorization state from the returned token. context.Session["authState"] = token; // Get tokeninfo for the access token if you want to verify. Oauth2Service service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); Oauth2Service.TokeninfoRequest request = service.Tokeninfo(); request.AccessToken = token.AccessToken; Tokeninfo info = request.Execute(); string gplus_id = info.UserId; } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else if (context.Request.Path.Contains("/connect")) { // The user is already connected and credentials are cached. context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Write(JsonConvert.SerializeObject("Current user is already connected.")); return; } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. token = (TokenResponse)context.Session["authState"]; IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); UserCredential credential = new UserCredential(flow, "me", token); bool success = credential.RefreshTokenAsync(CancellationToken.None).Result; token = credential.Token; ps = new PlusService( new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = ".NET Quickstart", HttpClientInitializer = credential }); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible).Execute(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. token = (TokenResponse)context.Session["authState"]; string tokenToRevoke = (token.RefreshToken != null) ? token.RefreshToken : token.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + token); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Get the code from the request POST body. string accessToken = context.Request.Params["access_token"]; string idToken = context.Request.Params["id_token"]; // Validate the ID token if (idToken != null) { JwtSecurityToken token = new JwtSecurityToken(idToken); JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler(); // Configure validation Byte[][] certBytes = getCertBytes(); Dictionary <String, X509Certificate2> certificates = new Dictionary <String, X509Certificate2>(); for (int i = 0; i < certBytes.Length; i++) { X509Certificate2 certificate = new X509Certificate2(certBytes[i]); certificates.Add(certificate.Thumbprint, certificate); } { // Set up token validation TokenValidationParameters tvp = new TokenValidationParameters() { ValidateActor = false, // check the profile ID ValidateAudience = (CLIENT_ID != "YOUR_VALID_CLIENT_ID"), // check the client ID ValidAudience = CLIENT_ID, ValidateIssuer = true, // check token came from Google ValidIssuer = "accounts.google.com", ValidateIssuerSigningKey = true, RequireSignedTokens = true, CertificateValidator = X509CertificateValidator.None, IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) => { return(identifier.Select(x => { // TODO: Consider returning null here if you have case sensitive JWTs. /*if (!certificates.ContainsKey(x.Id)) * { * return new X509SecurityKey(certificates[x.Id]); * }*/ if (certificates.ContainsKey(x.Id.ToUpper())) { return new X509SecurityKey(certificates[x.Id.ToUpper()]); } return null; }).First(x => x != null)); }, ValidateLifetime = true, RequireExpirationTime = true, ClockSkew = TimeSpan.FromHours(13) }; try { // Validate using the provider SecurityToken validatedToken; ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken); if (cp != null) { its.valid = true; its.message = "Valid ID Token."; } } catch (Exception e) { // Multiple certificates are tested. if (its.valid != true) { its.message = "Invalid ID Token."; } if (e.Message.IndexOf("The token is expired") > 0) { // TODO: Check current time in the exception for clock skew. } } } // Get the Google+ id for this user from the "sub" claim. Claim[] claims = token.Claims.ToArray <Claim>(); for (int i = 0; i < claims.Length; i++) { if (claims[i].Type.Equals("sub")) { its.gplus_id = claims[i].Value; } } } // Use Tokeninfo to validate the user and the client. var tokeninfo_request = new Oauth2Service().Tokeninfo(); tokeninfo_request.AccessToken = accessToken; // Use Google as a trusted provider to validate the token. // Invalid values, including expired tokens, return 400 Tokeninfo tokeninfo = null; try { tokeninfo = tokeninfo_request.Execute(); if (tokeninfo.IssuedTo != CLIENT_ID) { ats.message = "Access Token not meant for this app."; } else { ats.valid = true; ats.message = "Valid Access Token."; ats.gplus_id = tokeninfo.UserId; } } catch (Exception stve) { ats.message = "Invalid Access Token: " + stve.Message; } // Use the wrapper to return JSON token_status_wrapper tsr = new token_status_wrapper(); tsr.id_token_status = its; tsr.access_token_status = ats; context.Response.StatusCode = 200; context.Response.ContentType = "text/json"; context.Response.Write(JsonConvert.SerializeObject(tsr)); }
public void ShouldHaveCorrectTokenName() { Tokeninfo tokeninfo = GW2Api.V2().TokenInfo.Get(TestData.FullAccessAccountToken); Assert.AreEqual(TestData.FullAccessAccountTokenName, tokeninfo.Name); }
public void ShouldHaveCorrectTokenId() { Tokeninfo tokeninfo = GW2Api.V2().TokenInfo.Get(TestData.FullAccessAccountToken); Assert.AreEqual(TestData.FullAccessAccountToken.Substring(0, 36), tokeninfo.Id); // Seems like only 36 letters of the Id will be returned. }
/// <summary> /// Code example for creating a future payment object. /// </summary> /// <param name="correlationId"></param> /// <param name="authorizationCode"></param> private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl) { // ###Payer // A resource representing a Payer that funds a payment // Payment Method // as `paypal` Payer payer = new Payer() { payment_method = "paypal" }; // ###Details // Let's you specify details of a payment amount. Details details = new Details() { tax = "15", shipping = "10", subtotal = "75" }; // ###Amount // Let's you specify a payment amount. var amount = new Amount() { currency = "USD", total = "100", // Total must be equal to sum of shipping, tax and subtotal. details = details }; // # Redirect URLS var redirUrls = new RedirectUrls() { cancel_url = redirectUrl, return_url = redirectUrl }; // ###Items // Items within a transaction. var itemList = new ItemList() { items = new List <Item>() }; itemList.items.Add(new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" }); // ###Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. var transactionList = new List <Transaction>(); // The Payment creation API requires a list of // Transaction; add the created `Transaction` // to a List transactionList.Add(new Transaction() { description = "Transaction description.", amount = amount, item_list = itemList }); var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters(); authorizationCodeParameters.setClientId(Configuration.ClientId); authorizationCodeParameters.setClientSecret(Configuration.ClientSecret); authorizationCodeParameters.SetCode(authorizationCode); var apiContext = new APIContext(); apiContext.Config = Configuration.GetConfig(); var tokenInfo = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters); var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token); // ###Payment // A FuturePayment Resource this.futurePayment = new FuturePayment() { intent = "authorize", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; return(this.futurePayment.Create(accessToken, correlationId)); }