public async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            // ChallengeHandler function for AuthenticationManager that will be called whenever access to a secured
            // resource is attempted
            OAuthTokenCredential credential = null;

            try
            {
                // Create generate token options if necessary
                if (info.GenerateTokenOptions == null)
                {
                    info.GenerateTokenOptions = new GenerateTokenOptions();
                }

                // AuthenticationManager will handle challenging the user for credentials
                credential = await AuthenticationManager.Current.GenerateCredentialAsync
                             (
                    info.ServiceUri,
                    info.GenerateTokenOptions
                             ) as OAuthTokenCredential;
            }
            catch (Exception ex)
            {
                // Exception will be reported in calling function
                throw (ex);
            }

            return(credential);
        }
示例#2
0
        /// <summary>
        /// Get PayPal Api context
        /// </summary>
        /// <param name="paypalDirectPaymentSettings">PayPalDirectPayment settings</param>
        /// <returns>ApiContext</returns>
        public static APIContext GetApiContext(PayPalDirectPaymentSettings payPalDirectPaymentSettings)
        {
            var mode = payPalDirectPaymentSettings.UseSandbox ? "sandbox" : "live";

            var config = new Dictionary <string, string>
            {
                { "clientId", payPalDirectPaymentSettings.ClientId },
                { "clientSecret", payPalDirectPaymentSettings.ClientSecret },
                { "mode", mode }
            };

            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accessToken)
            {
                Config = config
            };

            if (apiContext.HTTPHeaders == null)
            {
                apiContext.HTTPHeaders = new Dictionary <string, string>();
            }
            apiContext.HTTPHeaders["PayPal-Partner-Attribution-Id"] = BN_CODE;

            return(apiContext);
        }
示例#3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get a reference to the config
        Dictionary <string, string> config = ConfigManager.Instance.GetProperties();

        // Use OAuthTokenCredential to request an access token from PayPal
        String accessToken = new OAuthTokenCredential(config).GetAccessToken();

        ServicePointManager.Expect100Continue      = true;
        ServicePointManager.SecurityProtocol       = SecurityProtocolType.Tls;
        ServicePointManager.DefaultConnectionLimit = 9999;

        APIContext apiContext = new APIContext(accessToken);

        // Initialize the apiContext's configuration with the default configuration for this application.
        apiContext.Config = ConfigManager.Instance.GetProperties();

        // Define any custom configuration settings for calls that will use this object.
        apiContext.Config["connectionTimeout"] = "1000"; // Quick timeout for testing purposes

        // Define any HTTP headers to be used in HTTP requests made with this APIContext object
        if (apiContext.HTTPHeaders == null)
        {
            apiContext.HTTPHeaders = new Dictionary <string, string>();
        }
        apiContext.HTTPHeaders["some-header-name"] = "some-value";
    }
        // ChallengeHandler function for AuthenticationManager, called whenever access to a secured resource is attempted.
        private async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            OAuthTokenCredential credential = null;

            try
            {
                // Create generate token options if necessary.
                if (info.GenerateTokenOptions == null)
                {
                    info.GenerateTokenOptions = new GenerateTokenOptions();
                }

                // AuthenticationManager will handle challenging the user for credentials.
                credential = await AuthenticationManager.Current.GenerateCredentialAsync
                             (
                    info.ServiceUri,
                    info.GenerateTokenOptions
                             ) as OAuthTokenCredential;
            }
            catch (TaskCanceledException)
            {
                return(credential);
            }
            catch (Exception)
            {
                // Exception will be reported in calling function.
                throw;
            }

            return(credential);
        }
        protected void btnConfirmOrder_Click(object sender, EventArgs e)
        {
            var config      = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            var paymentId = Session["paymentId"].ToString();

            if (!String.IsNullOrEmpty(paymentId))
            {
                //create a payment object with the paymentId from session
                var payment = new Payment()
                {
                    id = paymentId
                };

                //retrieve the payerId from the querystring and use it to create a new payment execution object
                var payerId          = Request.QueryString["PayerID"].ToString();
                var paymentExecution = new PaymentExecution()
                {
                    payer_id = payerId
                };

                //execute the payment
                var executedPayment = payment.Execute(apiContext, paymentExecution);

                //inform the user
                litResult.Text          = "<p>Your order has been completed</p>";
                btnConfirmOrder.Visible = false;
            }
        }
        protected void btnConfirmPurchase_Click(object sender, EventArgs e)
        {
            var config      = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            var paymentId = Session["paymentId"].ToString();

            if (!String.IsNullOrEmpty(paymentId))
            {
                var payment = new Payment()
                {
                    id = paymentId
                };

                var payerId          = Request.QueryString["PayerID"].ToString();
                var paymentExecution = new PaymentExecution()
                {
                    payer_id = payerId
                };

                var executedPayment = payment.Execute(apiContext, paymentExecution);

                litInformation.Text        = "<p>Your order has been completed</p>";
                btnConfirmPurchase.Visible = false;
            }
        }
        protected void btnComplete_Click(object sender, EventArgs e)
        {
            var config      = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            var paymentId = Session["paymentId"].ToString();

            if (!String.IsNullOrEmpty(paymentId))
            {
                var payment = new Payment()
                {
                    id = paymentId
                };                                              //make payment object
                var payerId          = Request.QueryString["PayerID"].ToString();
                var paymentExecution = new PaymentExecution()
                {
                    payer_id = payerId
                };

                var executedPayment = payment.Execute(apiContext, paymentExecution);

                btnComplete.Visible     = false;
                pnlCompleteShow.Visible = true;
                pnlHead.Visible         = false;
            }
        }
示例#8
0
        public static APIContext GetApiContext()
        {
            var config      = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();

            return(new APIContext(accessToken));
        }
示例#9
0
        private static string GetAccessToken()
        {
            string accessToken = new OAuthTokenCredential
                                     (ClientId, ClientSecret, GetConfig()).GetAccessToken();

            return(accessToken);
        }
示例#10
0
        private APIContext GetContext()
        {
            var accessToken = new OAuthTokenCredential(_config).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            return(apiContext);
        }
示例#11
0
        public ActionResult Void(string authorizationId)
        {
            var viewData = new ConfirmedViewData();

            try
            {
                var accessToken   = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["clientId"], ConfigManager.Instance.GetProperties()["clientSecret"]).GetAccessToken();
                var apiContext    = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var voidedAuthorization = authorization.Void(apiContext);

                    viewData.JsonResponse = JObject.Parse(voidedAuthorization.ConvertToJson()).ToString(Formatting.Indented);

                    var reservaID = ((EntCuenta)Session["cuenta"]).ReservaID;

                    bool eliminaReserva = LogReserva.Instancia.EliminarReserva(reservaID);

                    return(RedirectToAction("Inicio", "Menu"));
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return(View("Error", viewData));
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return(View("Error", viewData));
            }
        }
        public PaymentService(IPlanRepository planRepository, ITenantPlanRepository tenantPlanRepository)
        {
            this._planRepository       = planRepository;
            this._tenantPlanRepository = tenantPlanRepository;
            var config       = new Dictionary <string, string>();
            var mode         = ConfigurationManager.AppSettings["mode"];
            var clientId     = ConfigurationManager.AppSettings["clientId"];
            var clientSecret = ConfigurationManager.AppSettings["clientSecret"];

            config.Add("mode", mode);
            config.Add("clientId", clientId);
            config.Add("clientSecret", clientSecret);

            // Use OAuthTokenCredential to request an access token from PayPal
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();

            _apiContext = new APIContext(accessToken);
            // Initialize the apiContext's configuration with the default configuration for this application.
            _apiContext.Config = ConfigManager.Instance.GetProperties();

            // Define any custom configuration settings for calls that will use this object.
            _apiContext.Config["connectionTimeout"] = "3000";    // Quick timeout for testing purposes

            // Define any HTTP headers to be used in HTTP requests made with this APIContext object
            if (_apiContext.HTTPHeaders == null)
            {
                _apiContext.HTTPHeaders = new Dictionary <string, string>();
            }
            _apiContext.HTTPHeaders["some-header-name"] = "some-value";
        }
示例#13
0
 public APIContext GetApiContext()
 {
     config     = PayPal.Api.ConfigManager.Instance.GetProperties();
     auth       = new OAuthTokenCredential(config);
     apiContext = new APIContext(auth.GetAccessToken());
     return(apiContext);
 }
        private PayPalRest.Payment CreatePayPalPayment(PaymentProcessingContext request, PayPalConfig settings)
        {
            var config = new Dictionary <string, string>();

            config.Add("mode", settings.SandboxMode ? "sandbox" : "live");

            var credentials = new OAuthTokenCredential(settings.ClientId, settings.ClientSecret, config);
            var accessToken = credentials.GetAccessToken();
            var payment     = new PayPalRest.Payment
            {
                intent = "sale",
                payer  = new Payer
                {
                    payment_method      = "credit_card",
                    funding_instruments = new List <PayPalRest.FundingInstrument>
                    {
                        new PayPalRest.FundingInstrument
                        {
                            credit_card = CreateCreditCard(request)
                        }
                    }
                },
                transactions = new List <Transaction> {
                    CreateTransaction(request)
                }
            };

            return(payment.Create(new APIContext(accessToken)
            {
                Config = config
            }));
        }
示例#15
0
        public void OAuthTokenCredentialCtorClientInfoTest()
        {
            var oauthTokenCredential = new OAuthTokenCredential("aaa", "bbb");

            Assert.AreEqual("aaa", oauthTokenCredential.ClientId);
            Assert.AreEqual("bbb", oauthTokenCredential.ClientSecret);
        }
        private static string GetAccessToken()
        {
            // getting accesstocken from paypal
            string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();

            return(accessToken);
        }
示例#17
0
        public ActionResult Confirmed(Guid id, string token, string payerId)
        {
            var viewData = new ConfirmedViewData
            {
                Id      = id,
                Token   = token,
                PayerId = payerId
            };

            var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
            var apiContext  = new APIContext(accessToken);
            var payment     = new Payment()
            {
                id = (string)Session[id.ToString()],
            };

            var executedPayment = payment.Execute(apiContext, new PaymentExecution {
                payer_id = payerId
            });

            viewData.AuthorizationId = executedPayment.transactions[0].related_resources[0].authorization.id;
            viewData.JsonRequest     = JObject.Parse(payment.ConvertToJson()).ToString(Formatting.Indented);
            viewData.JsonResponse    = JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented);

            return(View(viewData));
        }
示例#18
0
        public ActionResult Void(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken   = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext    = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var voidedAuthorization = authorization.Void(apiContext);

                    viewData.JsonResponse = JObject.Parse(voidedAuthorization.ConvertToJson()).ToString(Formatting.Indented);

                    return(View(viewData));
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return(View("Error", viewData));
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return(View("Error", viewData));
            }
        }
示例#19
0
        // ChallengeHandler function for AuthenticationManager that will be called whenever access to a secured
        // resource is attempted
        public async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            OAuthTokenCredential credential = null;

            try
            {
                // Create generate token options if necessary
                if (info.GenerateTokenOptions == null)
                {
                    info.GenerateTokenOptions = new GenerateTokenOptions();
                }

                // IOAuthAuthorizeHandler will challenge the user for credentials
                credential = await AuthenticationManager.Current.GenerateCredentialAsync
                             (
                    info.ServiceUri,
                    info.GenerateTokenOptions
                             ) as OAuthTokenCredential;
            }
            catch (Exception ex)
            {
                // Exception will be reported in calling function
                throw (ex);
            }

            return(credential);
        }
示例#20
0
        private static APIContext GetAPIContext(string clientId, string secretKey, string token = null)
        {
            APIContext apiContext = null;

            if (string.IsNullOrWhiteSpace(token))
            {
                var accessToken = new OAuthTokenCredential(clientId, secretKey);

                apiContext = new APIContext(accessToken.GetAccessToken());
            }
            else
            {
                apiContext = new APIContext(token);
            }

            var config = new Dictionary <string, string>();

            config.Add("mode", "sandbox");
            config.Add("clientId", clientId);
            config.Add("clientSecret", secretKey);

            apiContext.Config = config;

            return(apiContext);
        }
示例#21
0
        private IEnumerable <TfsClientCredentials> GetOAuthCredentials()
        {
            try
            {
                var usernameAndPassword = GetServiceIdentityUsernameAndPasswordFromConfig();

                if (usernameAndPassword == null ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthClientId) ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthContext) ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthResourceId))
                {
                    return(new List <TfsClientCredentials>());
                }

                var userCredential = new UserCredential(usernameAndPassword.Item1, usernameAndPassword.Item2);
                var authContext    = new AuthenticationContext(_config.TfsServerConfig.OAuthContext);
                var result         = authContext.AcquireToken(_config.TfsServerConfig.OAuthResourceId, _config.TfsServerConfig.OAuthClientId, userCredential);
                var oauthToken     = new OAuthTokenCredential(result.AccessToken);
                return(new List <TfsClientCredentials>()
                {
                    new TfsClientCredentials(oauthToken)
                });
            }
            catch (Exception ex)
            {
                Logger.WarnFormat("Error trying to generate OAuth Token for TFS connection\n{0}", ex);
                return(new List <TfsClientCredentials>());
            }
        }
示例#22
0
        private void DoPayPalPayment(double price)
        {
            var config      = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            var payout = new Payout
            {
                sender_batch_header = new PayoutSenderBatchHeader
                {
                    sender_batch_id = "batch_" + Guid.NewGuid().ToString().Substring(0, 8),
                    email_subject   = "You have payment",
                    recipient_type  = PayoutRecipientType.EMAIL
                },

                items = new List <PayoutItem>
                {
                    new PayoutItem
                    {
                        recipient_type = PayoutRecipientType.EMAIL,
                        amount         = new Currency {
                            value = price.ToString(), currency = "USD"
                        },
                        receiver       = "*****@*****.**",
                        note           = "Thank you",
                        sender_item_id = "item_1"
                    }
                }
            };

            var created = payout.Create(apiContext, false);
        }
        public void OAuthTokenCredentialCtorNullValuesTest()
        {
            var oauthTokenCredential = new OAuthTokenCredential(null, null, null);

            Assert.IsTrue(string.IsNullOrEmpty(oauthTokenCredential.ClientId));
            Assert.IsTrue(string.IsNullOrEmpty(oauthTokenCredential.ClientSecret));
        }
示例#24
0
        /// <summary>
        /// Generate the credentials with the existing credentials or challenge the user to enter credentials.
        /// </summary>
        public async Task <Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            OAuthTokenCredential credential = null;

            try
            {
                // Portal "single sign in" check when trying to load webmap
                if (info.Response != null && info.ServiceUri.StartsWith(MyServerUrl))
                {
                    Credential existingCredential = IdentityManager.Current.FindCredential(info.ServiceUri);
                    if (existingCredential != null)
                    {
                        // Already logged in and current user does not have access
                        throw new Exception("Current logged in user does not have access.");
                    }
                }

                // Modify generate token options if necessary
                if (info.GenerateTokenOptions == null)
                {
                    info.GenerateTokenOptions = new GenerateTokenOptions();
                }

                // Identity Manager will handle challenging the user for credentials
                credential = await IdentityManager.Current.GenerateCredentialAsync(
                    info.ServiceUri, info.GenerateTokenOptions
                    ) as OAuthTokenCredential;

                // Switch to UI thread to change control state and content
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                               () =>
                {
                    SignInButton.IsEnabled      = false;
                    SignOutButton.IsEnabled     = true;
                    LoadWebMapButton.IsEnabled  = true;
                    LoggedInUserName.Text       = string.Format("Logged in as: {0}", credential.UserName);
                    LoggedInUserName.Visibility = Visibility.Visible;
                });


                // Store the RefreshToken
                if (credential.OAuthRefreshToken != null)
                {
                    StoreRefreshToken(credential.OAuthRefreshToken);
                }

                // Not a challenge, user initiated directly
                if (info.Response == null)
                {
                    IdentityManager.Current.AddCredential(credential);
                }
            }
            catch (Exception ex)
            {
                throw (ex);                 // Exception will be reported in calling function
            }

            return(credential);
        }
        private string GetAccessToken()
        {
            // getting accesstocken from paypal
            string accessToken = new OAuthTokenCredential
                                     (_settingPaypal["ClientId"], _settingPaypal["ClientSecretKey"], GetConfig()).GetAccessToken();

            return(accessToken);
        }
        public void OAuthTokenCredentialCtorEmptyConfigTest()
        {
            var config = new Dictionary <string, string>();
            var oauthTokenCredential = new OAuthTokenCredential(config);

            Assert.IsTrue(string.IsNullOrEmpty(oauthTokenCredential.ClientId));
            Assert.IsTrue(string.IsNullOrEmpty(oauthTokenCredential.ClientSecret));
        }
示例#27
0
        private static string GetAccessToken()
        {
            // getting accesstocken from paypal
            string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();

            //string accessToken = new OAuthTokenCredential("sk_test_hcmP8DXpYwpyinHpUYzjo7NT000xY9Afqm", "pk_test_P9R7dH3l5Rf7xPd6NlIY1vBF007pCUR4vB", GetConfig()).GetAccessToken();
            return(accessToken);
        }
        private APIContext GetAPIContext()
        {
            var config      = ConfigManager.Instance.GetProperties();
            var accessToken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            return(apiContext);
        }
示例#29
0
        public APIContext GetAPIContext()
        {
            Dictionary <string, string> config = ConfigManager.Instance.GetProperties();
            string     accessToken             = new OAuthTokenCredential(config).GetAccessToken();
            APIContext apiContext = new APIContext(accessToken);

            return(apiContext);
        }
        public void OAuthTokenCredentialCtorNullValuesTest()
        {
            // If null values are passed in, OAuthTokenCredential uses the values specified in the config.
            var oauthTokenCredential = new OAuthTokenCredential(null, null, null);

            Assert.IsTrue(!string.IsNullOrEmpty(oauthTokenCredential.ClientId));
            Assert.IsTrue(!string.IsNullOrEmpty(oauthTokenCredential.ClientSecret));
        }
示例#31
0
        public void Can_Get_An_AccessToken()
        {
            //// Arrange
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.DefaultConnectionLimit = 9999;

            var settings = ((PayPalApiService)PayPalApiService).Settings;

            var sdkConfig = settings.GetApiSdkConfig();

            //// Act
            var accessToken = new OAuthTokenCredential(settings.ClientId, settings.ClientSecret, sdkConfig.Result).GetAccessToken();

            //// Assert
            Console.WriteLine(accessToken);
            Assert.NotNull(accessToken);
        }
示例#32
0
        public ActionResult Capture(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var total = Convert.ToDecimal(authorization.amount.total);

                    var capture = authorization.Capture(apiContext, new Capture
                       {
                           is_final_capture = true,
                           amount = new Amount
                           {
                               currency = "USD",
                               total = (total + (total * .05m)).ToString("f2")
                           },
                       });

                    viewData.JsonResponse = JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented);

                    return View("Success", viewData);
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
示例#33
0
        public ActionResult Confirmed(Guid id, string token, string payerId)
        {
            var viewData = new ConfirmedViewData
            {
                Id = id,
                Token = token,
                PayerId = payerId
            };

            var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            var payment = new Payment()
            {
                id = (string)Session[id.ToString()],
            };

            var executedPayment = payment.Execute(apiContext, new PaymentExecution { payer_id = payerId });

            viewData.AuthorizationId = executedPayment.transactions[0].related_resources[0].authorization.id;
            viewData.JsonRequest = JObject.Parse(payment.ConvertToJson()).ToString(Formatting.Indented);
            viewData.JsonResponse = JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented);

            return View(viewData);
        }
示例#34
0
 /// <summary>
 /// gets acces token and creates apiContext for Paypal api
 /// </summary>
 /// <returns>ApiContext</returns>
 private APIContext GetAPIContext()
 {
     Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
     sdkConfig.Add("mode", "sandbox");
     string accessToken = new OAuthTokenCredential("Ae2ZWMxCl_ueuNy87vcg52hTjX9aVWfnvLQSMjDuTn2sj0crrWYIWwPseO_6H4nLpXKcHE9_DjtrmDEC", "EEmZr7iiuNCksXtPh5NjcVcguVGic0TwCW-f7GFmgfmrG8wBUhn_UJj53OxraTkKijC4UYQHv-fzlH7z", sdkConfig).GetAccessToken();
     APIContext apiContext = new APIContext(accessToken);
     return apiContext;
 }
        /// <summary>
        /// Retrieves all ArcGISRuntime credentials stored in the isolated storage.
        /// </summary>
        public static IEnumerable<Credential>  RetrieveAll()
        {
            var credentials = new List<Credential>();
            foreach(var cachedCredential in GetCachedCredentials())
            {
                Credential credential = null;
                string userName = cachedCredential.UserName;
                string passwordValue = cachedCredential.Password; // value stored as password
                string serviceUrl = cachedCredential.Url;

                // Create the credential depending on the type
                if (passwordValue.StartsWith(PasswordPrefix))
                {
                    string password = passwordValue.Substring(PasswordPrefix.Length);
                    credential = new ArcGISTokenCredential { ServiceUri = serviceUrl, UserName = userName, Password = password, Token = "dummy" }; // dummy to remove once the token will be refreshed pro actively
                }
                else if (passwordValue.StartsWith(OAuthRefreshTokenPrefix))
                {
                    string refreshToken = passwordValue.Substring(OAuthRefreshTokenPrefix.Length);
                    credential = new OAuthTokenCredential
                    {
                        ServiceUri = serviceUrl,
                        UserName = userName,
                        OAuthRefreshToken = refreshToken,
                        Token = "dummy"
                    };
                }
                else if (passwordValue.StartsWith(OAuthAccessTokenPrefix))
                {
                    string token = passwordValue.Substring(OAuthAccessTokenPrefix.Length);
                    credential = new OAuthTokenCredential
                    {
                        ServiceUri = serviceUrl,
                        UserName = userName,
                        Token = token,
                    };
                }
                else if (passwordValue.StartsWith(NetworkCredentialPasswordPrefix))
                {
                    string password = passwordValue.Substring(NetworkCredentialPasswordPrefix.Length);
                    credential = new ArcGISNetworkCredential { ServiceUri = serviceUrl, Credentials = new NetworkCredential(userName, password) };
                }
                else if (passwordValue.StartsWith(CertificateCredentialPrefix))
                {
                    string serial = passwordValue.Substring(CertificateCredentialPrefix.Length);
                    var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    X509Certificate2Collection certificates;
                    try
                    {
                        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                        // Find certificate by serial number
                        certificates = store.Certificates.Find(X509FindType.FindBySerialNumber, serial, true);
                    }
                    catch (Exception)
                    {
                        certificates = null;
                    }
                    finally
                    {
                        store.Close();
                    }
                    if (certificates != null && certificates.Count > 0)
                        credential = new CertificateCredential(certificates[0]) { ServiceUri = serviceUrl };
                }

                if (credential != null)
                {
                    credentials.Add(credential);
                }
            }
            return credentials;
        }
示例#36
0
		public void TriggerOAuth2TokenTokenReceivedEvent(OAuthTokenCredential oAuth2Token)
		{
			OAuth2TokenTokenReceived(oAuth2Token);
		}
		/// <summary>
		/// Check whether a refresh token exists. If yes, then add the credentials associated with the refresh token to the Identity Manager. If not,
		/// return to the app and wait for the user to click the Sign In button. 
		/// </summary>
		private async void CheckUseRefreshToken()
		{
			try
			{
				string refreshToken = await LoadRefreshToken();
				if (string.IsNullOrEmpty(refreshToken))
					return;

				OAuthTokenCredential credential = new OAuthTokenCredential();
				credential.OAuthRefreshToken = refreshToken;
				credential.ServiceUri = MyServerUrl;

				credential.GenerateTokenOptions = new GenerateTokenOptions
				{
					TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode,
				};

				await credential.RefreshTokenAsync();

				IdentityManager.Current.AddCredential(credential);

				SignOutButton.IsEnabled = true;
				SignInButton.IsEnabled = false;
				LoadWebMapButton.IsEnabled = true;
				LoggedInUserName.Text = string.Format("Logged in as: {0}", credential.UserName);
				LoggedInUserName.Visibility = Visibility.Visible;
			}
			catch (Exception ex)
			{
				ShowDialog(ex.Message);
			}
		}
示例#38
0
        private IEnumerable<TfsClientCredentials> GetOAuthCredentials()
        {
            try
            {
                var usernameAndPassword = GetServiceIdentityUsernameAndPasswordFromConfig();

                if (usernameAndPassword == null || 
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthClientId) ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthContext) ||
                    string.IsNullOrEmpty(_config.TfsServerConfig.OAuthResourceId))
                {
                    return new List<TfsClientCredentials>();
                }

                var userCredential = new UserCredential(usernameAndPassword.Item1, usernameAndPassword.Item2);
                var authContext = new AuthenticationContext(_config.TfsServerConfig.OAuthContext);
                var result = authContext.AcquireToken(_config.TfsServerConfig.OAuthResourceId, _config.TfsServerConfig.OAuthClientId, userCredential);
                var oauthToken = new OAuthTokenCredential(result.AccessToken);
                return new List<TfsClientCredentials>()
                {
                    new TfsClientCredentials(oauthToken)
                };
            }
            catch (Exception ex)
            {
                Logger.WarnFormat("Error trying to generate OAuth Token for TFS connection\n{0}", ex);
                return new List<TfsClientCredentials>();
            }
        }
        public bool CreatePayment(string priceStr, string description)
        {
            try
            {
                // Authenticate with PayPal
                var config = ConfigManager.Instance.GetProperties();
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                apiContext = new APIContext(accessToken);

                var itemList = new ItemList()
                {
                    items = new List<Item>()
                    {
                        new Item()
                        {
                            name = "PrintAhead print",
                            currency = "USD",
                            price = priceStr,
                            quantity = "1",
                            sku = "sku"
                        }
                    }
                };

                var payer = new Payer() { payment_method = "paypal" };
                var redirUrls = new RedirectUrls()
                {
                    cancel_url = "http://www.abalonellc.com/hairshop-10-coming-so10.html",
                    return_url = "http://www.abalonellc.com/"
                };

                var details = new Details()
                {
                    tax = "0",
                    shipping = "0",
                    subtotal = priceStr
                };

                var amount = new Amount()
                {
                    currency = "USD",
                    total = priceStr, // Total must be equal to sum of shipping, tax and subtotal.
                    details = details
                };

                var transactionList = new List<Transaction>
                {
                    new Transaction()
                    {
                        description = description, // transaction description
                        invoice_number = GetRandomInvoiceNumber(),
                        amount = amount,
                        item_list = itemList
                    }
                };

                var payment = new Payment()
                {
                    intent = "sale",
                    payer = payer,
                    transactions = transactionList,
                    redirect_urls = redirUrls
                };

                createdPayment = payment.Create(apiContext);
                var links = createdPayment.links.GetEnumerator();
                var hasGoodLink = false;
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link != null && link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        chromeBrowser.Load(link.href);
                        hasGoodLink = true;
                        break;
                    }
                }

                if (!hasGoodLink)
                    return false;
            }
            catch (PaymentsException ex)
            {
                // Get the details of this exception with ex.Details.  If you have logging setup for your project, this information will also be automatically logged to your logfile.
                var sb = new StringBuilder();
                sb.AppendLine("Error:    " + ex.Details.name);
                sb.AppendLine("Message:  " + ex.Details.message);
                sb.AppendLine("URI:      " + ex.Details.information_link);
                sb.AppendLine("Debug ID: " + ex.Details.debug_id);
                MessageBox.Show(sb.ToString());
                return false;
            }
            return true;
        }
 public void GetAccessTokenTest()
 {
     Dictionary<string, string> config = new Dictionary<string, string>();
     config.Add("endpoint", "https://api.sandbox.paypal.com");
     string clientId = "EBWKjlELKMYqRNQ6sYvFo64FtaRLRR5BdHEESmha49TM";
     string clientSecret = "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM";
     OAuthTokenCredential target = new OAuthTokenCredential(clientId, clientSecret, config);
     string expected = string.Empty;
     string actual;
     actual = target.GetAccessToken();
     Assert.AreEqual(true, actual.StartsWith("Bearer "));
 }
		private OAuthTokenCredential ParseResult(string jsonWebResponse)
		{
			OAuth2TokenResult results;
			try
			{
				using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonWebResponse)))
				{
					var serializer = new DataContractJsonSerializer(typeof (OAuth2TokenResult));
					results = serializer.ReadObject(stream) as OAuth2TokenResult;
				}
			}
			catch (Exception)
			{
				results = null;
			}

			var oAuthTokenCredential = new OAuthTokenCredential();

			if (results != null && results.AccessToken != null)
			{
				// Token returned --> no error
				oAuthTokenCredential.Token = results.AccessToken;
				oAuthTokenCredential.OAuthRefreshToken = results.RefreshToken;
				oAuthTokenCredential.UserName = results.Username;

				if (results.ExpiresIn != null)
				{
					long expiresIn;
					Int64.TryParse(results.ExpiresIn, out expiresIn);
					oAuthTokenCredential.ExpirationDate = DateTime.UtcNow + TimeSpan.FromSeconds(expiresIn);
				}

				if (string.IsNullOrEmpty(oAuthTokenCredential.Token))
				{
					throw new AuthenticationException("Empty token generated");
				}
			}
			else
			{
				// Error
				string message = "No token generated";
				if (results != null && results.Error != null)
				{
					OAuth2TokenError tokenError = results.Error;
					if (tokenError != null)
					{
						if (tokenError.Message != null)
						{
							message = tokenError.Message;
						}
						if (tokenError.Details != null)
						{
							object messages = tokenError.Details;
							if (messages is string)
							{
								message += string.Format("{0}{1}", message.Length > 0 ? Environment.NewLine : string.Empty, messages);
							}
							else if (messages is IEnumerable)
							{
								message += string.Format("{0}{1}", message.Length > 0 ? Environment.NewLine : string.Empty,
									(messages as IEnumerable).OfType<String>().FirstOrDefault());
							}
						}
						if (tokenError.ErrorDescription != null)
						{
							message += string.Format("{0}{1}", message.Length > 0 ? Environment.NewLine : string.Empty,
								tokenError.ErrorDescription);
						}
					}
				}
				throw new AuthenticationException(message);
			}
			return oAuthTokenCredential;
		}
        /// <summary>
        /// Retrieves all ArcGISRuntime credentials stored in the Credential Locker.
        /// </summary>
        public static IEnumerable<Credential>  RetrieveAll()
        {
            var passwordVault = new PasswordVault();
            var credentials = new List<Credential>();
            foreach (PasswordCredential passwordCredential in passwordVault.RetrieveAll().Where(pc => pc.Resource.StartsWith(ResourcePrefix)))
            {
                Credential credential = null;
                passwordCredential.RetrievePassword();
                string userName = passwordCredential.UserName;
                string passwordValue = passwordCredential.Password; // value stored as password
                string serviceUrl = passwordCredential.Resource.Substring(ResourcePrefix.Length);

                // Create the credential depending on the type
                if (passwordValue.StartsWith(PasswordPrefix))
                {
                    string password = passwordValue.Substring(PasswordPrefix.Length);
                    credential = new ArcGISTokenCredential { ServiceUri = serviceUrl, UserName = userName, Password = password, Token = "dummy"}; // dummy to remove once the token will be refreshed pro actively
                }
                else if (passwordValue.StartsWith(OAuthRefreshTokenPrefix))
                {
                    string refreshToken = passwordValue.Substring(OAuthRefreshTokenPrefix.Length);
                    credential = new OAuthTokenCredential
                    {
                        ServiceUri = serviceUrl,
                        UserName = userName,
                        OAuthRefreshToken = refreshToken,
                        Token = "dummy"
                    };
                }
                else if (passwordValue.StartsWith(OAuthAccessTokenPrefix))
                {
                    string token = passwordValue.Substring(OAuthAccessTokenPrefix.Length);
                    credential = new OAuthTokenCredential
                    {
                        ServiceUri = serviceUrl,
                        UserName = userName,
                        Token = token,
                    };
                }
                else if (passwordValue.StartsWith(NetworkCredentialPasswordPrefix))
                {
                    string password = passwordValue.Substring(NetworkCredentialPasswordPrefix.Length);
                    credential = new ArcGISNetworkCredential {ServiceUri = serviceUrl, Credentials = new NetworkCredential(userName, password)};
                }

                if (credential != null)
                {
                    credentials.Add(credential);
                }
            }
            return credentials;
        }
