internal string EncodeToken(ClaimsPrincipal user, StoredTokenData token)
        {
            byte[] encoded = GitHubTokenEncoder.EncodeToken(new GitHubTokenData(token.UserId,
                                                                                token.TokenId,
                                                                                token.Expiration,
                                                                                _resolver.GetAccessToken(user)));

            byte[] prot = _dataProtector.Protect(encoded);

            return(Convert.ToBase64String(prot));
        }
Exemplo n.º 2
0
        private void AddServices(IServiceCollection services)
        {
            services.AddMvc().WithRazorPagesRoot("/Pages").AddRazorPagesOptions(o => o.Conventions.AuthorizeFolder("/", MsftAuthorizationPolicyName).AllowAnonymousToPage("/Index"));
            services.AddApplicationInsightsTelemetry(Configuration.GetSection("ApplicationInsights").Bind);
            services.AddAuthentication()
            .AddGitHubOAuth(Configuration.GetSection("GitHubAuthentication"), GitHubScheme)
            .AddScheme <UserTokenOptions, GitHubUserTokenHandler>("github-token", o => { })
            .AddCookie(IdentityConstants.ApplicationScheme,
                       o =>
            {
                o.ExpireTimeSpan     = TimeSpan.FromDays(7);
                o.SlidingExpiration  = true;
                o.Cookie.IsEssential = true;
                o.LoginPath          = "/signin";
                o.LogoutPath         = "/signout";
                o.ReturnUrlParameter = "r";
                o.Events             = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async ctx =>
                    {
                        GitHubClaimResolver resolver =
                            ctx.HttpContext.RequestServices.GetRequiredService <GitHubClaimResolver>();
                        ClaimsIdentity identity = ctx.Principal.Identities.FirstOrDefault();
                        identity?.AddClaims(await resolver.GetMembershipClaims(resolver.GetAccessToken(ctx.Principal)));
                    }
                };
            })
            ;
            services.AddAzureTableTokenStore(o => Configuration.GetSection("AzureTableTokenStore").Bind(o));
            services.AddAuthorization(
                options =>
            {
                options.AddPolicy(
                    MsftAuthorizationPolicyName,
                    policy =>
                {
                    policy.RequireAuthenticatedUser();
                    if (!Env.IsDevelopment())
                    {
                        policy.RequireRole("github:team:dotnet/dnceng", "github:team:dotnet/bots-high");
                    }
                });
            });

            services.AddScoped <SimpleSigninMiddleware>();
            services.AddGitHubTokenProvider();
            services.AddSingleton <IInstallationLookup, InMemoryCacheInstallationLookup>();
            services.AddContextAwareAuthenticationScheme(o =>
            {
                o.SelectScheme = p => p.StartsWithSegments("/api") ? "github-token" : IdentityConstants.ApplicationScheme;
            });
            services.AddSingleton <GitHubJwtFactory>();
        }
Exemplo n.º 3
0
        private void AddServices(IServiceCollection services)
        {
            services.AddRazorPages(o =>
            {
                o.Conventions
                .AuthorizeFolder("/", MsftAuthorizationPolicyName)
                .AllowAnonymousToPage("/Index")
                .AllowAnonymousToPage("/Status")
                .AllowAnonymousToPage("/Error");
                o.RootDirectory = "/Pages";
            });

            services.AddControllers()
            .AddGitHubWebHooks();

            services.AddApplicationInsightsTelemetry(Configuration.GetSection("ApplicationInsights").Bind);
            services.Configure <LoggerFilterOptions>(o =>
            {
                // This handler is added by 'AddApplicationInsightsTelemetry' above and hard limits
                // and reporting below "warning", which basically kills all logging
                // Remove it, we already configured the filters in Program.cs
                o.Rules.Remove(o.Rules.FirstOrDefault(r =>
                                                      r.ProviderName ==
                                                      "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider"));
            });

            services.AddAuthentication("contextual")
            .AddPolicyScheme("contextual", "Contextual Scheme",
                             o => { o.ForwardDefaultSelector = context =>
                                    {
                                        if (context.Request.Path.StartsWithSegments("/api"))
                                        {
                                            return("github-token");
                                        }

                                        return(IdentityConstants.ApplicationScheme);
                                    }; })
            .AddGitHubOAuth(Configuration.GetSection("GitHubAuthentication"), GitHubScheme)
            .AddScheme <UserTokenOptions, GitHubUserTokenHandler>("github-token", o => { })
            .AddCookie(IdentityConstants.ApplicationScheme,
                       o =>
            {
                o.ExpireTimeSpan     = TimeSpan.FromDays(7);
                o.SlidingExpiration  = true;
                o.Cookie.IsEssential = true;
                o.LoginPath          = "/signin";
                o.LogoutPath         = "/signout";
                o.ReturnUrlParameter = "r";
                o.Events             = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async ctx =>
                    {
                        GitHubClaimResolver resolver =
                            ctx.HttpContext.RequestServices.GetRequiredService <GitHubClaimResolver>();
                        ClaimsIdentity identity = ctx.Principal.Identities.FirstOrDefault();
                        identity?.AddClaims(await resolver.GetMembershipClaims(resolver.GetAccessToken(ctx.Principal)));
                    },
                };
            })
            .AddExternalCookie()
            ;
            services.AddAzureTableTokenStore(o => Configuration.GetSection("AzureTableTokenStore").Bind(o));
            services.AddAuthorization(
                options =>
            {
                options.AddPolicy(
                    MsftAuthorizationPolicyName,
                    policy =>
                {
                    policy.RequireAuthenticatedUser();
                    if (!Env.IsDevelopment())
                    {
                        policy.RequireRole(GitHubClaimResolver.GetTeamRole("dotnet", "dnceng"), GitHubClaimResolver.GetTeamRole("dotnet", "bots-high"));
                    }
                });
            });
            services.AddKustoIngest(options => Configuration.GetSection("Kusto").Bind(options));

            services.AddScoped <SimpleSigninMiddleware>();
            services.AddGitHubTokenProvider();
            services.AddSingleton <IInstallationLookup, InMemoryCacheInstallationLookup>();

            services.AddSingleton <ZenHubClient>();
            services.AddSingleton <IGitHubApplicationClientFactory, GitHubApplicationClientFactory>();
            services.AddSingleton <IGitHubClientFactory, GitHubClientFactory>();
        }
Exemplo n.º 4
0
        private void AddServices(IServiceCollection services)
        {
            services.AddRazorPages(o =>
            {
                o.Conventions
                .AuthorizeFolder("/", MsftAuthorizationPolicyName)
                .AllowAnonymousToPage("/Index")
                .AllowAnonymousToPage("/Status")
                .AllowAnonymousToPage("/Routes")
                .AllowAnonymousToPage("/Error");
                o.RootDirectory = "/Pages";
            });

            services.AddControllers()
            .AddGitHubWebHooks();

            services.AddApplicationInsightsTelemetry(Configuration.GetSection("ApplicationInsights").Bind);
            services.Configure <LoggerFilterOptions>(o =>
            {
                // This handler is added by 'AddApplicationInsightsTelemetry' above and hard limits
                // and reporting below "warning", which basically kills all logging
                // Remove it, we already configured the filters in Program.cs
                o.Rules.Remove(o.Rules.FirstOrDefault(r =>
                                                      r.ProviderName ==
                                                      "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider"));

                // These two categories log a lot of noise at "Information", let's raise them to warning
                o.Rules.Add(new LoggerFilterRule(null, "Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter", LogLevel.Warning, null));
                o.Rules.Add(new LoggerFilterRule(null, "Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter", LogLevel.Warning, null));
            });

            services.AddAuthentication("contextual")
            .AddPolicyScheme("contextual", "Contextual Scheme",
                             o => { o.ForwardDefaultSelector = context =>
                                    {
                                        if (context.Request.Path.StartsWithSegments("/api/webhooks"))
                                        {
                                            return("nothing");
                                        }
                                        if (context.Request.Path.StartsWithSegments("/api"))
                                        {
                                            return("github-token");
                                        }

                                        return(IdentityConstants.ApplicationScheme);
                                    }; })
            .AddGitHubOAuth(Configuration.GetSection("GitHubAuthentication"), GitHubScheme)
            .AddScheme <NothingOptions, NothingHandler>("nothing", o => { })
            .AddScheme <UserTokenOptions, GitHubUserTokenHandler>("github-token", o => { })
            .AddCookie(IdentityConstants.ApplicationScheme,
                       o =>
            {
                o.ExpireTimeSpan     = TimeSpan.FromMinutes(30);
                o.SlidingExpiration  = true;
                o.Cookie.IsEssential = true;
                o.LoginPath          = "/signin";
                o.LogoutPath         = "/signout";
                o.ReturnUrlParameter = "r";
                o.Events             = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async ctx =>
                    {
                        GitHubClaimResolver resolver =
                            ctx.HttpContext.RequestServices.GetRequiredService <GitHubClaimResolver>();
                        ClaimsIdentity identity = ctx.Principal.Identities.FirstOrDefault();
                        identity?.AddClaims(await resolver.GetMembershipClaims(resolver.GetAccessToken(ctx.Principal)));
                    },
                };
            })
            .AddExternalCookie()
            ;
            services.AddAzureTableTokenStore(o => Configuration.GetSection("AzureTableTokenStore").Bind(o));
            services.AddAuthorization(
                options =>
            {
                options.AddPolicy(
                    MsftAuthorizationPolicyName,
                    policy =>
                {
                    policy.RequireAuthenticatedUser();
                    if (!Env.IsDevelopment())
                    {
                        policy.RequireRole(GitHubClaimResolver.GetTeamRole("dotnet", "dnceng"), GitHubClaimResolver.GetTeamRole("dotnet", "bots-high"));
                    }
                });
            });
            services.AddKustoIngest(options => Configuration.GetSection("Kusto").Bind(options));

            services.AddScoped <SimpleSigninMiddleware>();
            services.AddGitHubTokenProvider();
            services.AddSingleton <IInstallationLookup, InMemoryCacheInstallationLookup>();

            services.AddSingleton <ZenHubClient>();
            services.AddSingleton <IGitHubApplicationClientFactory, GitHubApplicationClientFactory>();
            services.AddSingleton <IGitHubClientFactory, GitHubClientFactory>();
            services.AddSingleton <ITimelineIssueTriage, TimelineIssueTriage>();
            services.AddSingleton <ExponentialRetry>();
            services.AddSingleton <ISystemClock, SystemClock>();
            services.AddSingleton <Microsoft.Extensions.Internal.ISystemClock, Microsoft.Extensions.Internal.SystemClock>();
            services.AddHttpClient();
            services.AddHealthReporting(
                b =>
            {
                b.AddLogging();
                b.AddAzureTable((o, p) => o.WriteSasUri = p.GetRequiredService <IConfiguration>()["HealthTableUri"]);
            });

            services.AddScoped <ITeamMentionForwarder, TeamMentionForwarder>();
        }