Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Libgit2sharp authentication using Personal Access Token

For more information. I have already cloned the private repository in my local drive. More background info. This is a web application which im trying to implement in which user can download different files from my local cloned folders of the git repo. So everytime someone tries to download im trying to fetch and pull to get the latest data in my local drive.

        var path = "my local drive path";
        using (var repo = new Repository(path))
        {
            FetchOptions options = new FetchOptions();
            options.CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) =>
                new UsernamePasswordCredentials()
                {
                    Username="[email protected]",
                    Password = "mypassword"
                });

            foreach (Remote remote in repo.Network.Remotes)
            {
                IEnumerable<string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification);
                Commands.Fetch(repo, remote.Name, refSpecs, options, logMessage);
            }
        }
        //Console.WriteLine(logMessage);

        using (var repo = new Repository(path))
        {
            // Credential information to fetch
            LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions();
            options.FetchOptions = new FetchOptions();
            options.FetchOptions.CredentialsProvider = new CredentialsHandler(
                (url, usernameFromUrl, types) =>
                    new UsernamePasswordCredentials()
                    {
                        Username = "[email protected]",
                        Password = "my password"
                    });

            // User information to create a merge commit
            var signature = new LibGit2Sharp.Signature(
                new Identity("xxxx", "[email protected]"), DateTimeOffset.Now);

            // Pull
            Commands.Pull(repo, signature, options);
        }

With my normal username and password it works fine. But when i use my personal access token inplace of password or username, it throws error. Can someone help me with this.

like image 560
eragon2983 Avatar asked Nov 15 '25 12:11

eragon2983


1 Answers

CloneOptions co = new CloneOptions();
string gitUser = "gitUser", gitToken = "gitToken";
co.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = gitUser, Password = gitToken };

Works for me using github. Just put the git token in place of a password and still include the user name. Maybe you need to provide the correct access to your token?

like image 191
codeOnTheWestCoast Avatar answered Nov 18 '25 20:11

codeOnTheWestCoast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!