Example #1
0
        public static async Task <GitHubClient> GetInstallationClient(long installationId)
        {
            // Use GitHubJwt library to create the GitHubApp Jwt Token using our private certificate PEM file
            var generator = new GitHubJwtFactory(
                new EnvironmentVariablePrivateKeySource("PrivateKey"),
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = Convert.ToInt32(Environment.GetEnvironmentVariable("GitHubAppId")),
                ExpirationSeconds = 600     // 10 minutes is the maximum time allowed
            }
                );
            var jwtToken = generator.CreateEncodedJwtToken();

            var productHeaderValue = Environment.GetEnvironmentVariable("GitHubProductHeader");
            // Use the JWT as a Bearer token
            var appClient = new GitHubClient(new ProductHeaderValue(productHeaderValue))
            {
                Credentials = new Credentials(jwtToken, AuthenticationType.Bearer)
            };
            // Get the current authenticated GitHubApp
            var app = await appClient.GitHubApps.GetCurrent();

            // Create an Installation token for Insallation Id
            var response = await appClient.GitHubApps.CreateInstallationToken(installationId);

            // Create a new GitHubClient using the installation token as authentication
            var installationClient = new GitHubClient(new ProductHeaderValue(productHeaderValue))
            {
                Credentials = new Credentials(response.Token)
            };

            return(installationClient);
        }
Example #2
0
        public async Task <GitHubClient> CreateAsync()
        {
            // See: https://octokitnet.readthedocs.io/en/latest/github-apps/ for details.

            var appId      = Convert.ToInt32(_configuration["GitHubAppId"]);
            var privateKey = _configuration["GitHubAppPrivateKey"];

            var privateKeySource = new PlainStringPrivateKeySource(privateKey);
            var generator        = new GitHubJwtFactory(
                privateKeySource,
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = appId,
                ExpirationSeconds = 8 * 60     // 600 is apparently too high
            });
            var token = generator.CreateEncodedJwtToken();

            var client = CreateForToken(token, AuthenticationType.Bearer);

            var installations = await client.GitHubApps.GetAllInstallationsForCurrent();

            var installation            = installations.Single();
            var installationTokenResult = await client.GitHubApps.CreateInstallationToken(installation.Id);

            return(CreateForToken(installationTokenResult.Token, AuthenticationType.Oauth));
        }
Example #3
0
        private string GetAppToken()
        {
            var generator = new GitHubJwtFactory(
                new StringPrivateKeySource(Options.PrivateKey),
                new GitHubJwtFactoryOptions {
                AppIntegrationId = Options.GitHubAppId, ExpirationSeconds = 600
            });

            return(generator.CreateEncodedJwtToken());
        }
        /// <inheritdoc />
        public IGitHubClient CreateAppClient()
        {
            //use app auth, max expiration time
            var jwtFac = new GitHubJwtFactory(this, new GitHubJwtFactoryOptions {
                AppIntegrationId = gitHubConfiguration.AppID, ExpirationSeconds = 600
            });
            var jwt    = jwtFac.CreateEncodedJwtToken();
            var client = CreateBareClient();

            client.Credentials = new Credentials(jwt, AuthenticationType.Bearer);
            return(client);
        }
        private string GetAppToken(int gitHubAppId, IPrivateKeySource privateKeySource)
        {
            var generator = new GitHubJwtFactory(
                privateKeySource,
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = gitHubAppId,
                ExpirationSeconds = 600
            });

            return(generator.CreateEncodedJwtToken());
        }
        private string GetAppToken(int gitHubAppId, IPrivateKeySource privateKeySource)
        {
            var generator = new GitHubJwtFactory(
                privateKeySource,
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId = gitHubAppId,
                // Due to clock drift, use 9:30 to avoid "'Expiration time' claim ('exp') is too far in the future"
                ExpirationSeconds = 570
            });

            return(generator.CreateEncodedJwtToken());
        }
        /// <inheritdoc />
        public string GetToken(int expirationSeconds = 600)
        {
            var readToEnd = _privateKeySource.GetPrivateKeyReader().ReadToEnd();

            var generator = new GitHubJwtFactory(
                _privateKeySource,
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = _appIntegrationId,
                ExpirationSeconds = expirationSeconds
            }
                );

            return(generator.CreateEncodedJwtToken());
        }
Example #8
0
        private static GitHubClient GetClient()
        {
            var generator = new GitHubJwtFactory(
                new FilePrivateKeySource(PathToPem),
                new GitHubJwtFactoryOptions {
                AppIntegrationId  = 97880,
                ExpirationSeconds = 530
            });

            var jwt = generator.CreateEncodedJwtToken();

            return(new GitHubClient(new ProductHeaderValue("GitHubCLI"))
            {
                Credentials = new Credentials(jwt, AuthenticationType.Bearer)
            });
        }
Example #9
0
        private Octo.GitHubClient GetClient()
        {
            var generator = new GitHubJwtFactory(
                new StringPrivateKeySource(Pem),
                new GitHubJwtFactoryOptions {
                AppIntegrationId  = 97880,
                ExpirationSeconds = 530
            });

            var jwt = generator.CreateEncodedJwtToken();

            return(new Octo.GitHubClient(new Octo.ProductHeaderValue("GiraBot"))
            {
                Credentials = new Octo.Credentials(jwt, Octo.AuthenticationType.Bearer)
            });
        }
Example #10
0
        private GitHubClient CreateForAppCore()
        {
            // See: https://octokitnet.readthedocs.io/en/latest/github-apps/ for details.

            var privateKeySource = new PlainStringPrivateKeySource(AppPrivateKey);
            var generator        = new GitHubJwtFactory(
                privateKeySource,
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = AppId,
                ExpirationSeconds = 600
            });

            var token = generator.CreateEncodedJwtToken();

            return(CreateForToken(token, AuthenticationType.Bearer));
        }
Example #11
0
        static async Task Main(string[] args)
        {
            var pathToPemFile = args[0];

            var generator = new GitHubJwtFactory(
                new FilePrivateKeySource(pathToPemFile),
                new GitHubJwtFactoryOptions {
                AppIntegrationId = 97880, ExpirationSeconds = 600
            });

            var jwt = generator.CreateEncodedJwtToken();

            // Авторизация в GitHub API как GitHub App.
            var client = new GitHubClient(new ProductHeaderValue("GiraBot"))
            {
                Credentials = new Credentials(jwt, AuthenticationType.Bearer)
            };

            // Чтобы найти установку именно для тестирования.
            var installationId = int.Parse(args[1]);

            // Авторизация в GitHub API как конкретный GitHub App Installation.
            var installationClient = new GitHubClient(new ProductHeaderValue($"GiraBotInstallation-{installationId}"))
            {
                Credentials = new Credentials((await client.GitHubApps.CreateInstallationToken(installationId)).Token)
            };

            //var repo = (await installationClient.GitHubApps.Installation.GetAllRepositoriesForCurrent()).Repositories.Single();
            var project = await installationClient.Repository.Project.GetAllForOrganization("Microsoft");

            //var repoIssues = await installationClient.Issue.GetAllForRepository(
            //	repo.Id,
            //	new RepositoryIssueRequest { State = ItemStateFilter.All });

            WriteLine("Processed issues:");
            //foreach (var issue in repoIssues)
            //	WriteLine($"\t{issue.Number}. {issue.Title} (state: {issue.State}).");

            // Считаем число закрытых issues, которые будут закрытыми задачами.
            //var closedIssuesCount = repoIssues.Count(issue => issue.State == ItemState.Closed);

            //WriteLine($"Sprint Burndown is {closedIssuesCount}/{repoIssues.Count}.");

            // Чтобы консольное окно не закрывалось сразу после вывода.
            ReadKey();
        }
Example #12
0
        public void CreateEncodedJwtToken_FromString_ShouldNotFail()
        {
            // Arrange
            var privateKeySource = new StringPrivateKeySource(File.ReadAllText("envvar.pem"));
            var options          = new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = 6837,
                ExpirationSeconds = 600 // 10 minutes maximum
            };
            var factory = new GitHubJwtFactory(privateKeySource, options);

            // Act
            var token = factory.CreateEncodedJwtToken();

            // Assert
            Assert.IsNotNull(token);
            Console.WriteLine(token);
        }
        private string GetJwtToken()
        {
            GitHubAppOptions settings = _settings.Value;

            var factoryOptions = new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = settings.ApplicationId, // The GitHub App Id
                ExpirationSeconds = 9 * 60                  // 10 minutes is the maximum time allowed, but because exp claim is absolute time, lets have it 9 minutes to cover time skew
            };

            // TODO: refactor into TryXXX(factoryOptions)
            if (!string.IsNullOrEmpty(settings.PrivateKey.KeyString))
            {
                // use `awk '{printf "%s\\n", $0}' private-key.pem` to store the pem data
                var privateKey = settings.PrivateKey.KeyString.Replace("\n", Environment.NewLine, StringComparison.Ordinal);

                var generator = new GitHubJwtFactory(new StringPrivateKeySource(privateKey), factoryOptions);

                return(generator.CreateEncodedJwtToken());
            }
            else if (!string.IsNullOrEmpty(settings.PrivateKey.Base64))
            {
                byte[] data          = Convert.FromBase64String(settings.PrivateKey.Base64);
                string decodedString = Encoding.UTF8.GetString(data);

                var generator = new GitHubJwtFactory(new StringPrivateKeySource(decodedString), factoryOptions);

                return(generator.CreateEncodedJwtToken());
            }
            else if (!string.IsNullOrEmpty(settings.PrivateKey.File))
            {
                var generator = new GitHubJwtFactory(new FilePrivateKeySource(settings.PrivateKey.File), factoryOptions);

                return(generator.CreateEncodedJwtToken());
            }
            else
            {
                throw new InvalidOperationException("Not configured GitHubAppSettings.PrivateKey");
            }
        }
Example #14
0
        public async Task <GitHubClient> CreateAsync(bool localDev)
        {
            // See: https://octokitnet.readthedocs.io/en/latest/github-apps/ for details.

            var    appId      = Convert.ToInt32(_configuration["GitHubAppId"]);
            string privateKey = null;

            if (localDev)
            {
                privateKey = File.ReadAllText(_configuration["PemFilePath"]);
            }
            else
            {
                AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
                KeyVaultClient            keyVaultClient            = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                SecretBundle secretBundle = await keyVaultClient.GetSecretAsync(_configuration["AppSecretUri"]).ConfigureAwait(false);

                privateKey = secretBundle.Value;
            }

            var privateKeySource = new PlainStringPrivateKeySource(privateKey);
            var generator        = new GitHubJwtFactory(
                privateKeySource,
                new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = appId,
                ExpirationSeconds = 8 * 60     // 600 is apparently too high
            });
            var token = generator.CreateEncodedJwtToken();

            var client = CreateForToken(token, AuthenticationType.Bearer);

            var installations = await client.GitHubApps.GetAllInstallationsForCurrent();

            var installationTokenResult = await client.GitHubApps.CreateInstallationToken(long.Parse(_configuration["InstallationId"]));

            return(CreateForToken(installationTokenResult.Token, AuthenticationType.Oauth));
        }
Example #15
0
        private static IGitHubClient ConstructGitHubClientWithPrivateKey(IConfiguration configuration, string privateKey)
        {
            var privateKeySource = new StringPrivateKeySource(
                privateKey);

            var tokenFactory = new GitHubJwtFactory(
                privateKeySource,
                new GitHubJwtFactoryOptions()
            {
                AppIntegrationId = int.Parse(
                    configuration["GitHub:PullDog:AppIdentifier"],
                    CultureInfo.InvariantCulture),
                ExpirationSeconds = 60 * 5
            });

            var token = tokenFactory.CreateEncodedJwtToken();

            return(new GitHubClient(new ProductHeaderValue("pull-dog"))
            {
                Credentials = new Credentials(
                    token,
                    AuthenticationType.Bearer)
            });
        }
Example #16
0
        public void CreateEncodedJwtToken_FromEnvVar_ShouldNotFail()
        {
            // Arrange
            var privateKeyName   = Guid.NewGuid().ToString("N");
            var privateKeySource = new EnvironmentVariablePrivateKeySource(privateKeyName);
            var options          = new GitHubJwtFactoryOptions
            {
                AppIntegrationId  = 6837,
                ExpirationSeconds = 600 // 10 minutes maximum
            };
            var factory = new GitHubJwtFactory(privateKeySource, options);

            using (new EnvironmentVariableScope(privateKeyName))
            {
                Environment.SetEnvironmentVariable(privateKeyName, File.ReadAllText("envvar.pem"));

                // Act
                var token = factory.CreateEncodedJwtToken();

                // Assert
                Assert.IsNotNull(token);
                Console.WriteLine(token);
            }
        }