public async Task ValidPersonalAccessToken_TokenShouldSet_LoginShouldBeUnAvailable_SignoutShoudBeAvailable() { // prepare GitHubToken token = new GitHubToken("I am a token", TokenTypes.PersonalAccessToken); var settingsService = new Mock <ISettingsService>(); var authorizationService = new Mock <IAuthorizationService>(); settingsService.Setup(x => x.GetTokenAsync(TokenTypes.PersonalAccessToken)) .Returns(Task.FromResult(token)); authorizationService.Setup(x => x.AuthenticateWithPersonalAccessTokenAsync(It.IsAny <string>())) .Returns(Task.FromResult(new AuthenticationResult() { AuthenticationSuccessful = true })); HomeViewModel viewModel = new HomeViewModel(new Mock <ILogger <HomeViewModel> >().Object, new Mock <INavigationService>().Object, settingsService.Object, authorizationService.Object, new Mock <IProfileService>().Object); // act await viewModel.PrepareViewModelAsync(); // assert Assert.True(viewModel.IsAuthenticated); Assert.False(viewModel.LoginWithCredentialsCommand.CanExecute(null)); Assert.False(viewModel.LoginWithTokenCommand.CanExecute(null)); }
public async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest request, ILogger log) { foreach (var testToken in _testTokenList) { var timeout = TimeSpan.FromSeconds(2); var cancellationTokenSource = new CancellationTokenSource(timeout); var gitHubApiRateLimits = await _gitHubApiExceptionService.GetApiRateLimits(new AuthenticationHeaderValue("bearer", testToken), cancellationTokenSource.Token).ConfigureAwait(false); if (gitHubApiRateLimits.RestApi.RemainingRequestCount > 1000 && gitHubApiRateLimits.GraphQLApi.RemainingRequestCount > 1000) { var gitHubToken = new GitHubToken(testToken, GitHubConstants.OAuthScope, "Bearer"); return(new ContentResult { Content = JsonConvert.SerializeObject(gitHubToken), StatusCode = (int)HttpStatusCode.OK, ContentType = "application/json" }); } } ; return(new NotFoundObjectResult("No Valid GitHub Token Found")); }
private async Task <bool> PerformAuthenticateWithPersonalAccessTokenAsync() { // check to see if we have a token. _logger.LogDebug("Getting personal access token..."); _token = await _settingsService.GetTokenAsync(TokenTypes.PersonalAccessToken); if (_token == null || !_token.IsValid) { _logger.LogError("No personal token available."); IsAuthenticated = false; return(false); } // token is available, attempt to log in with it. _logger.LogInformation("Personal access token available. Attempting to login..."); Status = "Token available. Logging in..."; AuthenticationResult tokenResult = await _authorizationService.AuthenticateWithPersonalAccessTokenAsync(_token.Token); if (!tokenResult.AuthenticationSuccessful) { // token was invalid _logger.LogInformation("Personal access token was invalid."); _IsAuthenticated = false; // clear token. _logger.LogInformation("Clearing Personal access token..."); await _settingsService.ClearTokenAsync(TokenTypes.PersonalAccessToken); return(false); } return(true); }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest request, ILogger log) { var token = new GitHubToken(_uiTestToken, string.Empty, "Bearer"); return(new ContentResult { Content = JsonConvert.SerializeObject(token), StatusCode = (int)HttpStatusCode.OK, ContentType = "application/json" }); }
private void ValidateToken(GitHubToken token) { if (token == null) { throw new ApplicationException("Token cannot be null."); } if (!token.IsValid) { throw new ApplicationException("Token is not valid and cannot be saved."); } }
public async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req, FunctionContext functionContext) { var log = functionContext.GetLogger <GetTestToken>(); foreach (var testTokenPair in _testTokenDictionary) { log.LogInformation($"Retrieving Rate Limits for {testTokenPair.Key}"); var timeout = TimeSpan.FromSeconds(2); var cancellationTokenSource = new CancellationTokenSource(timeout); try { _gitHubApiStatusService.SetAuthenticationHeaderValue(new AuthenticationHeaderValue("bearer", testTokenPair.Value)); var gitHubApiRateLimits = await _gitHubApiStatusService.GetApiRateLimits(cancellationTokenSource.Token).ConfigureAwait(false); log.LogInformation($"\tREST API Rate Limit: {gitHubApiRateLimits.RestApi.RemainingRequestCount}"); log.LogInformation($"\tGraphQL API Rate Limit: {gitHubApiRateLimits.GraphQLApi.RemainingRequestCount}"); if (gitHubApiRateLimits.RestApi.RemainingRequestCount > 1000 && gitHubApiRateLimits.GraphQLApi.RemainingRequestCount > 1000) { var gitHubToken = new GitHubToken(testTokenPair.Value, GitHubConstants.OAuthScope, "Bearer"); var okResponse = req.CreateResponse(HttpStatusCode.OK); var gitHubTokenJson = JsonConvert.SerializeObject(gitHubToken); await okResponse.WriteStringAsync(gitHubTokenJson).ConfigureAwait(false); return(okResponse); } log.LogInformation($"\tAPI Limits for {testTokenPair.Key} too low"); log.LogInformation($"\tRetrieving next token"); } catch (Exception e) { log.LogError(e, e.Message); var errorResponse = req.CreateResponse(HttpStatusCode.InternalServerError); await errorResponse.WriteStringAsync(e.ToString()).ConfigureAwait(false); return(errorResponse); } } ; var notFoundResponse = req.CreateResponse(HttpStatusCode.NotFound); await notFoundResponse.WriteStringAsync("No Valid GitHub Token Found").ConfigureAwait(false); return(notFoundResponse); }
private async Task <GitHubClient> CreateClientAsync(GitHubToken token, string acceptHeader = null) { if (token is null) { throw new ArgumentNullException(nameof(token)); } GitHubClient gitHubClient = null; if (token.Enabled) { #pragma warning disable CA2000 // Dispose objects before losing scope // this is a factory methods - we must not dispose the http client instance here as this would make the client unusable for the caller var gitHubHttpClient = new GitHubInterceptor(new HttpClientAdapter(HttpMessageHandlerFactory.CreateDefault), acceptHeader); #pragma warning restore CA2000 // Dispose objects before losing scope if (token.AccessTokenExpired) { gitHubClient = new GitHubClient(new Connection(GitHubConstants.ProductHeader, gitHubHttpClient) { Credentials = new Credentials(token.GetPemToken(), Octokit.AuthenticationType.Bearer) }); try { var accessToken = await gitHubClient.GitHubApps .CreateInstallationToken(long.Parse(token.InstallationId, CultureInfo.InvariantCulture)) .ConfigureAwait(false); token.AccessToken = accessToken.Token; token.AccessTokenExpires = accessToken.ExpiresAt.UtcDateTime; token = await TokenClient .SetAsync(token, true) .ConfigureAwait(false); } catch { // swallow } } gitHubClient = token.AccessTokenExpired ? null : new GitHubClient(new Connection(GitHubConstants.ProductHeader, gitHubHttpClient) { Credentials = new Credentials(token.AccessToken) }); } return(gitHubClient); }
internal static string GetPemToken(this GitHubToken token) { var utcNow = DateTime.UtcNow; using var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(GetRSAParameters()); return(JWT.Encode(new Dictionary <string, object> { { "iat", ToUtcSeconds(utcNow) }, { "exp", ToUtcSeconds(utcNow.AddMinutes(1)) }, { "iss", token.ApplicationId } }, rsa, JwsAlgorithm.RS256));
public async Task SaveGitHubTokenTest_InvalidScopes() { //Arrange var scopes_MissingOrg = HttpUtility.UrlEncode("public_repo read:user"); var gitHubToken = new GitHubToken(_token, scopes_MissingOrg, _tokenType); var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService <GitHubUserService>(); //Act await gitHubUserService.SaveGitHubToken(gitHubToken).ConfigureAwait(false); var retrievedToken = await gitHubUserService.GetGitHubToken().ConfigureAwait(false); //Assert Assert.AreEqual(GitHubToken.Empty.AccessToken, retrievedToken.AccessToken); Assert.AreEqual(GitHubToken.Empty.Scope, retrievedToken.Scope); Assert.AreEqual(GitHubToken.Empty.TokenType, retrievedToken.TokenType); }
static async Task Main(string[] args) { var gitHubGraphQLApiService = new GitHubGraphQLApiService(); var githubToken = new GitHubToken(_token, "bearer"); //Get All Repositories await foreach (var repositories in gitHubGraphQLApiService.GetRepositories("brminnick", githubToken, CancellationToken.None).ConfigureAwait(false)) { foreach (var repository in repositories) { System.Console.WriteLine(repository); } } //Get One Repository var gitTrendsRepository = await gitHubGraphQLApiService.GetRepository("brminnick", "GitTrends", githubToken, CancellationToken.None).ConfigureAwait(false); System.Console.WriteLine(gitTrendsRepository); }
public async Task SaveGitHubTokenTest() { //Arrange var gitHubToken = new GitHubToken(_token, _scope, _tokenType); var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService <GitHubUserService>(); //Act await gitHubUserService.SaveGitHubToken(gitHubToken).ConfigureAwait(false); var retrievedToken = await gitHubUserService.GetGitHubToken().ConfigureAwait(false); //Assert Assert.AreEqual(_token, retrievedToken.AccessToken); Assert.AreEqual(_scope, retrievedToken.Scope); Assert.AreEqual(_tokenType, retrievedToken.TokenType); Assert.AreEqual(gitHubToken.AccessToken, retrievedToken.AccessToken); Assert.AreEqual(gitHubToken.Scope, retrievedToken.Scope); Assert.AreEqual(gitHubToken.TokenType, retrievedToken.TokenType); }
private bool SetValue <T>(string key, T value) { GitHubToken token = value as GitHubToken; ValidateToken(token); // gather data. string tokenKey = GetTokenKeyFromTokenType(token.TokenType); ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; object existingValue = settings.Values[tokenKey]; // set data. if (existingValue == null) { settings.Values.Add(key, value); } else { settings.Values[key] = value; } return(true); }
public static bool IsEmpty(this GitHubToken gitHubToken) => gitHubToken.AccessToken == string.Empty && gitHubToken.Scope == string.Empty && gitHubToken.TokenType == string.Empty;
protected static string GetGitHubBearerTokenHeader(GitHubToken token) => $"{token.TokenType} {token.AccessToken}";
async Task <IActionResult> IAdapterAuthorize.HandleCallbackAsync(DeploymentScope deploymentScope, HttpRequest request, IAuthorizationEndpoints authorizationEndpoints) { if (deploymentScope is null) { throw new ArgumentNullException(nameof(deploymentScope)); } if (request is null) { throw new ArgumentNullException(nameof(request)); } if (authorizationEndpoints is null) { throw new ArgumentNullException(nameof(authorizationEndpoints)); } var json = await request .ReadJsonAsync() .ConfigureAwait(false); var appId = json .SelectToken("installation.app_id")? .ToString(); var token = await TokenClient .GetAsync <GitHubToken>(deploymentScope) .ConfigureAwait(false); if (token?.ApplicationId?.Equals(appId, StringComparison.OrdinalIgnoreCase) ?? false) { var action = json .SelectToken("action")? .ToString(); switch (action) { case "created": token.InstallationId = json .SelectToken("installation.id")? .ToString(); break; case "deleted": token = new GitHubToken(deploymentScope); break; case "suspend": token.Suspended = true; break; case "unsuspend": token.Suspended = false; break; default: token = null; break; } if (token is not null) { _ = await TokenClient .SetAsync(token) .ConfigureAwait(false); return(new OkResult()); } } return(new NotFoundResult()); }
public Task <bool> SetTokenAsync(GitHubToken token) { return(SetSettingAsync(GetTokenKeyFromTokenType(token.TokenType), token)); }