// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = _ => true; options.MinimumSameSitePolicy = SameSiteMode.Strict; }); services.AddControllersWithViews(); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }).AddCookie(options => { options.AccessDeniedPath = "/Home/Unauthorized"; options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = context => { var provider = _app.ApplicationServices; var scopeFactory = provider.GetRequiredService <IServiceScopeFactory>(); using var scope = scopeFactory.CreateScope(); var userService = scope.ServiceProvider.GetService <IUserService>(); var email = context.Principal?.Claims.GetEmail(); if (userService != null && !userService.IsValidSession(email).GetAwaiter().GetResult()) { context.RejectPrincipal(); } return(Task.CompletedTask); } }; }) .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options => { options.Authority = Configuration["VismaConnectUrl"]; options.ClientId = Configuration["ClientId"]; options.ClientSecret = Configuration["ClientSecret"]; options.ResponseType = "code"; options.Scope.Add("email"); options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }; options.Events = new OpenIdConnectEvents { OnUserInformationReceived = context => { var email = context?.User?.RootElement.GetProperty("email").GetString(); if (string.IsNullOrWhiteSpace(email)) { throw new UnauthorizedAccessException(); } var provider = _app.ApplicationServices; var scopeFactory = provider.GetRequiredService <IServiceScopeFactory>(); using var scope = scopeFactory.CreateScope(); var userService = scope.ServiceProvider.GetService <IUserService>(); userService?.SaveSession(email).GetAwaiter().GetResult(); return(Task.CompletedTask); }, }; }); services.AddApplicationInsightsTelemetry(); services.AddMvc(options => options.Filters.Add(new AuthorizeFilter())).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddDistributedMemoryCache(); services.AddSession(); _apiBuilder.BuildServices(services); }