Skip to content

Instantly share code, notes, and snippets.

@hnrkndrssn
Created August 23, 2019 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnrkndrssn/c40a4aba66a2680cac4e72d6d0fde4a1 to your computer and use it in GitHub Desktop.
Save hnrkndrssn/c40a4aba66a2680cac4e72d6d0fde4a1 to your computer and use it in GitHub Desktop.
Handle 2FA authentication in Octokit.net
<Query Kind="Program">
<NuGetReference>Octokit</NuGetReference>
<Namespace>Octokit</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
</Query>
static string product = "Octokit-LINQPad-2FA-Demo";
IGitHubClient _Client = new GitHubClient(new ProductHeaderValue(product));
string clientId = "client-id-of-your-registered-github-application";
string clientSecret = "client-secret-of-your-registered-github-application";
async Task Main()
{
await Login();
}
private async Task Login()
{
string Username = Util.ReadLine();
string Password = Util.GetPassword("github password", true);
_Client.Connection.Credentials = new Credentials(Username, Password);
var newAuthorization = new NewAuthorization
{
Scopes = new List<string> { "user", "repo" },
Note = product
};
try
{
var authorization = await _Client.Authorization.GetOrCreateApplicationAuthentication(
clientId,
clientSecret,
newAuthorization);
_Client.Connection.Credentials = new Credentials(authorization.Token);
"Successfully authenticated with username password".Dump();
}
catch (TwoFactorRequiredException)
{
await AuthenticateWithOTP();
}
catch (Exception ex)
{
throw ex;
}
}
private async Task AuthenticateWithOTP()
{
string OneTimePassword = Util.GetPassword("github otp", true);
var newAuthorization = new NewAuthorization
{
Scopes = new List<string> { "user", "repo" },
Note = product
};
try
{
var authorization = await _Client.Authorization.GetOrCreateApplicationAuthentication(
clientId,
clientSecret,
newAuthorization,
OneTimePassword);
_Client.Connection.Credentials = new Credentials(authorization.Token);
"Successfully authenticated with One Time Password".Dump();
}
catch (Exception ex)
{
throw ex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment