public async Task CannotCreatePersonalTokenWhenUsingOauthTokenCredentials() { var github = Helper.GetAuthenticatedClient(); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new string[] { "user" }); var error = Assert.ThrowsAsync<ForbiddenException>(() => github.Authorization.Create(newAuthorization)); Assert.True(error.Result.Message.Contains("username and password Basic Auth")); }
/// <summary> /// Creates a new authorization for the specified OAuth application if an authorization for that application /// doesn’t already exist for the user; otherwise, it fails. /// </summary> /// <remarks> /// This method requires authentication. /// See the <a href="http://developer.github.com/v3/oauth/#get-or-create-an-authorization-for-a-specific-app">API documentation</a> for more information. /// </remarks> /// <param name="clientId">Client ID of the OAuth application for the token</param> /// <param name="clientSecret">The client secret</param> /// <param name="newAuthorization">Describes the new authorization to create</param> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make this request. /// </exception> /// <exception cref="TwoFactorRequiredException"> /// Thrown when the current account has two-factor authentication enabled and an authentication code is required. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>The created <see cref="Authorization"/>.</returns> public IObservable<ApplicationAuthorization> Create( string clientId, string clientSecret, NewAuthorization newAuthorization) { Ensure.ArgumentNotNullOrEmptyString(clientId, "clientId"); Ensure.ArgumentNotNullOrEmptyString(clientSecret, "clientSecret"); Ensure.ArgumentNotNull(newAuthorization, "authorization"); return _client.Create(clientId, clientSecret, newAuthorization).ToObservable(); }
public async Task CanCreateAndGetAuthorizationWithoutFingerPrint() { var client = Helper.GetAuthenticatedClient(); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }); // the first call will create the authorization var created = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.NotNull(created); Assert.False(String.IsNullOrWhiteSpace(created.Token)); Assert.True(String.IsNullOrWhiteSpace(created.TokenLastEight)); Assert.True(String.IsNullOrWhiteSpace(created.HashedToken)); // we can then query it through the regular API var get = await client.Authorization.Get(created.Id); Assert.Equal(created.Id, get.Id); Assert.Equal(created.Note, get.Note); // but the second time we call this API we get // a different set of data var getExisting = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.Equal(created.Id, getExisting.Id); // NOTE: the old API will continue to return the full // token if no Fingerprint is included Assert.False(String.IsNullOrWhiteSpace(getExisting.Token)); // NOTE: and these new values are not included Assert.True(String.IsNullOrWhiteSpace(getExisting.TokenLastEight)); Assert.True(String.IsNullOrWhiteSpace(getExisting.HashedToken)); await client.Authorization.Delete(created.Id); }
public async Task CanCreateAndGetAuthorizationByFingerprint() { var client = Helper.GetAuthenticatedClient(); var fingerprint = Helper.MakeNameWithTimestamp("authorization-testing"); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }, fingerprint); var created = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.NotNull(created); Assert.False(String.IsNullOrWhiteSpace(created.Token)); // we can then query it through the regular API var get = await client.Authorization.Get(created.Id); Assert.Equal(created.Id, get.Id); Assert.Equal(created.Note, get.Note); // but the second time we call this API we get // a different set of data var getExisting = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.Equal(created.Id, getExisting.Id); // NOTE: the new API will no longer return the full // token as soon as you specify a Fingerprint Assert.True(String.IsNullOrWhiteSpace(getExisting.Token)); // NOTE: however you will get these two new properties // to help identify the authorization at hand Assert.False(String.IsNullOrWhiteSpace(getExisting.TokenLastEight)); Assert.False(String.IsNullOrWhiteSpace(getExisting.HashedToken)); await client.Authorization.Delete(created.Id); }
public async Task CanCreatePersonalToken() { var github = Helper.GetBasicAuthClient(); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new string[] { "user" }); var created = await github.Authorization.Create(newAuthorization); Assert.False(string.IsNullOrWhiteSpace(created.Token)); Assert.False(string.IsNullOrWhiteSpace(created.TokenLastEight)); Assert.False(string.IsNullOrWhiteSpace(created.HashedToken)); var get = await github.Authorization.Get(created.Id); Assert.Equal(created.Id, get.Id); Assert.Equal(created.Note, get.Note); }
private async Task <ApplicationAuthorization> CreateAndDeleteExistingApplicationAuthorization( IGitHubClient client, NewAuthorization newAuth, string twoFactorAuthenticationCode) { ApplicationAuthorization result; var retry = 0; do { if (twoFactorAuthenticationCode == null) { result = await client.Authorization.GetOrCreateApplicationAuthentication( clientId, clientSecret, newAuth); } else { result = await client.Authorization.GetOrCreateApplicationAuthentication( clientId, clientSecret, newAuth, twoFactorAuthenticationCode); } if (result.Token == string.Empty) { if (twoFactorAuthenticationCode == null) { await client.Authorization.Delete(result.Id); } else { await client.Authorization.Delete(result.Id, twoFactorAuthenticationCode); } } } while (result.Token == string.Empty && retry++ == 0); return(result); }
public async Task CanCreateAndGetAuthorizationWithoutFingerPrint() { var github = Helper.GetBasicAuthClient(); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }); // the first call will create the authorization var created = await github.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.False(string.IsNullOrWhiteSpace(created.Token)); Assert.False(string.IsNullOrWhiteSpace(created.TokenLastEight)); Assert.False(string.IsNullOrWhiteSpace(created.HashedToken)); // we can then query it through the regular API var get = await github.Authorization.Get(created.Id); Assert.Equal(created.Id, get.Id); Assert.Equal(created.Note, get.Note); // but the second time we call this API we get // a different set of data var getExisting = await github.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.Equal(created.Id, getExisting.Id); // the token is no longer returned for subsequent calls Assert.True(string.IsNullOrWhiteSpace(getExisting.Token)); // however the hashed and last 8 characters are available Assert.False(string.IsNullOrWhiteSpace(getExisting.TokenLastEight)); Assert.False(string.IsNullOrWhiteSpace(getExisting.HashedToken)); await github.Authorization.Delete(created.Id); }
public async Task CanCreateAndGetAuthorizationWithoutFingerPrint() { var client = Helper.GetAuthenticatedClient(); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }); // the first call will create the authorization var created = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.False(String.IsNullOrWhiteSpace(created.Token)); Assert.False(String.IsNullOrWhiteSpace(created.TokenLastEight)); Assert.False(String.IsNullOrWhiteSpace(created.HashedToken)); // we can then query it through the regular API var get = await client.Authorization.Get(created.Id); Assert.Equal(created.Id, get.Id); Assert.Equal(created.Note, get.Note); // but the second time we call this API we get // a different set of data var getExisting = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); Assert.Equal(created.Id, getExisting.Id); // the token is no longer returned for subsequent calls Assert.True(String.IsNullOrWhiteSpace(getExisting.Token)); // however the hashed and last 8 characters are available Assert.False(String.IsNullOrWhiteSpace(getExisting.TokenLastEight)); Assert.False(String.IsNullOrWhiteSpace(getExisting.HashedToken)); await client.Authorization.Delete(created.Id); }
public async Task CanRevokeApplicationAuthentication() { var github = Helper.GetAuthenticatedClient(); var fingerprint = Helper.MakeNameWithTimestamp("authorization-testing"); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }, fingerprint); var created = await github.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); var applicationClient = Helper.GetAuthenticatedApplicationClient(); await applicationClient.Authorization.RevokeApplicationAuthentication(Helper.ClientId, created.Token); Assert.ThrowsAsync <NotFoundException>(() => applicationClient.Authorization.CheckApplicationAuthentication(Helper.ClientId, created.Token)); Assert.ThrowsAsync <NotFoundException>(() => github.Authorization.Get(created.Id)); }
public async Task GetsOrCreatesAuthenticationWithFingerprintAtCorrectUrl() { var data = new NewAuthorization { Fingerprint = "ha-ha-fingerprint" }; var client = Substitute.For <IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); Uri calledUri = null; dynamic calledBody = null; client.Put <ApplicationAuthorization>(Arg.Do <Uri>(u => calledUri = u), Arg.Do <object>(body => calledBody = body)); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); Assert.NotNull(calledUri); Assert.Equal(calledUri.ToString(), "authorizations/clients/clientId"); Assert.NotNull(calledBody); Assert.Equal(calledBody.fingerprint, "ha-ha-fingerprint"); }
public async Task GetsOrCreatesAuthenticationWithFingerprintAtCorrectUrl() { var data = new NewAuthorization { Fingerprint = "ha-ha-fingerprint" }; var client = Substitute.For <IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); Uri calledUri = null; dynamic calledBody = null; client.Put <ApplicationAuthorization>(Arg.Do <Uri>(u => calledUri = u), Arg.Do <dynamic>(body => calledBody = body)); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); Assert.NotNull(calledUri); Assert.Equal(calledUri.ToString(), "authorizations/clients/clientId"); Assert.NotNull(calledBody); var fingerprintProperty = ((IEnumerable <PropertyInfo>)calledBody.GetType().DeclaredProperties).FirstOrDefault(x => x.Name == "fingerprint"); Assert.NotNull(fingerprintProperty); Assert.Equal(fingerprintProperty.GetValue(calledBody), "ha-ha-fingerprint"); }
public void ThrowsTwoFactorChallengeFailedExceptionWhenProvidedCodeIsIncorrect() { var challengeResults = new Queue <TwoFactorChallengeResult>(new[] { TwoFactorChallengeResult.RequestResendCode, new TwoFactorChallengeResult("wrong-code") }); var twoFactorFailedException = new TwoFactorChallengeFailedException(); var data = new NewAuthorization(); var client = Substitute.For <IObservableAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any <NewAuthorization>()) .Returns(Observable.Throw <ApplicationAuthorization>(new TwoFactorRequiredException())); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any <NewAuthorization>(), "wrong-code") .Returns(Observable.Throw <ApplicationAuthorization>(twoFactorFailedException)); var observer = Substitute.For <System.IObserver <ApplicationAuthorization> >(); client.GetOrCreateApplicationAuthentication( "clientId", "secret", data, _ => Observable.Return(challengeResults.Dequeue())) .Subscribe(observer); observer.Received().OnError(twoFactorFailedException); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any <NewAuthorization>()); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any <NewAuthorization>(), "wrong-code"); }
private async Task Login() { _Client.Connection.Credentials = new Credentials(Username, Password); var newAuthorization = new NewAuthorization { Scopes = new List <string> { "user", "repo", "delete_repo", "notifications", "gist" }, Note = "Grimpoteuthis" }; try { var authorization = await _Client.Authorization.GetOrCreateApplicationAuthentication( "client-id-of-your-registered-github-application", "client-secret-of-your-registered-github-application", newAuthorization); _Client.Connection.Credentials = new Credentials(authorization.Token); RxApp.MutableResolver.Register(() => _Client, typeof(IGitHubClient)); Username = String.Empty; Password = String.Empty; ErrorMessage = "Successfully authenticated with username password"; } catch (TwoFactorRequiredException tfrex) { ErrorMessage = tfrex.Message; RequireOneTimePassword = true; } catch (Exception ex) { ErrorMessage = ex.Message; } }
/// <inheritdoc/> public async Task <LoginResult> Login( HostAddress hostAddress, IGitHubClient client, string userName, string password) { Guard.ArgumentNotNull(hostAddress, nameof(hostAddress)); Guard.ArgumentNotNull(client, nameof(client)); Guard.ArgumentNotEmptyString(userName, nameof(userName)); Guard.ArgumentNotEmptyString(password, nameof(password)); // Start by saving the username and password, these will be used by the `IGitHubClient` // until an authorization token has been created and acquired: await keychain.Save(userName, password, hostAddress).ConfigureAwait(false); var newAuth = new NewAuthorization { Scopes = requestedScopes, Note = authorizationNote, Fingerprint = fingerprint, }; ApplicationAuthorization auth = null; do { try { auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null) .ConfigureAwait(false); EnsureNonNullAuthorization(auth); } catch (TwoFactorAuthorizationException e) { auth = await HandleTwoFactorAuthorization(hostAddress, client, newAuth, e) .ConfigureAwait(false); } catch (Exception e) { // Some enterpise instances don't support OAUTH, so fall back to using the // supplied password - on intances that don't support OAUTH the user should // be using a personal access token as the password. if (EnterpriseWorkaround(hostAddress, e)) { auth = new ApplicationAuthorization(0, null, null, null, null, null, null, null, DateTimeOffset.MinValue, DateTimeOffset.MinValue, null, password); } else { await keychain.Delete(hostAddress).ConfigureAwait(false); throw; } } } while (auth == null); await keychain.Save(userName, auth.Token, hostAddress).ConfigureAwait(false); return(await ReadUserWithRetry(client).ConfigureAwait(false)); }
/// <inheritdoc/> public async Task <LoginResultData> Login( UriString host, IGitHubClient client, string username, string password) { Guard.ArgumentNotNull(host, nameof(host)); Guard.ArgumentNotNull(client, nameof(client)); Guard.ArgumentNotNullOrWhiteSpace(username, nameof(username)); Guard.ArgumentNotNullOrWhiteSpace(password, nameof(password)); // Start by saving the username and password, these will be used by the `IGitHubClient` // until an authorization token has been created and acquired: keychain.Connect(host); keychain.SetCredentials(new Credential(host, username, password)); var newAuth = new NewAuthorization { Scopes = scopes, Note = authorizationNote, Fingerprint = fingerprint, }; ApplicationAuthorization auth = null; try { logger.Info("Login Username:{0}", username); auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null); EnsureNonNullAuthorization(auth); } catch (TwoFactorAuthorizationException e) { LoginResultCodes result; if (e is TwoFactorRequiredException) { result = LoginResultCodes.CodeRequired; logger.Debug("2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message); } else { result = LoginResultCodes.CodeFailed; logger.Error(e, "2FA TwoFactorAuthorizationException: {0} {1}", LoginResultCodes.CodeRequired, e.Message); } return(new LoginResultData(result, e.Message, client, host, newAuth)); } catch (LoginAttemptsExceededException e) { logger.Warning(e, "Login LoginAttemptsExceededException: {0}", e.Message); await keychain.Clear(host, false); return(new LoginResultData(LoginResultCodes.LockedOut, Localization.LockedOut, host)); } catch (ApiValidationException e) { logger.Warning(e, "Login ApiValidationException: {0}", e.Message); var message = e.ApiError.FirstErrorMessageSafe(); await keychain.Clear(host, false); return(new LoginResultData(LoginResultCodes.Failed, message, host)); } catch (Exception e) { logger.Warning(e, "Login Exception"); // Some enterprise instances don't support OAUTH, so fall back to using the // supplied password - on instances that don't support OAUTH the user should // be using a personal access token as the password. if (EnterpriseWorkaround(host, e)) { auth = new ApplicationAuthorization(password); } else { await keychain.Clear(host, false); return(new LoginResultData(LoginResultCodes.Failed, Localization.LoginFailed, host)); } } keychain.SetToken(host, auth.Token); await keychain.Save(host); return(new LoginResultData(LoginResultCodes.Success, "Success", host)); }
public async Task CanResetApplicationAuthentication() { var github = Helper.GetBasicAuthClient(); var fingerprint = Helper.MakeNameWithTimestamp("authorization-testing"); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }, fingerprint); var created = await github.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); var applicationClient = Helper.GetAuthenticatedApplicationClient(); var applicationAuthorization = await applicationClient.Authorization.ResetApplicationAuthentication(Helper.ClientId, created.Token); Assert.NotNull(applicationAuthorization); Assert.NotEqual(created.Token, applicationAuthorization.Token); await github.Authorization.Delete(created.Id); Assert.ThrowsAsync<NotFoundException>(() => github.Authorization.Get(created.Id)); }
public void GetsOrCreatesAuthenticationAtCorrectUrl() { var data = new NewAuthorization(); var client = Substitute.For<IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); client.Received().Put<ApplicationAuthorization>(Arg.Is<Uri>(u => u.ToString() == "authorizations/clients/clientId"), Args.Object); }
public async Task CanRevokeApplicationAuthentication() { var client = Helper.GetAuthenticatedClient(); var fingerprint = Helper.MakeNameWithTimestamp("authorization-testing"); var note = Helper.MakeNameWithTimestamp("Testing authentication"); var newAuthorization = new NewAuthorization( note, new[] { "user" }, fingerprint); var created = await client.Authorization.GetOrCreateApplicationAuthentication( Helper.ClientId, Helper.ClientSecret, newAuthorization); var applicationClient = Helper.GetAuthenticatedApplicationClient(); await applicationClient.Authorization.RevokeApplicationAuthentication(Helper.ClientId, created.Token); AssertEx.Throws<NotFoundException>(async () => await applicationClient.Authorization.CheckApplicationAuthentication(Helper.ClientId, created.Token)); AssertEx.Throws<NotFoundException>(async () => await client.Authorization.Get(created.Id)); }
/// <inheritdoc/> public async Task <User> Login( HostAddress hostAddress, IGitHubClient client, string userName, string password) { Guard.ArgumentNotNull(hostAddress, nameof(hostAddress)); Guard.ArgumentNotNull(client, nameof(client)); Guard.ArgumentNotEmptyString(userName, nameof(userName)); Guard.ArgumentNotEmptyString(password, nameof(password)); // Start by saving the username and password, these will be used by the `IGitHubClient` // until an authorization token has been created and acquired: await keychain.Save(userName, password, hostAddress).ConfigureAwait(false); var newAuth = new NewAuthorization { Scopes = scopes, Note = authorizationNote, Fingerprint = fingerprint, }; ApplicationAuthorization auth = null; do { try { auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null) .ConfigureAwait(false); EnsureNonNullAuthorization(auth); } catch (TwoFactorAuthorizationException e) { auth = await HandleTwoFactorAuthorization(hostAddress, client, newAuth, e) .ConfigureAwait(false); } catch (Exception e) { // Some enterpise instances don't support OAUTH, so fall back to using the // supplied password - on intances that don't support OAUTH the user should // be using a personal access token as the password. if (EnterpriseWorkaround(hostAddress, e)) { auth = new ApplicationAuthorization(password); } else { await keychain.Delete(hostAddress).ConfigureAwait(false); throw; } } } while (auth == null); await keychain.Save(userName, auth.Token, hostAddress).ConfigureAwait(false); var retry = 0; while (true) { try { return(await client.User.Current().ConfigureAwait(false)); } catch (AuthorizationException) { if (retry++ == 3) { throw; } } // It seems that attempting to use a token immediately sometimes fails, retry a few // times with a delay of of 1s to allow the token to propagate. await Task.Delay(1000); } }
public async Task UsesCallbackToRetrieveTwoFactorCode() { var twoFactorChallengeResult = new TwoFactorChallengeResult("two-factor-code"); var data = new NewAuthorization { Note = "note" }; var client = Substitute.For<IAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()) .Returns<Task<ApplicationAuthorization>>(_ => { throw new TwoFactorRequiredException(); }); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "two-factor-code") .Returns(Task.Factory.StartNew(() => new ApplicationAuthorization("xyz"))); var result = await client.GetOrCreateApplicationAuthentication("clientId", "secret", data, e => Task.Factory.StartNew(() => twoFactorChallengeResult)); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Is<NewAuthorization>(u => u.Note == "note")); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "two-factor-code"); Assert.Equal("xyz", result.Token); }
public async Task WrapsTwoFactorFailureWithTwoFactorException() { var data = new NewAuthorization(); var client = Substitute.For<IApiConnection>(); client.Put<ApplicationAuthorization>(Args.Uri, Args.Object, Args.String) .ThrowsAsync<ApplicationAuthorization>( new AuthorizationException( new Response(HttpStatusCode.Unauthorized, null, new Dictionary<string, string>(), "application/json"))); var authEndpoint = new AuthorizationsClient(client); await Assert.ThrowsAsync<TwoFactorChallengeFailedException>(() => authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data, "authenticationCode")); }
/// <summary> /// Creates a new personal token for the authenticated user. /// </summary> /// <remarks> /// This method requires authentication. /// See the <a href="https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization">API documentation</a> for more information. /// </remarks> /// <param name="newAuthorization">Describes the new authorization to create</param> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make this request. /// </exception> /// <exception cref="TwoFactorRequiredException"> /// Thrown when the current account has two-factor authentication enabled and an authentication code is required. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>The created <see cref="Authorization"/>.</returns> public IObservable <ApplicationAuthorization> Create(NewAuthorization newAuthorization) { Ensure.ArgumentNotNull(newAuthorization, "authorization"); return(_client.Create(newAuthorization).ToObservable()); }
/// <summary> /// Creates a new personal token for the authenticated user. /// </summary> /// <remarks> /// This method requires authentication. /// See the <a href="https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization">API documentation</a> for more information. /// </remarks> /// <param name="newAuthorization">Describes the new authorization to create</param> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make this request. /// </exception> /// <exception cref="TwoFactorRequiredException"> /// Thrown when the current account has two-factor authentication enabled and an authentication code is required. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>The created <see cref="Authorization"/>.</returns> public IObservable<ApplicationAuthorization> Create(NewAuthorization newAuthorization) { Ensure.ArgumentNotNull(newAuthorization, "newAuthorization"); return _client.Create(newAuthorization).ToObservable(); }
/// <summary> /// This method will create a new authorization for the specified OAuth application, only if an authorization /// for that application doesn’t already exist for the user. It returns the user’s token for the application /// if one exists. Otherwise, it creates one. /// </summary> /// <remarks> /// See <a href="http://developer.github.com/v3/oauth/#get-or-create-an-authorization-for-a-specific-app">API /// documentation</a> for more details. /// </remarks> /// <param name="clientId">Client ID for the OAuth application that is requesting the token</param> /// <param name="clientSecret">The client secret</param> /// <param name="newAuthorization">Defines the scopes and metadata for the token</param> /// <param name="twoFactorAuthenticationCode">The two-factor authentication code provided by the user</param> /// <exception cref="AuthorizationException">Thrown when the user does not have permission to make /// this request. Check </exception> /// <exception cref="TwoFactorChallengeFailedException">Thrown when the two-factor code is not /// valid.</exception> /// <returns></returns> public IObservable<ApplicationAuthorization> GetOrCreateApplicationAuthentication( string clientId, string clientSecret, NewAuthorization newAuthorization, string twoFactorAuthenticationCode) { Ensure.ArgumentNotNullOrEmptyString(clientId, "clientId"); Ensure.ArgumentNotNullOrEmptyString(clientSecret, "clientSecret"); Ensure.ArgumentNotNull(newAuthorization, "newAuthorization"); Ensure.ArgumentNotNullOrEmptyString(twoFactorAuthenticationCode, "twoFactorAuthenticationCode"); return _client.GetOrCreateApplicationAuthentication( clientId, clientSecret, newAuthorization, twoFactorAuthenticationCode) .ToObservable(); }
/// <summary> /// Creates a new personal token for the authenticated user. /// </summary> /// <remarks> /// This method requires authentication. /// See the <a href="https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization">API documentation</a> for more information. /// </remarks> /// <param name="twoFactorAuthenticationCode">The two-factor authentication code in response to the current user's previous challenge</param> /// <param name="newAuthorization">Describes the new authorization to create</param> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make this request. /// </exception> /// <exception cref="TwoFactorRequiredException"> /// Thrown when the current account has two-factor authentication enabled and an authentication code is required. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>The created <see cref="Authorization"/>.</returns> public IObservable<ApplicationAuthorization> Create( NewAuthorization newAuthorization, string twoFactorAuthenticationCode) { Ensure.ArgumentNotNull(newAuthorization, "newAuthorization"); Ensure.ArgumentNotNullOrEmptyString(twoFactorAuthenticationCode, "twoFactorAuthenticationCode"); return _client.Create(newAuthorization, twoFactorAuthenticationCode).ToObservable(); }
public async Task RetriesWhenResendRequested() { var challengeResults = new Queue<TwoFactorChallengeResult>(new[] { TwoFactorChallengeResult.RequestResendCode, new TwoFactorChallengeResult("two-factor-code") }); var data = new NewAuthorization(); var client = Substitute.For<IAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()) .Returns<Task<ApplicationAuthorization>>(_ => { throw new TwoFactorRequiredException(); }); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "two-factor-code") .Returns(Task.Factory.StartNew(() => new ApplicationAuthorization("OAUTHSECRET"))); var result = await client.GetOrCreateApplicationAuthentication("clientId", "secret", data, e => Task.Factory.StartNew(() => challengeResults.Dequeue())); client.Received(2).GetOrCreateApplicationAuthentication("clientId", "secret", Args.NewAuthorization); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Args.NewAuthorization, "two-factor-code"); Assert.Equal("OAUTHSECRET", result.Token); }
public void ThrowsTwoFactorChallengeFailedExceptionWhenProvidedCodeIsIncorrect() { var challengeResults = new Queue<TwoFactorChallengeResult>(new[] { TwoFactorChallengeResult.RequestResendCode, new TwoFactorChallengeResult("wrong-code"), }); var twoFactorFailedException = new TwoFactorChallengeFailedException(); var data = new NewAuthorization(); var client = Substitute.For<IObservableAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()) .Returns(Observable.Throw<Authorization>(new TwoFactorRequiredException())); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "wrong-code") .Returns(Observable.Throw<Authorization>(twoFactorFailedException)); var observer = Substitute.For<System.IObserver<Authorization>>(); client.GetOrCreateApplicationAuthentication( "clientId", "secret", data, _ => Observable.Return(challengeResults.Dequeue())) .Subscribe(observer); observer.Received().OnError(twoFactorFailedException); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "wrong-code"); }
public async Task ThrowsTwoFactorChallengeFailedExceptionWhenProvidedCodeIsIncorrect() { var challengeResults = new Queue<TwoFactorChallengeResult>(new[] { TwoFactorChallengeResult.RequestResendCode, new TwoFactorChallengeResult("wrong-code") }); var data = new NewAuthorization(); var client = Substitute.For<IAuthorizationsClient>(); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()) .Returns<Task<ApplicationAuthorization>>(_ => { throw new TwoFactorRequiredException(); }); client.GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "wrong-code") .Returns<Task<ApplicationAuthorization>>(_ => { throw new TwoFactorChallengeFailedException(); }); var exception = await Assert.ThrowsAsync<TwoFactorChallengeFailedException>(() => client.GetOrCreateApplicationAuthentication( "clientId", "secret", data, e => Task.Factory.StartNew(() => challengeResults.Dequeue()))); Assert.NotNull(exception); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>()); client.Received().GetOrCreateApplicationAuthentication("clientId", "secret", Arg.Any<NewAuthorization>(), "wrong-code"); }
private static Config Setup() { var config = new Config(); Console.WriteLine("Lpgist Setup"); Console.Write("lprun.exe path [lprun.exe]: "); var lprun = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(lprun)) { config.LprunPath = lprun.Trim(' ', '"', '\''); } Console.Write("Default format(text|html|htmlfrag|csv|csvi) [html]: "); var format = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(format)) { config.Format = format.Trim(); } Console.Write("Want to log into GitHub? [yes]: "); if (YesOrNo(true)) { Console.Write("Username: "******"Password: "******"1c6ea6235caf92bd0f0e"; const string clientSecret = "fd0924a473072503af961a3214a9933e96b930d2"; var newAuthorization = new NewAuthorization( "Lpgist requires Gist access to upload your queries.", new[] { "gist" }); ApplicationAuthorization result; try { result = client.Authorization .Create(clientId, clientSecret, newAuthorization) .GetAwaiter().GetResult(); } catch (TwoFactorRequiredException ex) { Console.Write("Two-factor code from {0}: ", ex.TwoFactorType); var code = Console.ReadLine()?.Trim(); result = client.Authorization .Create(clientId, clientSecret, newAuthorization, code) .GetAwaiter().GetResult(); } config.GitHubAccessToken = result.Token; Console.Write("Want the gists to be public? [yes]: "); config.IsPublic = YesOrNo(true); } Console.WriteLine(); return(config); }
public async Task GetsOrCreatesAuthenticationWithFingerprintAtCorrectUrl() { var data = new NewAuthorization { Fingerprint = "ha-ha-fingerprint" }; var client = Substitute.For<IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); Uri calledUri = null; dynamic calledBody = null; client.Put<ApplicationAuthorization>(Arg.Do<Uri>(u => calledUri = u), Arg.Do<object>(body => calledBody = body)); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); Assert.NotNull(calledUri); Assert.Equal(calledUri.ToString(), "authorizations/clients/clientId"); Assert.NotNull(calledBody); Assert.Equal(calledBody.fingerprint, "ha-ha-fingerprint"); }
public async Task GetsOrCreatesAuthenticationWithFingerprintAtCorrectUrl() { var data = new NewAuthorization { Fingerprint = "ha-ha-fingerprint"}; var client = Substitute.For<IApiConnection>(); var authEndpoint = new AuthorizationsClient(client); authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data); client.Received().Put<ApplicationAuthorization>(Arg.Is<Uri>(u => u.ToString() == "authorizations/clients/clientId/ha-ha-fingerprint"), Args.Object, Args.String, Args.String); // NOTE: preview API }
public async Task WrapsTwoFactorFailureWithTwoFactorException() { var data = new NewAuthorization(); var client = Substitute.For<IApiConnection>(); client.Put<Authorization>(Args.Uri, Args.Object, Args.String) .ThrowsAsync<Authorization>( new AuthorizationException( new ApiResponse<object> { StatusCode = HttpStatusCode.Unauthorized })); var authEndpoint = new AuthorizationsClient(client); await AssertEx.Throws<TwoFactorChallengeFailedException>(async () => await authEndpoint.GetOrCreateApplicationAuthentication("clientId", "secret", data, "authenticationCode")); }