Пример #1
0
        public void Run(string[] args)
        {
            Dictionary <string, string> allOption = AssertMandatoryOptions(args);

            BunqContext.LoadApiContext(
                ApiContext.Restore(allOption[OPTION_CONTEXT])
                );

            OauthClient oauthClient;

            if (File.Exists(FILE_OAUTH_CONFIGURATION))
            {
                oauthClient = OauthClient.CreateFromJsonString(File.ReadAllText(FILE_OAUTH_CONFIGURATION));
            }
            else
            {
                int oauthClientId = OauthClient.Create().Value;

                OauthCallbackUrl.Create(oauthClientId, allOption[OPTION_REDIRECT_URI]);
                oauthClient = OauthClient.Get(oauthClientId).Value;

                String serializedClient = BunqJsonConvert.SerializeObject(oauthClient);
                File.WriteAllText(FILE_OAUTH_CONFIGURATION, serializedClient);
            }

            OauthAuthorizationUri authorizationUri = OauthAuthorizationUri.Create(
                OauthResponseType.CODE,
                allOption[OPTION_REDIRECT_URI],
                oauthClient
                );

            Console.WriteLine(" | Created oauth client. Stored in {0}.", FILE_OAUTH_CONFIGURATION);
            Console.WriteLine(" | Point your user to {0} to obtain an Authorization code.", authorizationUri.AuthorizationUri);
        }
Пример #2
0
        public async Task PostsWithCorrectBodyAndContentType()
        {
            var responseToken = new OauthToken(null, null, null);
            var response      = Substitute.For <IApiResponse <OauthToken> >();

            response.Body.Returns(responseToken);
            var connection = Substitute.For <IConnection>();

            connection.BaseAddress.Returns(new Uri("https://api.github.com/"));
            Uri calledUri = null;
            FormUrlEncodedContent calledBody = null;
            Uri calledHostAddress            = null;

            connection.Post <OauthToken>(
                Arg.Do <Uri>(uri => calledUri      = uri),
                Arg.Do <object>(body => calledBody = body as FormUrlEncodedContent),
                "application/json",
                null,
                Arg.Do <Uri>(uri => calledHostAddress = uri))
            .Returns(_ => Task.FromResult(response));
            var client = new OauthClient(connection);

            var token = await client.CreateAccessToken(new OauthTokenRequest("secretid", "secretsecret", "code")
            {
                RedirectUri = new Uri("https://example.com/foo")
            });

            Assert.Same(responseToken, token);
            Assert.Equal("login/oauth/access_token", calledUri.ToString());
            Assert.NotNull(calledBody);
            Assert.Equal("https://github.com/", calledHostAddress.ToString());
            Assert.Equal(
                "client_id=secretid&client_secret=secretsecret&code=code&redirect_uri=https%3A%2F%2Fexample.com%2Ffoo",
                await calledBody.ReadAsStringAsync());
        }
Пример #3
0
        public EtradeExchange(ExchangeConfig config)
            : base(config)
        {
            Dictionary <string, string> tokenUrls = new Dictionary <string, string>()
            {
                { "request_token_url", EndPoints.REQUEST_TOKEN },
                { "token_authorize_url", EndPoints.AUTHORIZE_TOKEN },
                { "access_token_url", EndPoints.ACCESS_TOKEN },
                { "renew_access_token_url", EndPoints.RENEW_ACCESS_TOKEN },
            };
            Dictionary <string, string> signParams = new Dictionary <string, string>()
            {
                { "callback", "oob" },
                { "consumer_key", this.AuthVal.Key },
                { "nonce", string.Empty },
                { "timestamp", string.Empty },
                { "signature_method", "HMAC-SHA1" },
                { "version", "1.0" },
                { "consumer_secret", this.AuthVal.Secret },
                { "token", string.Empty },
                { "token_secret", string.Empty },
                { "verifier", string.Empty }
            };

            ApiClient = new OauthClient(this.AuthVal, tokenUrls, signParams);
            converter = new EtradeConvert();
        }
        public static OauthAuthorizationUri Create(
            OauthResponseType responseType,
            string redirectUri,
            OauthClient client,
            string state = null
            )
        {
            Dictionary <string, string> allRequestParameter = new Dictionary <string, string>();

            allRequestParameter.Add(FIELD_REDIRECT_URI, redirectUri);
            allRequestParameter.Add(FIELD_RESPONSE_TYPE, responseType.TypeString);

            if (!string.IsNullOrEmpty(client.ClientId))
            {
                allRequestParameter.Add(FIELD_CLIENT_ID, client.ClientId);
            }

            if (!string.IsNullOrEmpty(state))
            {
                allRequestParameter.Add(FIELD_STATE, state);
            }

            return(new OauthAuthorizationUri(
                       string.Format(DetermineTokenUriFormat(), HttpUtils.CreateQueryString(allRequestParameter))
                       ));
        }
Пример #5
0
        public void ReturnsProperAuthorizeUrl(string baseAddress, string expectedUrl)
        {
            var connection = Substitute.For <IConnection>();

            connection.BaseAddress.Returns(new Uri(baseAddress));
            var client = new OauthClient(connection);

            var result = client.GetGitHubLoginUrl(new OauthLoginRequest("secret"));

            Assert.Equal(new Uri(expectedUrl), result);
        }
Пример #6
0
        /// <summary>
        /// Create access token
        /// </summary>
        public static OauthAccessToken Create(
            OauthGrantType grantType,
            string authCode,
            string redirectUri,
            OauthClient client
            )
        {
            HttpClient          apiClient   = new HttpClient();
            HttpResponseMessage responseRaw = apiClient.PostAsync(
                CreateTokenUri(grantType, authCode, redirectUri, client),
                null
                ).Result;

            return(BunqJsonConvert.DeserializeObject <OauthAccessToken>(responseRaw.Content.ReadAsStringAsync().Result));
        }
Пример #7
0
        /// <summary>
        /// Create token URI string.
        /// </summary>
        protected static string CreateTokenUri(
            OauthGrantType grantType,
            string authCode,
            string redirectUri,
            OauthClient client
            )
        {
            Dictionary <string, string> allTokenParameter = new Dictionary <string, string>()
            {
                { FIELD_GRANT_TYPE, grantType.TypeString },
                { FIELD_CODE, authCode },
                { FIELD_REDIRECT_URI, redirectUri },
                { FIELD_CLIENT_ID, client.ClientId },
                { FIELD_CLIENT_SECRET, client.Secret },
            };

            return(String.Format(DetermineTokenUriFormat(), HttpUtils.CreateQueryString(allTokenParameter)));
        }
Пример #8
0
        public void ReturnsUrlWithAllParameters()
        {
            var request = new OauthLoginRequest("secret")
            {
                RedirectUri = new Uri("https://example.com/foo?foo=bar"),
                Scopes      = { "foo", "bar" },
                State       = "canARY"
            };
            var connection = Substitute.For <IConnection>();

            connection.BaseAddress.Returns(new Uri("https://api.github.com"));
            var client = new OauthClient(connection);

            var result = client.GetGitHubLoginUrl(request);

            Assert.Equal("/login/oauth/authorize", result.AbsolutePath);
            Assert.Equal("?client_id=secret&redirect_uri=https%3A%2F%2Fexample.com%2Ffoo%3Ffoo%3Dbar&scope=foo%2Cbar&state=canARY", result.Query);
        }
Пример #9
0
        public void TestCreateOauthClient()
        {
            if (File.Exists(FILE_TEST_OAUTH))
            {
                return;
            }

            int         clientId    = OauthClient.Create().Value;
            OauthClient oauthClient = OauthClient.Get(clientId).Value;

            Assert.NotNull(oauthClient);

            File.WriteAllText(
                FILE_TEST_OAUTH,
                BunqJsonConvert.SerializeObject(oauthClient)
                );
            Assert.True(File.Exists(FILE_TEST_OAUTH));
        }
Пример #10
0
        private static void Main(string[] args)
        {
            var environmentType   = ApiEnvironmentType.SANDBOX;
            var deviceDescription = "C# PSD2 test runner";
            var permittedIps      = new List <string>();
            var redirectUri       = "https://postman-echo.com/get";
            var certificateString =
                @"-----BEGIN CERTIFICATE-----
Please use the following command to generate a certificate for sandbox:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=<YOUR COMPANY NAME> PISP AISP/C=NL'

Make sure to supply a company name or any other identifier so that we'll be able to assist you if you have any problems.

Replace that text with the contents of cert.pem

-----END CERTIFICATE-----";

            var privateKeyString =
                @"-----BEGIN PRIVATE KEY-----
Please use the command described above to get certificate and a private key.

Replace that text with the contents of key.pem

-----END PRIVATE KEY-----";

            var certificateChainString =
                @"-----BEGIN CERTIFICATE-----
MIID1zCCAr+gAwIBAgIBATANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJOTDEW
MBQGA1UECBMNTm9vcmQtSG9sbGFuZDESMBAGA1UEBxMJQW1zdGVyZGFtMRIwEAYD
VQQKEwlidW5xIGIudi4xDzANBgNVBAsTBkRldk9wczEVMBMGA1UEAxMMUFNEMiBU
ZXN0IENBMB4XDTE5MDIxODEzNDkwMFoXDTI5MDIxODEzNDkwMFowdTELMAkGA1UE
BhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQxEjAQBgNVBAcTCUFtc3RlcmRh
bTESMBAGA1UEChMJYnVucSBiLnYuMQ8wDQYDVQQLEwZEZXZPcHMxFTATBgNVBAMT
DFBTRDIgVGVzdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALOv
zPl+uegBpnFhXsjuKs0ws00e+232wR9tvDqYBjGdOlYorw8CyrT+mr0HKO9lx7vg
xhJ3f+oonkZvBb+IehDmEsBbZ+vRtdjEWw3RTWVBT69jPcRQGE2e5qUuTJYVCONY
JsOQP8CoCHXa6+oUSmUyMZX/zNJhTvbLV9e/qpIWwWVrKzK0EEB5c71gITNgzOXG
+lIKJmOnvvJyWPCx02hIgQI3nVphDj8ydMEKuwTgBrFV5Lqkar3L6ngF7LgzjXPC
Nbf3JL/2Ccp0hYPb2MLVEpYba8/38eN6izjorJiwu+uGehOpj/RNcfv27iGyvXRY
FC2PfRP8ZP5CpoijJR8CAwEAAaNyMHAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
FgQU38gzLVi6UQYiNLXKIhwoklPnSYMwCwYDVR0PBAQDAgEGMBEGCWCGSAGG+EIB
AQQEAwIABzAeBglghkgBhvhCAQ0EERYPeGNhIGNlcnRpZmljYXRlMA0GCSqGSIb3
DQEBCwUAA4IBAQBt6HBrnSvEbUX514ab3Zepdct0QWVLzzEKFC8y9ARLWttyaRJ5
AhzCa4t8LJnyoYuEPHOKDIsqLzmJlwqBnsXPuMdWEd3vnFRgj1oL3vVqoJwrfqDp
S3jHshWopqMKtmzAO9Q3BWpk/lrqJTP1y/6057LtMGhwA6m0fDmvA+VuTrh9mgzw
FgWwmahVa08h1Cm5+vc1Phi8wVXi3R1NzmVUQFYOixSwifs8P0MstBfCFlBFQ47C
EvGEYvOBLlEiiaoMUT6aoYj+L8zHWXakSQFAzIzQFJn668q2ds6zx67P7wKFZ887
VJSv7sTqspxON1s1oFlkRXu5JihaVJcHmFAY
-----END CERTIFICATE-----";

            if (certificateString.Contains("Please"))
            {
                Console.WriteLine("Please generate a certificate and a private key and update the code.");
                Console.WriteLine();
                Console.WriteLine("Use the following command:");
                Console.WriteLine("openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=<YOUR COMPANY NAME> PISP AISP/C=NL'");
                return;
            }

            var certificatePublic = new X509Certificate2(Encoding.UTF8.GetBytes(certificateString));

            var keyPair = SecurityUtils.CreateKeyPairFromPrivateKeyFormattedString(
                privateKeyString);
            var certificate = certificatePublic.CopyWithPrivateKey(keyPair);

            var certificateChain = new X509Certificate2Collection();

            certificateChain.Import(Encoding.UTF8.GetBytes(
                                        certificateChainString
                                        ));

            var psd2ApiContext = ApiContext.CreateForPsd2(environmentType, certificate, certificateChain,
                                                          deviceDescription, permittedIps);

            BunqContext.LoadApiContext(psd2ApiContext);
            var allOauthClient = OauthClient.List();

            if (!allOauthClient.Value.Any())
            {
                OauthClient.Create("ACTIVE");
                allOauthClient = OauthClient.List();
            }

            var client = allOauthClient.Value.First();

            Debug.Assert(client.Id != null, "client.Id != null");
            if (OauthCallbackUrl.List(client.Id.Value).Value.All(ocu => ocu.Url != redirectUri))
            {
                OauthCallbackUrl.Create(client.Id.Value, redirectUri);
            }

            Console.WriteLine(JsonConvert.SerializeObject(client));

            Console.WriteLine("To continue, you'll need a user with an installed app. For sandbox it needs to be " +
                              "an android app downloadable from https://appstore.bunq.com/api/android/builds/bunq-android-sandbox-master.apk");
            Console.WriteLine("You can create a sandbox user using tinker, see links at https://www.bunq.com/developer");
            Console.WriteLine("Run UserOverview, that'll show the user's phone number and add some money to the account.");
            Console.WriteLine("You can then login in app with phone/email displayed by tinker script and login code 000000");
            Console.WriteLine("If the app tries to send a code to phone it's going to be 123456");
            Console.WriteLine("If the app tries to scan 4 fingers, any finger-like picture should be accepted");
            Console.WriteLine();
            Console.WriteLine("https://oauth.sandbox.bunq.com/auth?response_type=code&client_id=" + client.ClientId +
                              "&redirect_uri=" + redirectUri);
            Console.WriteLine();
            Console.WriteLine(
                "Please direct user to the above url. When you successfully authorized the code in the app," +
                "it'll redirect to the website with the code. Please input the code: \n");
            var code     = Console.ReadLine();
            var tokenUrl = "https://api-oauth.sandbox.bunq.com/v1/token?grant_type=authorization_code&code=" + code +
                           "&redirect_uri=" + redirectUri + "&client_id=" + client.ClientId + "&client_secret=" +
                           client.Secret;
            var httpClient         = new HttpClient();
            var tokenRequestResult = httpClient.PostAsync(tokenUrl, new StringContent("")).Result.Content
                                     .ReadAsStringAsync().Result;
            dynamic result = JsonConvert.DeserializeObject(
                tokenRequestResult
                );

            if (result.access_token != null)
            {
                string apiKey = result.access_token;

                var apiContext = ApiContext.Create(
                    environmentType, apiKey, deviceDescription, permittedIps);
                BunqContext.LoadApiContext(apiContext);
                Console.WriteLine(JsonConvert.SerializeObject(MonetaryAccount.List().Value.First()));
            }
            else
            {
                Console.WriteLine("Couldn't get token!");
                Console.WriteLine(tokenRequestResult);
            }
        }
Пример #11
0
 private OauthClient CreateOauthClientFromFile(String path)
 {
     return(OauthClient.CreateFromJsonString(
                File.ReadAllText(path)
                ));
 }