コード例 #1
1
        public async void Post_UserInfo()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());
            var objectName = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("access_token", auth.AccessToken)
                });

            var response = await serviceHttpClient.HttpPostAsync<UserInfo>(objectName, new Uri(auth.Id));

            Assert.IsNotNull(response);
        }
コード例 #2
0
        public async void Auth_UsernamePassword_Check()
        {
            const string consumerKey = "CONSUMERKEY";
            const string consumerSecret = "CONSUMERSECRET";
            const string username = "******";
            const string password = "******";

            var client = new HttpClient(new AuthenticationClientRouteHandler(r =>
            {
                Assert.IsNotNull(r.Content);
                Assert.AreEqual(r.Content.ToString(), "System.Net.Http.FormUrlEncodedContent");
            }));

            using (var auth = new AuthenticationClient(client))
            {
                await auth.UsernamePasswordAsync(consumerKey, consumerSecret, username, password);

                Assert.IsNotNull(auth.AccessToken);
                Assert.IsNotNull(auth.ApiVersion);
                Assert.IsNotNull(auth.InstanceUrl);
                Assert.AreEqual(auth.AccessToken, "AccessToken");
                Assert.AreEqual(auth.ApiVersion, "v34.0");
                Assert.AreEqual(auth.InstanceUrl, "InstanceUrl");
            }
        }
コード例 #3
0
        public void Init()
        {
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, TokenRequestEndpointUrl).Wait();

            _jsonHttpClient = new JsonHttpClient(_auth.InstanceUrl, _auth.ApiVersion, _auth.AccessToken, new HttpClient());
        }
コード例 #4
0
        public void Init()
        {
            _userAgent = "common-libraries-dotnet";
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, _userAgent, TokenRequestEndpointUrl).Wait();

            _serviceHttpClient = new ServiceHttpClient(_auth.InstanceUrl, _auth.ApiVersion, _auth.AccessToken, _userAgent, new HttpClient());
        }
コード例 #5
0
ファイル: Tests.cs プロジェクト: chivaughan/uber-sdk-for-net
        public void WebServer_Fail_Arguments()
        {
            var auth = new AuthenticationClient();

            Assert.That(async () => await auth.WebServerAsync("", "", "", ""), Throws.InstanceOf<ArgumentNullException>());
            Assert.That(async () => await auth.WebServerAsync("clientid", "", "", ""), Throws.InstanceOf<ArgumentNullException>());
            Assert.That(async () => await auth.WebServerAsync("clientid", "clientSecret", "", ""), Throws.InstanceOf<ArgumentNullException>());
            Assert.That(async () => await auth.WebServerAsync("clientid", "clientSecret", "redirectUri", ""), Throws.InstanceOf<ArgumentNullException>());
            Assert.That(async () => await auth.WebServerAsync("clientid", "clientSecret", "redirectUri", "code"), Throws.InstanceOf<ArgumentException>());
        }
コード例 #6
0
        public async void Query_Describe()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());
            var objectName = "Account";
            var response = await serviceHttpClient.HttpGetAsync<dynamic>(string.Format("sobjects/{0}", objectName));
            
            Assert.IsNotNull(response);
        }
コード例 #7
0
        public async void Query_Objects()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());

            var response = await serviceHttpClient.HttpGetAsync<DescribeGlobalResult<dynamic>>(string.Format("sobjects"));

            Assert.IsTrue(response.maxBatchSize > 0);
            Assert.IsTrue(response.sobjects.Count > 0);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: jayinatlanta/TechEd14SDK
        static void Main(string[] args)
        {
            var auth = new AuthenticationClient();
            auth.UsernamePasswordAsync(_clientId, _clientSecret, _username, _password).Wait();

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            var results = client.QueryAsync<dynamic>("SELECT Id, Name, Description FROM Account");
            results.Wait();

            var accounts = results.Result.records;

            Console.WriteLine(accounts.Count);
        }
コード例 #9
0
        public async void Query_Select_Count()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());

            var query = "SELECT count() FROM Account";
            var response = await serviceHttpClient.HttpGetAsync<QueryResult<dynamic>>(string.Format("query?q={0}", query));

            Assert.IsTrue(response.totalSize > 0);
            Assert.IsTrue(response.records.Count == 0);
        }
コード例 #10
0
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password))
            {
                _consumerKey = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username = Environment.GetEnvironmentVariable("Username");
                _password = Environment.GetEnvironmentVariable("Password");
            }

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, TokenRequestEndpointUrl).Wait();

            _serviceHttpClient = new ServiceHttpClient(_auth.InstanceUrl, _auth.ApiVersion, _auth.AccessToken, new HttpClient());
        }
コード例 #11
0
        public async Task <IActionResult> Portfolio(int id)
        {
            var user = await AuthenticationClient.AuthenticateAsync(HttpContext.Request);

            if (!await PortfolioReader.UserOwnsPortfolio(id, user.Id))
            {
                throw new UnauthorizedAccessException();
            }

            return(View(new PortfolioViewModel
            {
                User = user,
                Portfolio = await PortfolioReader.ReadByIdAsync(id),
                Report = await Reporter.GenerateAsync(user.Id, id)
            }));
        }