示例#43
0
        public ActionResult Void(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var voidedAuthorization = authorization.Void(apiContext);

                    viewData.JsonResponse = JObject.Parse(voidedAuthorization.ConvertToJson()).ToString(Formatting.Indented);

                    return View(viewData);
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
示例#44
0
        //
        // GET: /Payment/
        public ActionResult CreatePayment(string description, decimal price, decimal tax = 0, decimal shipping = 0)
        {
            var viewData = new PayPalViewData();
            var guid = Guid.NewGuid().ToString();

            var paymentInit = new Payment
            {
                intent = "authorize",
                payer = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new List<Transaction>
                {
                    new Transaction
                    {
                        amount = new Amount
                        {
                            currency = "USD",
                            total = (price + tax + shipping).ToString(),
                            details = new Details
                            {
                                subtotal = price.ToString(),
                                tax = tax.ToString(),
                                shipping = shipping.ToString()
                            }
                        },
                        description = description
                    }
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/paypal/confirmed?id={0}", guid)),
                    cancel_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/paypal/canceled?id={0}", guid)),
                },
            };

            viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Formatting.Indented);

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var createdPayment = paymentInit.Create(apiContext);

                var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));

                if (approvalUrl != null)
                {
                    Session.Add(guid, createdPayment.id);

                    return Redirect(approvalUrl.href);
                }

                viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented);

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }