private void ConfigureAuthentication(IServiceCollection services) { var authenticationSettings = Configuration .GetSection(nameof(Authentication)) .Get <Authentication>(); services.AddIdentity <ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128) .AddEntityFrameworkStores <BiddingContext>() .AddDefaultTokenProviders(); services.AddDbContext <BiddingContext>( options => options.UseSqlServer( Configuration.GetConnectionString("BiddingBaltic"), sqlOptions => sqlOptions.EnableRetryOnFailure() ) ); //Register the Permission policy handlers services.AddSingleton <IAuthorizationPolicyProvider, AuthorizationPolicyProvider>(); services.AddSingleton <IAuthorizationHandler, PermissionHandler>(); services .AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.Cookie.Name = Configuration["Cookies:Session"]; options.SlidingExpiration = true; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.LoginPath = "/sign-in"; options.Cookie.IsEssential = true; options.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = (context) => { if (context.Request.Path.StartsWithSegments("/api")) { context.Response.Clear(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; return(Task.CompletedTask); } context.Response.Redirect(context.RedirectUri); return(Task.CompletedTask); } }; }) .AddOpenIdConnect(Configuration["Authentication:Scheme"], options => { // Set the authority to your Auth0 domain options.Authority = Configuration["Authentication:Authority"]; // Configure the Auth0 Client ID and Client Secret options.ClientId = Configuration["Authentication:ClientId"]; options.ClientSecret = Configuration["Authentication:ClientSecret"]; // Set response type to code options.ResponseType = "code"; options.SaveTokens = true; // Configure the scope options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("email"); options.CallbackPath = new PathString("/" + Configuration["Authentication:CallbackPath"]); // Configure the Claims Issuer to be Auth0 options.ClaimsIssuer = Configuration["Authentication:Issuer"]; options.Events = new OpenIdConnectEvents { // handle the logout redirection OnRedirectToIdentityProviderForSignOut = (context) => { string logoutUri = $"https://{Configuration["Authentication:Domain"]}/v2/logout?client_id={Configuration["Authentication:ClientId"]}"; string postLogoutUri = context.Properties.RedirectUri; if (postLogoutUri.IsNotSpecified() == false) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = context.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } context.Response.Redirect(logoutUri); context.HandleResponse(); return(Task.CompletedTask); }, OnTokenValidated = async(context) => { JwtPayload payload = context.SecurityToken.Payload; if (payload.IsNotSpecified()) { throw new WebApiException(HttpStatusCode.Unauthorized, UserErrorMessage.CanNotSignIn); } ApplicationUser user = new ApplicationUser() { Email = payload["email"].ToString(), IdentityId = payload["sub"].ToString(), EmailConfirmed = Convert.ToBoolean(payload["email_verified"]), UserName = payload["email"].ToString() }; UsersService usersService = services.BuildServiceProvider().GetService <UsersService>(); ApplicationUser userDetails = await usersService.HandleUserLoginAsync(user).ConfigureAwait(true); // setup user claims context.Principal.AddIdentity(await SetupUserClaimsAsync(services, userDetails).ConfigureAwait(true)); // setup profile cookie string userProfileCookieJSON = SetupUserProfileCookie(userDetails); // setup profile cookie options CookieOptions userProfileCookieOptions = SetupUserProfileCookieOptions(); context.Response.Cookies.Append("BIDPROFILE", userProfileCookieJSON, userProfileCookieOptions); } }; }); }