コード例 #12
0
        public async Task <IActionResult> QuestradeResponse(string code)
        {
            try
            {
                await Tokenizer.ExchangeAsync(
                    code,
                    await AuthenticationClient.AuthenticateAsync(HttpContext.Request),
                    Request.AbsoluteUrl("/questrade/response").UrlEncode());

                return(Redirect("/"));
            }
            catch (ErrorException ex)
            {
                return(Content(ex.Message));
            }
        }
コード例 #13
0
        // ReSharper disable once InconsistentNaming
        public void Token_Gets_The_Token_From_The_API_Client(string token)
        {
            var client = new ApiClientMock
            {
                DefaultRequestHeaders =
                {
                    ["Authorization"] = $"Bearer {token}"
                }
            };

            var parser = new ParserMock();

            var auth = new AuthenticationClient(client, parser);

            Assert.Equal(token, auth.Token);
        }
コード例 #14
0
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password) && string.IsNullOrEmpty(_organizationId))
            {
                _consumerKey    = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username       = Environment.GetEnvironmentVariable("Username");
                _password       = Environment.GetEnvironmentVariable("Password");
                _organizationId = Environment.GetEnvironmentVariable("OrganizationId");
            }

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password).Wait();

            _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);
        }
コード例 #15
0
        public async void Auth_InvalidLogin()
        {
            const string userAgent = "common-libraries-dotnet";

            try
            {
                var auth = new AuthenticationClient();
                await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, "WRONGPASSWORD", userAgent, _tokenRequestEndpointUrl);
            }
            catch (ForceAuthException ex)
            {
                Assert.IsNotNull(ex);
                Assert.IsNotNull(ex.Message);
                Assert.IsNotNull(ex.Error);
            }
        }
コード例 #16
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            if (string.IsNullOrWhiteSpace(allowedOrigin))
            {
                allowedOrigin = "*";
            }

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var authenticationClient = new AuthenticationClient();
            var response             = await authenticationClient.Authenticate(new AuthenticateRequest { Username = context.UserName });

            var authenticated = response.IsSuccess && response.AuthenticatedUser != null && PasswordHelper.VerifyPassword(context.Password, response.AuthenticatedUser.HashedPassword);

            if (!authenticated)
            {
                context.SetError("invalid_grant", "The email or password is incorrect");
                return;
            }

            var claims = new[] {
                new Claim("sub", context.UserName),
                new Claim("role", response.AuthenticatedUser.RoleName),
                new Claim("user_id", response.AuthenticatedUser.Id.ToString())
            };

            var identity = new ClaimsIdentity(claims, context.Options.AuthenticationType);

            if (response.AuthenticatedUser.RoleName == "user")
            {
                context.SetError("invalid_grant", "The user does not have permissions for this service");
                return;
            }

            var props = new AuthenticationProperties(new Dictionary <string, string> {
                { "as:client_id", context.ClientId == null ? string.Empty : context.ClientId },
                { "userName", context.UserName },
                { "role", response.AuthenticatedUser.RoleName },
                { "photo", response.AuthenticatedUser.Photo }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
コード例 #17
0
        /// <summary>
        /// Verifies the username and password submitted by the login form.
        /// If the information is valid then the user's course will be
        /// populated and the ribbon will be updated to a logged in state.
        /// Otherwise an error message will appear.
        /// </summary>
        private void RefreshProc()
        {
            //validate login information
            try
            {
                m_authtoken = AuthenticationClient.Login(m_user, m_pass);
                m_name      = AsyncServiceClient.GetName(m_authtoken).Result;

                if (m_name == null)
                {
                    m_name = "";
                }
            }

            //connection error
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                m_onComplete(this, new OSBLEStateEventArgs(false,
                                                           "Could not connect to the OSBLE server. " +
                                                           "Please contact support if this problem persists."));
                return;
            }

            //credentials error
            if (string.IsNullOrEmpty(m_authtoken))
            {
                m_onComplete(this, new OSBLEStateEventArgs(false,
                                                           "Could not log into OSBLE. " +
                                                           "Please check your user name and password."));
                return;
            }

            //login was successful so update collection of the user's courses
            UpdateCourses();

            //don't bother continuing to login if no courses found
            if (null == m_courses || 0 == m_courses.Length)
            {
                m_onComplete(this, new OSBLEStateEventArgs(false,
                                                           "No courses were found for this user."));
                return;
            }

            //TODO: consider filtering courses by the user's role

            m_onComplete(this, new OSBLEStateEventArgs(true, string.Empty));
        }
コード例 #18
0
        private async Task Run()
        {
            Dictionary <string, string> uri_list = new Dictionary <string, string>();

            var appRegistration = new AppRegistration {
                Instance     = hostName,
                ClientId     = clientId,
                ClientSecret = clientSecret,
                Scope        = Scope.Read | Scope.Write
            };
            var authClient = new AuthenticationClient(appRegistration);

            var auth = await authClient.ConnectWithPassword(mail, pass);

            client = new MastodonClient(appRegistration, auth);

            var account = await client.GetCurrentUser();

            this.userId = account.AccountName;

            // LTL処理
            streaming           = client.GetLocalStreaming();
            streaming.OnUpdate += (sender, e) => {
                TextWrite(e.Status);
            };

            //通知処理
            homeStreaming = client.GetUserStreaming();
            homeStreaming.OnNotification += (sender, e) => {
                NotificationWrite(e.Notification);
            };

            // メディア処理用
            media = new MediaEditClass(ref client);

            Timer timer = new Timer();

            timer.Interval = DefaultValues.TOOTS_INTERVAL;
            timer.Tick    += (object sender, EventArgs e) => {
                // トゥート回数のリセット
                tootsCounter = 0;
            };
            timer.Start();

            streaming.Start();
            homeStreaming.Start();
        }
コード例 #19
0
        public async void SendSignatureRequestFromDocument()
        {
            var auth = new AuthenticationClient(_username, _password, _integratorKey);
            await auth.LoginInformationAsync();

            var client = new DocuSignClient(auth);

            var documentName = "test.pdf";
            var fileStream   = File.OpenRead(documentName);
            var envelope     = await client.SendDocumentSignatureRequestAsync(documentName, _recipientName, _recipientEmail, "application/pdf", fileStream);

            Assert.IsNotNull(envelope);
            Assert.IsNotNull(envelope.envelopeId);
            Assert.IsNotNull(envelope.status);
            Assert.IsNotNull(envelope.statusDateTime);
            Assert.IsNotNull(envelope.uri);
        }
コード例 #20
0
        public void ForceClientAndAuthenticationClientThrowSameError()
        {
            //check that the ForceClient and AuthenticationClient both throw the same argument exception
            AuthenticationClient auth = new AuthenticationClient();

            ArgumentNullException acex = Assert.Throws <ArgumentNullException>(() =>
            {
                var client = new ForceClient("ClientId", "ClientSecret", "username", "", DefaultTokenRequestEndpoint);
            });

            ArgumentNullException fcex = Assert.Throws <ArgumentNullException>(() =>
                                                                               auth.UsernamePassword("ClientId", "ClientSecret", "username", "", DefaultTokenRequestEndpoint)
                                                                               );

            Assert.True(fcex.GetType() == acex.GetType());
            Assert.True(acex.Message == fcex.Message);
        }
コード例 #21
0
        public async Task <ActionResult> Callback(string code)
        {
            var auth = new AuthenticationClient();
            await auth.WebServerAsync(_clientId, _clientSecret, _callbackUrl, code);

            Session["ApiVersion"]   = auth.ApiVersion;
            Session["AccessToken"]  = auth.AccessToken;
            Session["RefreshToken"] = auth.RefreshToken;

            var client = new UberClient(TokenTypes.Access, auth.AccessToken, "v1", new HttpClient());

            var userActivity = await client.UserActivityAsync();

            var user = await client.UserAsync();

            return(RedirectToAction("Index", "Home"));
        }
コード例 #22
0
ファイル: DNFClient.cs プロジェクト: teamchong/DotNetForce
        public async Task TokenRefreshAsync(Uri loginUri, string clientId, string clientSecret = "")
        {
            if (loginUri == null)
            {
                throw new ArgumentNullException(nameof(loginUri));
            }
            using var auth = new AuthenticationClient { ApiVersion = ApiVersion };
            var tokenRequestEndpointUrl = new Uri(new Uri(loginUri.GetLeftPart(UriPartial.Authority)), "/services/oauth2/token").ToString();
            await auth.TokenRefreshAsync(clientId, RefreshToken, clientSecret, tokenRequestEndpointUrl)
            .ConfigureAwait(false);

            Id = auth.Id;

            //Id = auth.Id;
            InstanceUrl = auth.InstanceUrl;
            AccessToken = auth.AccessToken;
        }
コード例 #23
0
        public static async Task RefreshAccessTokenAsync(DesignTimeAuthentication designTimeAuthentication)
        {
            AuthenticationClient client = new AuthenticationClient();

            client.AccessToken  = designTimeAuthentication.AccessToken;
            client.RefreshToken = designTimeAuthentication.RefreshToken;
            client.InstanceUrl  = designTimeAuthentication.InstanceUrl;

            await client.TokenRefreshAsync(
                Constants.VisualStudioConnectedAppClientId,
                client.RefreshToken,
                string.Empty,
                new Uri(designTimeAuthentication.Domain, "/services/oauth2/token").ToString());

            designTimeAuthentication.AccessToken = client.AccessToken;
            designTimeAuthentication.InstanceUrl = client.InstanceUrl;
        }
コード例 #24
0
        public static async Task <IForceClient> CreateAuthenticationClient()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);

            AccessToken = auth.AccessToken;

            Client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            return(Client);
        }
コード例 #25
0
        public string GetGroups()
        {
            AuthenticationClient auth = new AuthenticationClient();

            using (var context = DataContext.getUasDbContext())
            {
                context.Configuration.LazyLoadingEnabled = false;

                //var groups = context.uas_Group.Where(i => i.EnterpriseID == enterpriseId).ToList();
                var groups = UAS.Business.LocalClient.GetChildGroups(SessionHelper.LoginStatus.EnterpriseID, SessionHelper.LoginStatus.appGroupPermissions[0].authorizedGroups[0])
                             .Where(id => id > -1)
                             .Select(groupId => context.uas_Group.FirstOrDefault(g => g.GroupID == groupId)).ToList();

                string jsonString = fastJSON.JSON.ToJSON(groups);
                return(jsonString);
            }
        }
コード例 #26
0
        private void CancelAuthentication(CancelAuthenticationRequest cancelAuthenticationRequest, TransactionContext transactionContext, string RelyingPartyId)
        {
            IAuthenticationClient authenticationClient = AuthenticationClient.Create(SslSettings.Create(TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.KEYSTORE_PATH_PKCS12), TestKeystoreUtil.KEYSTORE_PASSWORD, TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.CERTIFICATE_PATH)), FrejaEnvironment.TEST)
                                                         .SetHttpService(CommonTestData.HttpServiceMock.Object)
                                                         .SetTransactionContext(transactionContext).Build <AuthenticationClient>();

            CommonTestData.HttpServiceMock.Setup(x => x.Send <EmptyFrejaResponse>(It.IsAny <Uri>(), It.IsAny <string>(), It.IsAny <CancelAuthenticationRequest>(), It.IsAny <string>())).Returns(new EmptyFrejaResponse());
            authenticationClient.Cancel(cancelAuthenticationRequest);
            if (transactionContext.Equals(TransactionContext.PERSONAL))
            {
                CommonTestData.HttpServiceMock.Verify(x => x.Send <EmptyFrejaResponse>(new Uri(FrejaEnvironment.TEST + MethodUrl.AUTHENTICATION_CANCEL), RequestTemplate.CANCEL_AUTHENTICATION_TEMPLATE, cancelAuthenticationRequest, RelyingPartyId));
            }
            else
            {
                CommonTestData.HttpServiceMock.Verify(x => x.Send <EmptyFrejaResponse>(new Uri(FrejaEnvironment.TEST + MethodUrl.ORGANISATION_AUTHENTICATION_CANCEL), RequestTemplate.CANCEL_AUTHENTICATION_TEMPLATE, cancelAuthenticationRequest, RelyingPartyId));
            }
        }
コード例 #27
0
        public SalesForceClient(AuthModel auth)
        {
            var authenticator = new AuthenticationClient();

            authenticator.UsernamePasswordAsync(
                auth.ConsumerKey
                , auth.ConsumerSecret
                , auth.Username
                , String.Concat(auth.Password, auth.SecurityToken)
                , auth.TokenRequestPointUrl).Wait();

            var instanceUrl = authenticator.InstanceUrl;
            var accessToken = authenticator.AccessToken;
            var apiVersion  = authenticator.ApiVersion;

            _client = new ForceClient(instanceUrl, accessToken, apiVersion, new HttpClient());
        }
コード例 #28
0
        /// <summary>
        /// Gets a ForceClient that has been authenticated using the UserName, Password, and SecurityToken settings
        /// specified in the config file.
        /// </summary>
        /// <returns>The authenticated ForceClient.</returns>
        public static async Task <ForceClient> GetUserNamePasswordForceClientAsync()
        {
            using (AuthenticationClient authenticationClient = new AuthenticationClient())
            {
                await authenticationClient.UsernamePasswordAsync(
                    SalesforceService.GetAppSetting("SalesforceConsumerKey"),
                    SalesforceService.GetAppSetting("SalesforceConsumerSecret"),
                    SalesforceService.GetAppSetting("SalesforceUserName"),
                    SalesforceService.GetAppSetting("SalesforcePassword") + SalesforceService.GetAppSetting("SalesforceSecurityToken", true),
                    SalesforceService.GetAppSetting("SalesforceDomain") + "/services/oauth2/token");

                return(new ForceClient(
                           authenticationClient.InstanceUrl,
                           authenticationClient.AccessToken,
                           authenticationClient.ApiVersion));
            }
        }
コード例 #29
0
        public async void Upsert_New_CheckReturnInclude()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());

            var account = new Account {
                Name = "New Account" + DateTime.Now.Ticks, Description = "New Account Description" + DateTime.Now.Ticks
            };
            var response = await serviceHttpClient.HttpPatchAsync(account, string.Format("sobjects/{0}/{1}/{2}", "Account", "ExternalID__c", DateTime.Now.Ticks));

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.id);
        }
コード例 #30
0
        private async void btnRefreshToken_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var auth = new AuthenticationClient();
                await auth.TokenRefreshAsync(ConsumerKey, _token.RefreshToken);

                var message = string.Format("Token Refresh Successful:\n\nAccess Token: {0}\n\nInstance URL: {1}",
                                            auth.AccessToken, auth.InstanceUrl);

                lblOutput.Text = message;
            }
            catch (ForceException ex)
            {
                lblOutput.Text = ex.Message;
            }
        }
コード例 #31
0
        protected virtual async Task <ForceClient> GetClientAsync()
        {
            if (_client == null)
            {
                var auth = new AuthenticationClient();
                var url  = _settings.IsSandboxUser
                    ? "https://test.salesforce.com/services/oauth2/Token"
                    : "https://login.salesforce.com/services/oauth2/token";

                //This is a real turd of a method - complete with async you cant do, a ConfigureAwait(dont save my context bro)
                // and weird json serialization errors or "InvalidGrant" instead of just saying "bad password".
                await auth.UsernamePasswordAsync(_settings.ConsumerKey, _settings.ConsumerSecret, _settings.UserName, _settings.Password, url).ConfigureAwait(false);

                _client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            }
            return(_client);
        }
