Exemplo n.º 1
0
        public static async Task <string> GetGithubAppTokenAsync(ApplicationConfig appConfig, string privateKey)
        {
            if (appConfig == null)
            {
                throw new ArgumentNullException(nameof(appConfig), "Parameter cannot be null.");
            }
            if (string.IsNullOrEmpty(privateKey))
            {
                throw new ArgumentNullException(nameof(privateKey), "Parameter cannot be null or empty.");
            }

            try
            {
                var utcNow  = DateTime.UtcNow;
                var payload = new Dictionary <string, object>
                {
                    { "iat", ToUtcSeconds(utcNow) },
                    { "exp", ToUtcSeconds(utcNow.AddSeconds(600)) }, // 10 minutes is the maximum time allowed
                    { "iss", appConfig.GitHubAppId } // The GitHub App Id
                };

                var jwtToken = JwtHelper.CreateEncodedJwtToken(privateKey, payload);

                // Pass the JWT as a Bearer token to Octokit.net
                var appClient = new GitHubClient(new ProductHeaderValue(appConfig.GitHubAppName))
                {
                    Credentials = new Credentials(jwtToken, AuthenticationType.Bearer)
                };

                // Get a list of installations for the authenticated GitHub App and installationID for the GitHub Organization
                var installations = await appClient.GitHubApps.GetAllInstallationsForCurrent();

                var id = installations.Where(installation => installation.Account.Login == appConfig.GitHubOrganization)
                         .FirstOrDefault().Id;

                // Create an Installation token for the GitHub Organization installation instance
                var response = await appClient.GitHubApps.CreateInstallationToken(id);

                string token = response.Token;

                return(token);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }