Tag: github

Automating GitHub authentication programmatically using Octokit

I recently made a little C# app to automate the opening of various pull requests to GitHub and add comments and close issues in JIRA simultaneously.

The biggest hurdle was authenticating with GitHub programmatically so that any user can use my app as themselves. Basic authentication is pretty easy, however, at work we enforce two-factor authentication and I didn’t want everyone to have to handle text messages and type in validation criteria every time they open pull requests.

Another option is to use OAuth and open a browser window which redirects the user to the github login screen. If you already have a github sessions and are logged in, there is typically no need to retype a username / password and you merely click “Click to allow this application access to your github account”. This is OK (but not great) if you’re making a web-app. However, if you’re using powershell or making a desktop client, this is far from ideal.

For the fully automated / one-time configuration route, I stumbled across another method. GitHub allows users to store what’s called a “Personal access token” from their Settings page. When creating these tokens, you can limit what functionality they are allowed access to (which is better than authenticating as the full user), and you can then store those tokens locally to give my application limited access to your GitHub account, so it can create pull requests from it.

This uses Octokit, a C# helper library to translate to the GitHub API. (Check out their docs here)

        public async void CreatePullRequest(string personalAccessToken)
            // Authenticate
            var gitHubClient = new GitHubClient(new ProductHeaderValue("mikeparker-testapp"));
            var authToken = new Credentials(personalAccessToken); // ask user to enter this from ui
            gitHubClient.Credentials = authToken;

            // Get current username
            var user = await this.client.User.Current();
            var username = user.Login;

            // Make the Pull Request
            var newPR = new NewPullRequest("The PR title", username + ":branch-to-merge", "master");
            newPR.Body = "This is my PR body..";
            var pullRequest = await this.client.Repository.PullRequest.Create("targetusername", "reponame", newPR);

Note that this requires each user to create a personal access token manually from their GitHub settings page, and then either enter it at runtime or store it as configuration somewhere.