コード例 #32
0
        public Register()
        {
            InitializeComponent();
            DataContext           = this;
            _authenticationClient = new AuthenticationClient();
            _userClient           = new UserClient();
            _profileImage         = null;
            ImageBrush profileButtonBackground = new ImageBrush();

            profileButtonBackground.ImageSource = new BitmapImage(new Uri(Properties.Settings.Default.ProfileImageDirectory + Properties.Settings.Default.DefaultProfileImage, UriKind.Absolute));
            ProfileButton.Background            = profileButtonBackground;

            _invalidTextBoxStyle     = FindResource("InvalidTextBox") as Style;
            _validTextBoxStyle       = FindResource("DefaultTextBox") as Style;
            _validPasswordBoxStyle   = FindResource("DefaultPasswordBox") as Style;
            _invalidPasswordBoxStyle = FindResource("InvalidPasswordBox") as Style;
        }
コード例 #33
0
        public async Task <ForceClient> GetForceClient(string proxyUrl = null)
        {
            System.Net.Http.HttpClient proxyClient = null;

            if (!string.IsNullOrEmpty(proxyUrl))
            {
                proxyClient = HttpClientFactory.CreateHttpClient(true, proxyUrl);
            }

            AuthenticationClient auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(AuthInfo.ClientId, AuthInfo.ClientSecret,
                                             AuthInfo.Username, AuthInfo.Password, AuthInfo.TokenRequestEndpoint);

            ForceClient client = new ForceClient(auth.AccessInfo.InstanceUrl, auth.ApiVersion, auth.AccessInfo.AccessToken, proxyClient);

            return(client);
        }
コード例 #34
0
        public TVDBClient(
            HttpClient client, IOptions <TVDBClientOptions> options, TVDBContext context)
        {
            if (!options.Value.ShareContextBetweenClients)
            {
                // If we don't want to share the context, we are creating one just for this client
                context = new TVDBContext();
            }

            Series         = new SeriesClient(client, options, context);
            Search         = new SearchClient(client, options, context);
            Episodes       = new EpisodesClient(client, options, context);
            Updates        = new UpdatesClient(client, options, context);
            Languages      = new LanguagesClient(client, options, context);
            Users          = new UsersClient(client, options, context);
            Authentication = new AuthenticationClient(client, options, context);
        }
コード例 #35
0
        public void InitAuth_organisationalTransaction_success()
        {
            AuthenticationClient authenticationClient = AuthenticationClient.Create(SslSettings.Create(TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.KEYSTORE_PATH_PKCS12), TestKeystoreUtil.KEYSTORE_PASSWORD, TestKeystoreUtil.GetKeystorePath(TestKeystoreUtil.CERTIFICATE_PATH)), FrejaEnvironment.TEST)
                                                        .SetTestModeCustomUrl(CUSTOM_URL).SetTransactionContext(TransactionContext.ORGANISATIONAL).Build <AuthenticationClient>();
            InitiateAuthenticationRequest initAuthenticationRequestWithRequestedAttributesUserInfoOrganisationId = InitiateAuthenticationRequest.CreateCustom()
                                                                                                                   .SetOrganisationId(ORGANISATION_ID)
                                                                                                                   .SetAttributesToReturn(AttributeToReturn.BASIC_USER_INFO, AttributeToReturn.EMAIL_ADDRESS, AttributeToReturn.SSN, AttributeToReturn.CUSTOM_IDENTIFIER, AttributeToReturn.INTEGRATOR_SPECIFIC_USER_ID, AttributeToReturn.ORGANISATION_ID_IDENTIFIER)
                                                                                                                   .Build();

            String initAuthResponseString = jsonService.SerializeToJson(initiateAuthenticationResponse);

            StartMockServer(initAuthenticationRequestWithRequestedAttributesUserInfoOrganisationId, (int)HttpStatusCode.OK, initAuthResponseString);
            String reference = authenticationClient.Initiate(initAuthenticationRequestWithRequestedAttributesUserInfoOrganisationId);

            StopServer();
            Assert.AreEqual(REFERENCE, reference);
        }
コード例 #36
0
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password))
            {
                _consumerKey    = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username       = Environment.GetEnvironmentVariable("Username");
                _password       = Environment.GetEnvironmentVariable("Password");
            }

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, TokenRequestEndpointUrl).Wait();

            const string apiVersion = "v34.0";

            _chatterClient = new ChatterClient(_auth.InstanceUrl, _auth.AccessToken, apiVersion);
        }
コード例 #37
0
        internal async Task <ForceClient> GetClientForWebJob()
        {
            var consumerkey    = ConfigurationManager.AppSettings["ConsumerKey"];
            var consumersecret = ConfigurationManager.AppSettings["ConsumerSecret"];
            var user           = ConfigurationManager.AppSettings["User"];
            var password       = ConfigurationManager.AppSettings["Password"];


            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(consumerkey, consumersecret, user, password);

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            Console.WriteLine("Connected to Salesforce, apiVersion:" + auth.ApiVersion);

            return(client);
        }
