Beispiel #1
0
        public void BasicAuthSetCredentialsTest()
        {
            TargetUri           targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-set");

            Credential credentials = null;

            Assert.IsFalse(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly retrieved.");
            try
            {
                basicAuth.SetCredentials(targetUri, credentials);
                Assert.Fail("User credentials were unexpectedly set.");
            }
            catch { }

            credentials = new Credential("username", "password");

            Assert.IsTrue(basicAuth.SetCredentials(targetUri, credentials), "User credentials were unexpectedly not set.");
            Assert.IsTrue(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly not retrieved.");
        }
Beispiel #2
0
        public void BasicAuthentication_GetCredentials_NonDesktopSession_Resource_UserPassPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var context = new TestCommandContext {
                SessionManager = { IsDesktopSession = false }
            };

            context.Terminal.Prompts["Username"]       = testUserName;
            context.Terminal.SecretPrompts["Password"] = testPassword; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource);

            Assert.Equal(testUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
Beispiel #3
0
        public List <ItemDescriptor> GetFileList(BasicAuthentication authentication, string project, string repo, string branch, string rootPath, string fileExtension, bool fullRecursion)
        {
            var restHttpClient = new RestHttpClient();
            var url            = $"{authentication.AccountUrl}/{project}/_apis/git/repositories/{repo}/items?api-version=1.0&recursionLevel={(fullRecursion ? "Full" : "1")}&versionType=branch&version={branch}&scopePath={rootPath}";
            var itemList       = new List <ItemDescriptor>();

            using (var response = restHttpClient.GetAsync <CollectionResult <ItemDescriptor> >(authentication, url))
            {
                if (response.Result.Value.Count > 0)
                {
                    foreach (var itemDescriptor in response.Result.Value)
                    {
                        if (!itemDescriptor.IsFolder && itemDescriptor.Path.EndsWith(fileExtension, System.StringComparison.InvariantCultureIgnoreCase))
                        {
                            itemList.Add(itemDescriptor);
                        }
                    }
                }
            }

            return(itemList);
        }
        public async Task ImportDataFromCsvAsync(string importUri, string fileToUpload, string username, string password)
        {
            using (FileStream fileStream = new FileStream(fileToUpload, FileMode.Open))
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create($"{Client.BaseUrl}{importUri}/data");
                httpWebRequest.Method                    = "POST";
                httpWebRequest.ContentLength             = fileStream.Length;
                httpWebRequest.ContentType               = "text/csv";
                httpWebRequest.AllowWriteStreamBuffering = true;
                httpWebRequest.Headers.Add("Authorization", BasicAuthentication.BuildAuthHeader(username, password));

                using (Stream reqStream = await httpWebRequest.GetRequestStreamAsync())
                {
                    byte[] inData = new byte[fileStream.Length];

                    reqStream.Write(inData, 0, (int)fileStream.Length);

                    fileStream.Close();
                    await httpWebRequest.GetResponseAsync();
                }
            }
        }
Beispiel #5
0
        public void ImportDataFromCsv(string importUri, string fileToUpload, string username, string password)
        {
            using (FileStream rdr = new FileStream(fileToUpload, FileMode.Open))
            {
                var req = (HttpWebRequest)WebRequest.Create(_client.Client.BaseUrl + importUri + "/data");
                req.Method                    = "POST";
                req.ContentLength             = rdr.Length;
                req.ContentType               = "text/csv";
                req.AllowWriteStreamBuffering = true;
                req.Headers.Add("Authorization", BasicAuthentication.BuildAuthHeader(username, password));

                using (Stream reqStream = req.GetRequestStream())
                {
                    byte[] inData = new byte[rdr.Length];

                    reqStream.Write(inData, 0, (int)rdr.Length);

                    rdr.Close();
                    req.GetResponse();
                }
            }
        }
Beispiel #6
0
        public IActionResult Dungeon(int level, int startX, int startY, string direction)
        {
            if (!BasicAuthentication.Authenticate(Secrets, Request))
            {
                return(new UnauthorizedResult());
            }

            Direction start = Direction.NoDir;

            switch (direction)
            {
            case "U":
                start = Direction.Up;
                break;

            case "D":
                start = Direction.Down;
                break;

            case "L":
                start = Direction.Left;
                break;

            case "R":
                start = Direction.Right;
                break;

            default:
                break;
            }

            Dungeon       dungeon = new Dungeon(level, startX, startY, start);
            StringBuilder output  = new StringBuilder();

            output.AppendLine(dungeon.VisualizeAsText(false, false));
            output.AppendLine(dungeon.BuildStats() + Environment.NewLine);

            return(new ObjectResult(output.ToString()));
        }
        public void Post_request_hook_should_return_a_challenge_on_a_nonajax_request_when_set_to_nonajax()
        {
            // Given
            var config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm", UserPromptBehaviour.NonAjax);
            var hooks  = new Pipelines();

            BasicAuthentication.Enable(hooks, config);

            var context = new NancyContext()
            {
                Request = new FakeRequest("GET", "/")
            };

            context.Response = new Response {
                StatusCode = HttpStatusCode.Unauthorized
            };

            // When
            hooks.AfterRequest.Invoke(context, new CancellationToken());

            // Then
            context.Response.Headers.ContainsKey("WWW-Authenticate").ShouldBeTrue();
        }
        public void Should_set_user_in_context_with_valid_username_in_auth_header()
        {
            // Given
            var fakePipelines = new Pipelines();

            var validator = A.Fake <IUserValidator>();
            var fakeUser  = A.Fake <ClaimsPrincipal>();

            A.CallTo(() => validator.Validate("foo", "bar")).Returns(fakeUser);

            var cfg = new BasicAuthenticationConfiguration(validator, "realm");

            var context = CreateContextWithHeader(
                "Authorization", new [] { "Basic" + " " + EncodeCredentials("foo", "bar") });

            BasicAuthentication.Enable(fakePipelines, cfg);

            // When
            fakePipelines.BeforeRequest.Invoke(context, new CancellationToken());

            // Then
            context.CurrentUser.ShouldBeSameAs(fakeUser);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // BasicAuthentication auth = new BasicAuthentication();
            var decryptedUserName = Logindecryption.DecryptStringAES(context.UserName);

            var decryptedPassword = Logindecryption.DecryptStringAES(context.Password);

            bool user = BasicAuthentication.IsAuthorizedUser(decryptedUserName, decryptedPassword);

            if (user)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                //  identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRoles));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                // identity.AddClaim(new Claim("Email", user.UserEmailID));
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
Beispiel #10
0
        /// <summary>
        /// Returns the object ID for the specified branch.
        /// </summary>
        /// <param name="authentication"></param>
        /// <param name="project"></param>
        /// <param name="repo"></param>
        /// <param name="branch"></param>
        /// <returns></returns>
        public string GetBranchObjectId(BasicAuthentication authentication, string project, string repo, string branch)
        {
            var restHttpClient = new RestHttpClient();
            var url            = $"{authentication.AccountUrl}/{project}/_apis/git/repositories/{repo}/refs/heads/{branch}?api-version=1.0";
            var objectId       = string.Empty;

            using (var response = restHttpClient.GetAsync <CollectionResult <Ref> >(authentication, url))
            {
                if (response.Result.Value.Count > 0)
                {
                    foreach (var branchItem in response.Result.Value)
                    {
                        if (branchItem.name.Equals($"refs/heads/{branch}", System.StringComparison.InvariantCultureIgnoreCase))
                        {
                            objectId = branchItem.objectId;
                            break;
                        }
                    }
                }
            }

            return(objectId);
        }
        public static IHandlerBuilder Create()
        {
            var auth = BasicAuthentication.Create(AccessControl.AuthenticateAsync);

            var resources = Resources.From(ResourceTree.FromAssembly("Resources"));

            var logo = Content.From(Resource.FromAssembly("eye.png"));

            var theme = Theme.Create()
                        .Title("Blickkontakt")
                        .FooterRight(RenderFooterRight)
                        .UserProfile(RenderUser)
                        .Logo(logo);

            var content = Layout.Create()
                          .Fallback(Controller.From <DashboardController>())
                          .AddController <CustomerController>("customers")
                          .AddController <AnnounceController>("announces")
                          .AddController <LetterController>("letters")
                          .AddController <AccountController>("accounts")
                          .Add("static", resources)
                          .Authentication(auth);

            var menu = Menu.Empty()
                       .Add("{website}", "Übersicht")
                       .Add("/customers/", "Kunden")
                       .Add("/announces/", "Anzeigen")
                       .Add("/letters/", "Infobriefe")
                       .Add("/accounts/", "Mitarbeiter");

            return(Website.Create()
                   .Theme(theme)
                   .Content(content)
                   .Menu(menu)
                   .AddScript("jquery-validate.js", Resource.FromAssembly("jquery.validate.min.js"))
                   .AddStyle("project.css", Resource.FromAssembly("project.css")));
        }
Beispiel #12
0
        internal void SetHeaders(string authorizationType, string headerParameters)
        {
            string rawHeaderParameters = headerParameters.Replace(" And ", ",");
            var    arrayHeaders        = rawHeaderParameters.Split(',');

            if (authorizationType.Equals("jwt", StringComparison.InvariantCultureIgnoreCase))
            {
                string authority = TestContext.Properties["Parameter:authority"].ToString();
                string brand     = TestContext.Properties["Parameter:brand"].ToString();
                string uid       = TestContext.Properties["Parameter:customeruid"].ToString();
                RequestParameters.SetHeaders(_authHeader, JsonWebToken.GetJsonWebToken(authority, brand, uid));
            }
            else if (authorizationType.Equals("basic", StringComparison.InvariantCultureIgnoreCase))
            {
                string clientId          = TestContext.Properties["Parameter:clientid"].ToString();
                string clientSecret      = TestContext.Properties["Parameter:clientsecret"].ToString();
                string encodedAuthString = BasicAuthentication.GetBasicAuthString(clientId, clientSecret);
                RequestParameters.SetHeaders(_authHeader, "Basic " + encodedAuthString);
            }

            foreach (var authorizationParameter in arrayHeaders)
            {
                try
                {
                    var parameterValue = TestContext.Properties["Parameter:" + authorizationParameter].ToString();
                    if (parameterValue != null)
                    {
                        RequestParameters.SetHeaders(authorizationParameter, parameterValue);
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }
            RequestParameters.SetHeaders("x-transaction-id", Helper.GenerateTransactionId());
        }
        public string DownloadRepositoryFromGit()
        {
            Credential credentialsInfo =
                new BasicAuthentication(new SecretStore("git")).GetCredentials(new TargetUri("https://github.com"));

            if (!Repository.IsValid(_localStoragePath))
            {
                var options = new CloneOptions();
                options.CredentialsProvider = (_url, usernameFromUrl, types) => new UsernamePasswordCredentials
                {
                    Username = credentialsInfo.Username,
                    Password = credentialsInfo.Password
                };
                Repository.Clone(_url, _localStoragePath, options);
            }
            else
            {
                var repository = new Repository(_localStoragePath);
                var options    = new PullOptions();

                options.FetchOptions = new FetchOptions();
                options
                .FetchOptions
                .CredentialsProvider = (_url, usernameFromUrl, types) => new UsernamePasswordCredentials
                {
                    Username = credentialsInfo.Username,
                    Password = credentialsInfo.Password
                };

                var signature = new Signature(
                    new Identity($"{credentialsInfo.Username}", $"{_data.Email}"), DateTimeOffset.Now);

                Commands.Pull(repository, signature, options);
            }

            return(_localStoragePath);
        }
Beispiel #14
0
        public IIdentity Authenticate(
            IncomingWebRequestContext request,
            OutgoingWebResponseContext response,
            object[] parameters,
            Type validatorType,
            bool secure,
            bool requiresTransportLayerSecurity,
            string source)
        {
            if (requiresTransportLayerSecurity && !secure)
            {
                throw new BasicRequiresTransportSecurityException();
            }
            var authentication = new BasicAuthentication(request.Headers);
            var validator      = validatorType != null
                ? DependencyResolver.Current.GetOperationService <UserNamePasswordValidator>(OperationContainer.GetCurrent(), validatorType)
                : DependencyResolver.Current.GetOperationService <UserNamePasswordValidator>(OperationContainer.GetCurrent()).ThrowIfNull();

            if (!authentication.Authenticate(validator))
            {
                throw new BasicUnauthorizedException(source);
            }
            return(new GenericIdentity(authentication.Username, "WebBasicAuthenticationHandler"));
        }
        static IDictionary <string, string> GetReferences(IRepository repo, string remoteName)
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            CredentialsHandler credentialsHandler =
                (url, user, cred) => new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password
            };

            var dictionary = new Dictionary <string, string>();
            var remote     = repo.Network.Remotes[remoteName];
            var refs       = repo.Network.ListReferences(remote, credentialsHandler);

            foreach (var reference in refs)
            {
                dictionary[reference.CanonicalName] = reference.TargetIdentifier;
            }

            return(dictionary);
        }
        static CredentialsHandler CreateCredentialsHandler(IRepository repo, string remoteName)
        {
            CredentialsHandler retval = null;

            var remote    = repo.Network.Remotes[remoteName];
            var remoteUri = new Uri(remote.Url);

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);

            var targetUrl = remoteUri.GetLeftPart(UriPartial.Authority);

            //HACK ALERT!! to make this thing play nice with Windows Credentials and how it stores my PATs. YMMV
            if (targetUrl.Contains("dev.azure.com", StringComparison.OrdinalIgnoreCase))
            {
                var url = new Uri(targetUrl);
                if (!string.IsNullOrWhiteSpace(url.UserInfo))
                {
                    targetUrl = url + url.UserInfo;
                }
            }
            //End HACK ALERT!!

            var creds = auth.GetCredentials(new TargetUri(targetUrl));

            if (creds != null)
            {
                retval = (url, user, cred) => new UsernamePasswordCredentials
                {
                    Username = creds.Username,
                    Password = creds.Password
                };
            }

            return(retval);
        }
        public Authentication_UnitTests()
        {
            _authSettings = new AuthenticationSettings()
            {
                EnvClientID     = "MOCK_CLIENTID",
                EnvUserName     = "******",
                EnvUserPassword = "******",
                EnvClientSecret = "MOCK_CLIENTSECRET",
                Note            = "MockNote",
                OAuth2Endpoint  = "http://mock/",
                Scopes          = new List <string>()
                {
                    "mock_scope"
                }
            };

            Environment.SetEnvironmentVariable("MOCK_CLIENTID", "mockClientId");
            Environment.SetEnvironmentVariable("MOCK_USERNAME", "mockUsername");
            Environment.SetEnvironmentVariable("MOCK_USERPASS", "mockPassword");
            Environment.SetEnvironmentVariable("MOCK_CLIENTSECRET", "mockClientSecret");

            _basicAuth  = new BasicAuthentication(_authSettings);
            _oauth2Auth = new OAuth2Authentication(_authSettings);
        }
Beispiel #18
0
        public HttpWebResponseWrapper GetHttpWebResponseForWebServerVuln(string host, BasicAuthentication basicAuthentication,
                                                                         ref List <Param> respHeader, string customRequestHeader, string httpMethodName)
        {
            HttpWebResponseWrapper resp = null;

            HttpWebRequest  wr   = GetHttpWebReqForWebServerVuln(host, basicAuthentication, customRequestHeader, httpMethodName);
            HttpWebResponse wres = null;

            try
            {
                wres = (HttpWebResponse)wr.GetResponse();
            }
            catch (Exception wex)
            {
                throw wex;
            }

            if (wres != null)
            {
                SetHeader(wres, ref respHeader);

                StreamReader streamReader = new StreamReader(wres.GetResponseStream());

                resp              = new HttpWebResponseWrapper();
                resp.WebResponse  = wres;
                resp.ResponseBody = streamReader.ReadToEnd();
            }

            return(resp);
        }
Beispiel #19
0
        private void LogInButton_Click(object sender, EventArgs e)
        {
            gitHubCredentials = new UsernamePasswordCredentials()
            {
                Username = gitHubUsernameTextBox.Text,
                Password = gitHubPasswordTextBox.Text
            };


            // Setup GitHub authentication
            SecretStore         gitSecretStore   = new SecretStore("git");
            BasicAuthentication authType         = new BasicAuthentication(gitSecretStore);
            Credential          userCredentials  = authType.GetCredentials(new TargetUri("https://github.com"));
            CloneOptions        credCloneOptions = new CloneOptions
            {
                OnTransferProgress = cloneProgress =>
                {
                    var clonePercentage = (100 * cloneProgress.ReceivedObjects) / cloneProgress.TotalObjects;
                    cloneProgressBar.Invoke(new Action(() => cloneProgressBar.Value = clonePercentage));
                    return(true);
                },
                CredentialsProvider = (_url, _user, _cred) => gitHubCredentials,
            };

            // Try to authenticate, notify the user if there's an error
            try
            {
                // Clone the repo and close the form
                // We also want to nullify all credential objects to respect the user's privacy
                // This should make the memory "out of scope" in the eyes of the garbage collector

                // Extract the repo name from the URL, then combine it with the path to make the full path
                string[] repoSplit    = projectURL.Trim().Split('/');
                string   repoName     = repoSplit[repoSplit.Length - 1].Split('.')[0];
                string   combinedPath = Path.Combine(pathToClone, repoName);


                Repository.Clone(projectURL, combinedPath, credCloneOptions);

                userCredentials  = null;
                credCloneOptions = null;

                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Repository cloned successfully! Closing login form.", "Cloned Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                })).Start();

                this.Close();
            }
            catch (LibGit2Sharp.NameConflictException)
            {
                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Failed to clone the repo. Directory already exists with that name.", "Cloning Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                })).Start();
            }
            catch (LibGit2Sharp.LibGit2SharpException)
            {
                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Failed to clone the repo. Please check your internet connection or credentials.", "Cloning Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                })).Start();
            }
        }
Beispiel #20
0
 public MembershipAuthentication(IAuthenticationSession session, IPrincipalContext context, IMembershipRepository membership, ILockedOutRule lockedOutRule)
 {
     _membership = membership;
     _inner      = new BasicAuthentication(session, context, this, this, lockedOutRule);
 }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm", UserPromptBehaviour.Always);
     this.hooks  = new Pipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
Beispiel #22
0
        /// <summary>
        /// Get Http job authentication.
        /// </summary>
        /// <param name="authenticationParams">Http authentication properties specified via PowerShell.</param>
        /// <returns>HttpAuthentication object.</returns>
        private HttpAuthentication PopulateHttpAuthentication(PSHttpJobAuthenticationParams authenticationParams)
        {
            if (authenticationParams == null ||
                authenticationParams.HttpAuthType == null ||
                authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationNone, StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationClientCertificate, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.ClientCertPfx) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientCertPassword))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidClientCertAuthRequest);
                }

                var clientCert = new ClientCertAuthentication()
                {
                    Type     = HttpAuthenticationType.ClientCertificate,
                    Pfx      = authenticationParams.ClientCertPfx,
                    Password = authenticationParams.ClientCertPassword
                };

                return(clientCert);
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationActiveDirectoryOAuth, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.Tenant) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientId) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Secret) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Audience))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidActiveDirectoryOAuthRequest);
                }

                var adOAuth = new OAuthAuthentication()
                {
                    Type     = HttpAuthenticationType.ActiveDirectoryOAuth,
                    Audience = authenticationParams.Audience,
                    ClientId = authenticationParams.ClientId,
                    Secret   = authenticationParams.Secret,
                    Tenant   = authenticationParams.Tenant
                };

                return(adOAuth);
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationBasic, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.Username) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Password))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidBasicRequest);
                }

                var basic = new BasicAuthentication()
                {
                    Type     = HttpAuthenticationType.Basic,
                    Username = authenticationParams.Username,
                    Password = authenticationParams.Password
                };

                return(basic);
            }
            else
            {
                throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidAuthenticationType);
            }
        }
        /**
         * [[cloud-connection-pool]]
         * ==== CloudConnectionPool
         *
         * A specialized subclass of `SingleNodeConnectionPool` that accepts a Cloud Id and credentials.
         * When used the client will also pick Elastic Cloud optimized defaults for the connection settings.
         *
         * A Cloud Id for your cluster can be fetched from your Elastic Cloud cluster administration console.
         *
         * A Cloud Id should be in the form of `cluster_name:base_64_data` where `base_64_data` are the UUIDs for the services in this cloud instance e.g
         *
         * `host_name$elasticsearch_uuid$kibana_uuid$apm_uuid`
         *
         * Out of these, only `host_name` and `elasticsearch_uuid` are always available.
         *
         */
        [U] public void CloudConnectionPool()
        {
            // hide
            string ToBase64(string s) => Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

            // hide
            var hostName = "cloud-endpoint.example";
            // hide
            var elasticsearchUuid = "3dadf823f05388497ea684236d918a1a";
            // hide
            var services = $"{hostName}${elasticsearchUuid}$3f26e1609cf54a0f80137a80de560da4";
            // hide
            var cloudId = $"my_cluster:{ToBase64(services)}";

            /**
             * A cloud connection pool can be created using credentials and a `cloudId`
             */
            var credentials = new BasicAuthentication("username", "password");    // <1> a username and password that can access Elasticsearch service on Elastic Cloud
            var pool        = new CloudConnectionPool(cloudId, credentials);      // <2> `cloudId` is a value that can be retrieved from the Elastic Cloud web console
            var client      = new ElasticClient(new ConnectionSettings(pool));

            // hide
            {
                pool.UsingSsl.Should().BeTrue();
                pool.Nodes.Should().HaveCount(1);
                var node = pool.Nodes.First();
                node.Uri.Port.Should().Be(443);
                node.Uri.Host.Should().Be($"{elasticsearchUuid}.{hostName}");
                node.Uri.Scheme.Should().Be("https");
            }

            /** This type of pool, like its parent the `SingleNodeConnectionPool`, is hardwired to opt out of
             * reseeding (<<sniffing-behaviour, sniffing>>) as well as <<pinging-behaviour, pinging>>.
             */
            // hide
            {
                pool.SupportsReseeding.Should().BeFalse();
                pool.SupportsPinging.Should().BeFalse();
            }

            /**
             * You can also directly create a cloud enabled connection using the `ElasticClient`'s constructor
             */
            client = new ElasticClient(cloudId, credentials);

            // hide
            {
                client.ConnectionSettings.ConnectionPool
                .Should()
                .BeOfType <CloudConnectionPool>();
            }

            // hide
            {
                client = new ElasticClient(new ConnectionSettings(pool));
                client.ConnectionSettings.ConnectionPool.Should().BeOfType <CloudConnectionPool>();
                client.ConnectionSettings.EnableHttpCompression.Should().BeTrue();
                var c = client.ConnectionSettings.Authentication.Should().NotBeNull().And.BeOfType <BasicAuthentication>();
                c.Subject.Header.Should().NotBeNullOrEmpty();
            }

            //hide
            {
                //make sure we can deal with trailing dollar sign separators.
                foreach (var dollars in Enumerable.Range(0, 5).Select(i => new string('$', i)))
                {
                    Func <IElasticClient> doesNotThrowWhenEndsWithDollar = () =>
                                                                           new ElasticClient($"my_cluster:{ToBase64($"hostname$guid{dollars}")}", credentials);

                    var validClient = doesNotThrowWhenEndsWithDollar.Should().NotThrow().Subject;
                    validClient.ConnectionSettings.ConnectionPool.Nodes.First().Uri.Should().Be("https://guid.hostname");
                }

                var badCloudIds = new[]
                {
                    "",
                    "my_cluster",
                    "my_cluster:",
                    $"my_cluster:{ToBase64("hostname")}",
                    $"my_cluster:{ToBase64("hostname$")}"
                };

                foreach (var id in badCloudIds)
                {
                    Action create = () => new ElasticClient(id, credentials);

                    create.Should()
                    .Throw <ArgumentException>()
                    .And.Message.Should()
                    .Contain("should be a string in the form of cluster_name:base_64_data");
                }
            }
        }
        public static Credential QueryCredentials(Program program, OperationArguments operationArguments)
        {
            if (ReferenceEquals(operationArguments, null))
            {
                throw new ArgumentNullException(nameof(operationArguments));
            }
            if (ReferenceEquals(operationArguments.TargetUri, null))
            {
                throw new ArgumentException("TargetUri property returned null", nameof(operationArguments));
            }

            var task = Task.Run(async() => { return(await program.CreateAuthentication(operationArguments)); });
            BaseAuthentication authentication = task.Result;
            Credential         credentials    = null;

            switch (operationArguments.Authority)
            {
            default:
            case AuthorityType.Basic:
            {
                BasicAuthentication basicAuth = authentication as BasicAuthentication;

                Task.Run(async() =>
                    {
                        // attempt to get cached creds or acquire creds if interactivity is allowed
                        if ((operationArguments.Interactivity != Interactivity.Always &&
                             (credentials = authentication.GetCredentials(operationArguments.TargetUri)) != null) ||
                            (operationArguments.Interactivity != Interactivity.Never &&
                             (credentials = await basicAuth.AcquireCredentials(operationArguments.TargetUri)) != null))
                        {
                            Git.Trace.WriteLine("credentials found.");
                            // no need to save the credentials explicitly, as Git will call back with
                            // a store command if the credentials are valid.
                        }
                        else
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' not found.");
                            program.LogEvent($"Failed to retrieve credentials for '{operationArguments.TargetUri}'.", EventLogEntryType.FailureAudit);
                        }
                    }).Wait();
            }
            break;

            case AuthorityType.AzureDirectory:
            {
                VstsAadAuthentication aadAuth = authentication as VstsAadAuthentication;

                Task.Run(async() =>
                    {
                        // attempt to get cached creds -> non-interactive logon -> interactive
                        // logon note that AAD "credentials" are always scoped access tokens
                        if (((operationArguments.Interactivity != Interactivity.Always &&
                              ((credentials = aadAuth.GetCredentials(operationArguments.TargetUri)) != null) &&
                              (!operationArguments.ValidateCredentials ||
                               await aadAuth.ValidateCredentials(operationArguments.TargetUri, credentials)))) ||
                            (operationArguments.Interactivity != Interactivity.Always &&
                             ((credentials = await aadAuth.NoninteractiveLogon(operationArguments.TargetUri, true)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              await aadAuth.ValidateCredentials(operationArguments.TargetUri, credentials))) ||
                            (operationArguments.Interactivity != Interactivity.Never &&
                             ((credentials = await aadAuth.InteractiveLogon(operationArguments.TargetUri, true)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              await aadAuth.ValidateCredentials(operationArguments.TargetUri, credentials))))
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' found.");
                            program.LogEvent($"Azure Directory credentials  for '{operationArguments.TargetUri}' successfully retrieved.", EventLogEntryType.SuccessAudit);
                        }
                        else
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' not found.");
                            program.LogEvent($"Failed to retrieve Azure Directory credentials for '{operationArguments.TargetUri}'.", EventLogEntryType.FailureAudit);
                        }
                    }).Wait();
            }
            break;

            case AuthorityType.MicrosoftAccount:
            {
                VstsMsaAuthentication msaAuth = authentication as VstsMsaAuthentication;

                Task.Run(async() =>
                    {
                        // attempt to get cached creds -> interactive logon note that MSA
                        // "credentials" are always scoped access tokens
                        if (((operationArguments.Interactivity != Interactivity.Always &&
                              ((credentials = msaAuth.GetCredentials(operationArguments.TargetUri)) != null) &&
                              (!operationArguments.ValidateCredentials ||
                               await msaAuth.ValidateCredentials(operationArguments.TargetUri, credentials)))) ||
                            (operationArguments.Interactivity != Interactivity.Never &&
                             ((credentials = await msaAuth.InteractiveLogon(operationArguments.TargetUri, true)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              await msaAuth.ValidateCredentials(operationArguments.TargetUri, credentials))))
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' found.");
                            program.LogEvent($"Microsoft Live credentials for '{operationArguments.TargetUri}' successfully retrieved.", EventLogEntryType.SuccessAudit);
                        }
                        else
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' not found.");
                            program.LogEvent($"Failed to retrieve Microsoft Live credentials for '{operationArguments.TargetUri}'.", EventLogEntryType.FailureAudit);
                        }
                    }).Wait();
            }
            break;

            case AuthorityType.GitHub:
            {
                Github.Authentication ghAuth = authentication as Github.Authentication;

                Task.Run(async() =>
                    {
                        if ((operationArguments.Interactivity != Interactivity.Always &&
                             ((credentials = ghAuth.GetCredentials(operationArguments.TargetUri)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              await ghAuth.ValidateCredentials(operationArguments.TargetUri, credentials))) ||
                            (operationArguments.Interactivity != Interactivity.Never &&
                             ((credentials = await ghAuth.InteractiveLogon(operationArguments.TargetUri)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              await ghAuth.ValidateCredentials(operationArguments.TargetUri, credentials))))
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' found.");
                            program.LogEvent($"GitHub credentials for '{operationArguments.TargetUri}' successfully retrieved.", EventLogEntryType.SuccessAudit);
                        }
                        else
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' not found.");
                            program.LogEvent($"Failed to retrieve GitHub credentials for '{operationArguments.TargetUri}'.", EventLogEntryType.FailureAudit);
                        }
                    }).Wait();
            }
            break;

            case AuthorityType.Bitbucket:
            {
                var bbcAuth = authentication as Bitbucket.Authentication;

                Task.Run(async() =>
                    {
                        if (((operationArguments.Interactivity != Interactivity.Always) &&
                             ((credentials = bbcAuth.GetCredentials(operationArguments.TargetUri, operationArguments.CredUsername)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              ((credentials = await bbcAuth.ValidateCredentials(operationArguments.TargetUri, operationArguments.CredUsername, credentials)) != null))) ||
                            ((operationArguments.Interactivity != Interactivity.Never) &&
                             ((credentials = await bbcAuth.InteractiveLogon(operationArguments.TargetUri, operationArguments.CredUsername)) != null) &&
                             (!operationArguments.ValidateCredentials ||
                              ((credentials = await bbcAuth.ValidateCredentials(operationArguments.TargetUri, operationArguments.CredUsername, credentials)) != null))))
                        {
                            Git.Trace.WriteLine($"credentials for '{operationArguments.TargetUri}' found.");
                            // Bitbucket relies on a username + secret, so make sure there is a
                            // username to return
                            if (operationArguments.CredUsername != null)
                            {
                                credentials = new Credential(operationArguments.CredUsername, credentials.Password);
                            }
                            program.LogEvent($"Bitbucket credentials for '{operationArguments.TargetUri}' successfully retrieved.", EventLogEntryType.SuccessAudit);
                        }
                        else
                        {
                            program.LogEvent($"Failed to retrieve Bitbucket credentials for '{operationArguments.TargetUri}'.", EventLogEntryType.FailureAudit);
                        }
                    }).Wait();
            }
            break;

            case AuthorityType.Ntlm:
            {
                Git.Trace.WriteLine($"'{operationArguments.TargetUri}' is NTLM.");
                credentials = BasicAuthentication.NtlmCredentials;
            }
            break;
            }

            if (credentials != null)
            {
                operationArguments.SetCredentials(credentials);
            }

            return(credentials);
        }
Beispiel #25
0
 public BitbucketCloudClient(string url, BasicAuthentication basic)
     : this(url)
 {
     _auth = basic;
 }
        /* Wikipedia:
         * http://en.wikipedia.org/wiki/Basic_access_authentication
         *
         * "Aladdin:open sesame"
         * should equal
         * "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
         */

        public BasicAuthTest()
        {
            _auth = new BasicAuthentication(OnAuth, OnRequired);
        }
Beispiel #27
0
 public MauticApi(BasicAuthentication authentication)
 {
 }
 public MembershipAuthentication(IAuthenticationSession session, IPrincipalContext context, IMembershipRepository membership, ILockedOutRule lockedOutRule)
 {
     _membership = membership;
     _inner = new BasicAuthentication(session, context, this, this, lockedOutRule);
 }
Beispiel #29
0
 public override void UpdateHeaders(System.Net.WebHeaderCollection headers)
 {
     BasicAuthentication.SetUnauthorizedHeader(headers, _realm);
 }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm");
     this.hooks  = new FakeApplicationPipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
Beispiel #31
0
 public void Initialize(IPipelines pipelines)
 {
     BasicAuthentication.Enable(pipelines, new BasicAuthenticationConfiguration(new DummyValidator(), "argolis"));
 }
        /// <summary>
        /// Get Http job authentication.
        /// </summary>
        /// <param name="authenticationParams">Http authentication properties specified via PowerShell.</param>
        /// <returns>HttpAuthentication object.</returns>
        private HttpAuthentication PopulateHttpAuthentication(PSHttpJobAuthenticationParams authenticationParams)
        {
            if (authenticationParams == null ||
                authenticationParams.HttpAuthType == null ||
                authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationNone, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationClientCertificate, StringComparison.InvariantCultureIgnoreCase))
            {
                if(string.IsNullOrWhiteSpace(authenticationParams.ClientCertPfx) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientCertPassword))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidClientCertAuthRequest);
                }

                var clientCert = new ClientCertAuthentication()
                {
                    Type = HttpAuthenticationType.ClientCertificate,
                    Pfx = authenticationParams.ClientCertPfx,
                    Password = authenticationParams.ClientCertPassword
                };

                return clientCert;
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationActiveDirectoryOAuth, StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(authenticationParams.Tenant) ||
                    string.IsNullOrWhiteSpace(authenticationParams.ClientId) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Secret) ||
                    string.IsNullOrWhiteSpace(authenticationParams.Audience))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidActiveDirectoryOAuthRequest);
                }

                var adOAuth = new OAuthAuthentication()
                {
                    Type = HttpAuthenticationType.ActiveDirectoryOAuth,
                    Audience = authenticationParams.Audience,
                    ClientId = authenticationParams.ClientId,
                    Secret = authenticationParams.Secret,
                    Tenant = authenticationParams.Tenant
                };

                return adOAuth;
            }
            else if (authenticationParams.HttpAuthType.Equals(Constants.HttpAuthenticationBasic, StringComparison.InvariantCultureIgnoreCase))
            {
                if(string.IsNullOrWhiteSpace(authenticationParams.Username) ||
                   string.IsNullOrWhiteSpace(authenticationParams.Password))
                {
                    throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidBasicRequest);
                }

                var basic = new BasicAuthentication()
                {
                    Type = HttpAuthenticationType.Basic,
                    Username = authenticationParams.Username,
                    Password = authenticationParams.Password
                };

                return basic;
            }
            else
            {
                throw new PSManagement.PSArgumentException(Resources.SchedulerInvalidAuthenticationType);
            }
        }