Created
August 23, 2019 07:24
-
-
Save hnrkndrssn/c40a4aba66a2680cac4e72d6d0fde4a1 to your computer and use it in GitHub Desktop.
Handle 2FA authentication in Octokit.net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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