コード例 #38
0
        /// <summary>
        /// Gets a Salesforce token from an authorization code and adds it to the cache.
        /// </summary>
        /// <param name="authorizationCode">The code that was returned to the OAuth callback.</param>
        /// <param name="redirectUri">The redirect URI that was used to acquire the code.</param>
        /// <returns>The asynchronous task.</returns>
        public static async Task AcquireTokenByAuthorizationCodeAsync(string authorizationCode, string redirectUri)
        {
            using (AuthenticationClient authenticationClient = new AuthenticationClient())
            {
                await authenticationClient.WebServerAsync(
                    SalesforceService.GetAppSetting("Salesforce:ConsumerKey"),
                    SalesforceService.GetAppSetting("Salesforce:ConsumerSecret"),
                    redirectUri,
                    authorizationCode,
                    SalesforceService.GetAppSetting("Salesforce:Domain") + "/services/oauth2/token");

                SalesforceToken salesforceToken = new SalesforceToken(authenticationClient);

                // Add the new token to the cache
                HttpContext.Current.Session[SalesforceService.TokenCacheKey] = salesforceToken;
            }
        }
コード例 #39
0
        public async void Post_UserInfo()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());
            var objectName        = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("access_token", auth.AccessToken)
            });

            var response = await serviceHttpClient.HttpPostAsync <UserInfo>(objectName, new Uri(auth.Id));

            Assert.IsNotNull(response);
        }
コード例 #40
0
        public void Execute()
        {
            try
            {
                lock (_lock)
                {
                    if (_shuttingDown)
                    {
                        return;
                    }

                    var auth = new AuthenticationClient();
                    auth.UsernamePasswordAsync(
                        "3MVG9Vik22TUgUpgCRwGDThV341ngTEs4NEwxdKpnnSgKQWWz8qdO.HuKgnMqmEYdhNkhCiQEPw6tZ87RyfRa",
                        "1880827973329100538",
                        "*****@*****.**",
                        "NogameNolife10" + "IQE5D5w03xW9MLWiJ6T15uoQr", "https://test.salesforce.com/services/oauth2/token").Wait();
                    var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                    //if (VerificarExistenciaContratoBanco())
                    //{
                    //    TodosContratos = ObterContratosSalesForce(client);
                    //}
                    //else
                    //{
                    TodosContratos = ObterTodosContratosSalesForce(client);
                    //}
                    foreach (var item in TodosContratos)
                    {
                        try
                        {
                            VerificarExistenciaContrato(item, client);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
            finally
            {
                // Always unregister the job when done.
                //HostingEnvironment.UnregisterObject(this);
            }
        }
コード例 #41
0
        public void Init()
        {
            if (string.IsNullOrEmpty(_consumerKey) && string.IsNullOrEmpty(_consumerSecret) && string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_password))
            {
                _consumerKey = Environment.GetEnvironmentVariable("ConsumerKey");
                _consumerSecret = Environment.GetEnvironmentVariable("ConsumerSecret");
                _username = Environment.GetEnvironmentVariable("Username");
                _password = Environment.GetEnvironmentVariable("Password");
            }

            // Use TLS 1.2 (instead of defaulting to 1.0)
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, TokenRequestEndpointUrl).Wait();
            
            _serviceHttpClient = new ServiceHttpClient(_auth.InstanceUrl, _auth.ApiVersion, _auth.AccessToken, new HttpClient());
        }
コード例 #42
0
        public ActionResult AccessRequest()
        {
            string code = TryParse(Request.QueryString["CODE"].ToString());
            AuthenticationClient client = new AuthenticationClient();
            OAuthToken oauthToken = null;
            try {
                oauthToken = client.Request(code, Server.UrlEncode(EnvironmentHelpers.GetConfigValue("CallBackUrl")), EnvironmentHelpers.GetConfigValue("ClientId"), EnvironmentHelpers.GetConfigValue("ClientSecret"));
            } catch (Exception ex) {  }

            if (oauthToken != null) {
                // set a cookie with the users access token?
                HttpCookie userCookie = new HttpCookie(COOKIE_ID);
                Response.Cookies.Remove(COOKIE_ID);
                Response.Cookies.Add(userCookie);
                userCookie.Values.Add("token", oauthToken.access_token);
                Response.Cookies[COOKIE_ID].Expires = DateTime.Now.AddYears(1);

                return RedirectToAction("Index", "Home");
            }

            return View(oauthToken);
        }
コード例 #43
0
 public void Update(AuthenticationClient entity)
 {
     AuthenticationClientRepository.Update(entity);
 }
コード例 #44
0
 public string Save(AuthenticationClient entity)
 {
     return AuthenticationClientRepository.Save(entity);
 }
コード例 #45
0
 public void Auth_HasApiVersion()
 {
     var auth = new AuthenticationClient();
     Assert.IsNotNullOrEmpty(auth.ApiVersion);
 }
コード例 #46
0
        public async void Auth_InvalidLogin()
        {
            const string userAgent = "common-libraries-dotnet";

            try
            {
                var auth = new AuthenticationClient();
                await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, "WRONGPASSWORD", userAgent, _tokenRequestEndpointUrl);
            }
            catch (ForceAuthException ex)
            {
                Assert.IsNotNull(ex);
                Assert.IsNotNull(ex.Message);
                Assert.IsNotNull(ex.Error);
            }
        }
コード例 #47
0
	    public async void BadTokenHandling()
	    {
            _auth = new AuthenticationClient();
            _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, TokenRequestEndpointUrl).Wait();

	        var badToken = "badtoken";
            var serviceHttpClient = new JsonHttpClient(_auth.InstanceUrl, _auth.ApiVersion, badToken, new HttpClient());

            const string query = "SELECT count() FROM Account";

	        try
	        {
                await serviceHttpClient.HttpGetAsync<QueryResult<dynamic>>(string.Format("query?q={0}", query));
	        }
            catch (ForceException ex)
            {
                Assert.IsNotNull(ex);
                Assert.IsNotNull(ex.Message);
                Assert.That(ex.Message, Is.EqualTo("Session expired or invalid"));
                Assert.IsNotNull(ex.Error);
            }
	    }
コード例 #48
0
        public void CheckWebAuthFlow()
        {
            var url = Common.FormatAuthorizeUrl(ResponseTypes.Code, _clientId, HttpUtility.UrlEncode(_callbackUrl));
            var expectedUrl = string.Format("https://login.uber.com/oauth/authorize?response_type=code&client_id={0}&redirect_uri={1}", _clientId, HttpUtility.UrlEncode(_callbackUrl));

            Assert.AreEqual(url, expectedUrl);

            var webClient = new WebClient(BrowserVersion.FIREFOX_17);

            webClient.Options.ThrowExceptionOnScriptError = false;

            webClient.Options.JavaScriptEnabled = true;
            webClient.Options.RedirectEnabled = true;
            webClient.Options.ActiveXNative = false;
            webClient.Options.CssEnabled = true; 

            // ########################################
            // # Uber login page
            // ########################################

            var loginPage = webClient.GetHtmlPage(url);
            Assert.IsNotNull(loginPage);

            var loginPageText = loginPage.AsText();

            StringAssert.Contains("sign in", loginPageText.toLowerCase());
            StringAssert.Contains("connect with facebook", loginPageText.toLowerCase());
            StringAssert.Contains("don't have an account", loginPageText.toLowerCase());
            StringAssert.Contains("email", loginPageText.toLowerCase());
            StringAssert.Contains("password", loginPageText.toLowerCase());

            var signInSpan = (HtmlSpan)loginPage.GetElementsByTagName("span")[0];
            Assert.AreEqual(signInSpan.AsText(), "Sign In");

            var emailInputElement = (HtmlTextInput)loginPage.GetElementByName("email");
            Assert.IsNotNull(emailInputElement, "email");

            emailInputElement.SetValueAttribute(_userName);
            Assert.AreEqual(emailInputElement.Text, _userName);

            var passwordInputElement = (HtmlPasswordInput)loginPage.GetElementByName("password");
            Assert.IsNotNull(passwordInputElement, "password");

            passwordInputElement.SetValueAttribute(_password);
            Assert.AreEqual(passwordInputElement.Text, _password);

            var loginForm = (HtmlForm)loginPage.GetElementsByTagName("form")[0];
            Assert.IsNotNull(loginForm);

            var loginFormText = loginForm.AsText();

            StringAssert.Contains("sign in", loginFormText.toLowerCase());
            StringAssert.Contains("connect with facebook", loginFormText.toLowerCase());
            StringAssert.Contains("email", loginFormText.toLowerCase());
            StringAssert.Contains("password", loginFormText.toLowerCase());

            var loginFormButtons = loginForm.GetElementsByTagName("button");
            Assert.IsNotNull(loginFormButtons);

            var loginButton = (HtmlButton)loginFormButtons.First();
            Assert.IsNotNull(loginButton);

            var loginButtonText = loginButton.AsText();
            StringAssert.Contains("sign in", loginButtonText.toLowerCase());

            // ########################################
            // # Uber consent page
            // ########################################

            var consentPage = (HtmlPage)loginButton.Click();
            Assert.IsNotNull(consentPage);

            IPage callbackPage;

            // check if previously consented
            if (!consentPage.Url.ToString().contains(string.Format("{0}?code=", _callbackUrl)))
            {
                var consentPageUrl = consentPage.Url.ToString();
                Assert.IsNotNullOrEmpty(consentPageUrl);

                var consentPageText = consentPage.AsText();
                StringAssert.Contains("access to your full name", consentPageText.toLowerCase());

                var consentPageButtons = consentPage.GetElementsByTagName("button");
                Assert.IsNotNull(consentPageButtons);

                var noAllowButton = (HtmlButton)consentPageButtons[0];
                Assert.IsNotNull(noAllowButton);
                Assert.AreEqual("Deny", noAllowButton.AsText());

                var allowButton = (HtmlButton)consentPageButtons[1];
                Assert.IsNotNull(allowButton);
                Assert.AreEqual("Allow", allowButton.AsText());

                callbackPage = allowButton.Click();
                Assert.IsNotNull(callbackPage);
            }
            else
            {
                callbackPage = consentPage;
            }

            // ########################################
            // # Callback page
            // ########################################
            
            var page3Url = callbackPage.Url.ToString();
            Assert.IsNotNullOrEmpty(page3Url);
            StringAssert.Contains(string.Format("{0}?code=", _callbackUrl), page3Url);

            var queryCollection = HttpUtility.ParseQueryString(page3Url);
            var code = queryCollection[0];

            var auth = new AuthenticationClient();
            auth.WebServerAsync(_clientId, _clientSecret, _callbackUrl, code).Wait();

            Assert.IsNotNull(auth);
            Assert.IsNotNullOrEmpty(auth.AccessToken);
        }
コード例 #49
0
        public async void Auth_UsernamePassword_HasInstanceUrl()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            Assert.IsNotNullOrEmpty(auth.InstanceUrl);
        }
コード例 #50
0
 public SalesforceManager(ISalesforceApiConfig salesforceApiConfig)
 {
     this.salesforceApiConfig = salesforceApiConfig;
     this.auth = new AuthenticationClient();
 }
コード例 #51
0
 public void Auth_HasApiVersion()
 {
     var auth = new AuthenticationClient();
     Assert.That(auth.ApiVersion, Is.Not.Null.And.Not.Empty);
 }
コード例 #52
0
        static void Main(string[] args)
        {
            // Generate auth token to use for SalesLogix service.
            var lAuthClient = new AuthenticationClient();
            var lAuthResponse = lAuthClient.Authenticate(new AuthenticationEntitiesAuthenticationRequest
            {
                Username = ConfigurationManager.AppSettings["username"],
                Password = ConfigurationManager.AppSettings["password"]
            });
            if (lAuthResponse.Status != ResponseStatus.Success)
            {
                throw new AuthenticationException("Unable to authenticate");
            }
            var lToken = lAuthResponse.Token;

            var lSalesLogixClientService = new SalesLogixClient();
            lSalesLogixClientService.Endpoint.Binding.ReceiveTimeout = new TimeSpan(30, 0, 0);
            lSalesLogixClientService.Endpoint.Binding.SendTimeout = new TimeSpan(30, 0, 0);
            // Inject token into the service for each request.
            lSalesLogixClientService.Endpoint.Behaviors.Add(
                new ClientMessageInspector
                {
                    AuthToken = lToken
                }
            );

            // Note: All fields present below are required to submit.
            var lResponse = lSalesLogixClientService.CreateLead(
                new CreateLeadEntitiesCreateLeadRequest
                {
                    LeadSource = new CreateLeadEntitiesLeadSource
                    {
                        BrandAssociation = CreateLeadEntitiesBrandAssociation.Floream,
                        CampaignCode = "IDMCVF0016" // This is a leadsource and might change.
                    },
                    CourseInterests = new []{ "AAA" }, // Course code that the user enquired about
                    Contacts = new []
                    {
                        new Contact
                        {
                            Type = ContactType.Lead,
                            FirstName = "Joe",
                            LastName = "Doe",
                            Email = "*****@*****.**",
                            HomeTelephone = "02086766255", // Mobile and work number properties exist as well
                            Reference = "Your unique reference" // Reference in your database
                        }
                    },
                    Questions = new CreateLeadEntitiesQuestions
                    {
                        PayForCourse = CreateLeadEntitiesPlanToPay.Employer, // If the user's employer will sponsor them
                        EnrolmentExpectation = DateTime.UtcNow.AddMonths(6), // The user wishes to enrol is six months time
                    }
                }
            );

            if (lResponse.Status == FloreamSaleslogixApi.ResponseStatus.Success)
            {
                Console.WriteLine("Lead created!");
                Console.WriteLine(lResponse.Contacts.First().Identifier); // If one contact is created, contact in response should exist.
            }
            else
            {
                // Always look at message details for extra information.
                Console.WriteLine(lResponse.Message);
                if (lResponse.MessageDetails == null || lResponse.MessageDetails.Length <= 0) return;

                foreach (var lMessage in lResponse.MessageDetails)
                {
                    Console.WriteLine("- {0}", lMessage.Message);
                }
            }

            Console.ReadLine();
        }
コード例 #53
0
 /// <summary>
 /// </summary>
 /// <param name="entity"></param>
 public void Update(AuthenticationClient entity)
 {
     CurrentSession.Update(entity);
 }
コード例 #54
0
        public async void Upsert_New_CheckReturnInclude()
        {
            const string userAgent = "common-libraries-dotnet";

            var auth = new AuthenticationClient();
            await auth.UsernamePasswordAsync(_consumerKey, _consumerSecret, _username, _password, userAgent, _tokenRequestEndpointUrl);

            var serviceHttpClient = new ServiceHttpClient(auth.InstanceUrl, auth.ApiVersion, auth.AccessToken, userAgent, new HttpClient());

            var account = new Account { Name = "New Account" + DateTime.Now.Ticks, Description = "New Account Description" + DateTime.Now.Ticks };
            var response = await serviceHttpClient.HttpPatchAsync(account, string.Format("sobjects/{0}/{1}/{2}", "Account", "ExternalID__c", DateTime.Now.Ticks));

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.id);
        }
コード例 #55
0
 /// <summary>
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 public string Save(AuthenticationClient entity)
 {
     return (string) CurrentSession.Save(entity);
 }