public void ConfigureAuthServices(IServiceCollection services, WebApiConfiguration configuration) { /* Configure sharing cookies between application. * See https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?tabs=aspnetcore2x for details */ services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(configuration.Web.CookieKeyRingDirectory)) .SetApplicationName("ulearn"); services.ConfigureApplicationCookie(options => { options.Cookie.Name = configuration.Web.CookieName; options.Cookie.Expiration = TimeSpan.FromDays(14); options.Cookie.Domain = configuration.Web.CookieDomain; options.LoginPath = "/users/login"; options.LogoutPath = "/users/logout"; options.Events.OnRedirectToLogin = context => { /* Replace standard redirecting to LoginPath */ context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return(Task.CompletedTask); }; options.Events.OnRedirectToAccessDenied = context => { /* Replace standard redirecting to AccessDenied */ context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Task.CompletedTask); }; }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = configuration.Web.Authentication.Jwt.Issuer, ValidAudience = configuration.Web.Authentication.Jwt.Audience, IssuerSigningKey = JwtBearerHelpers.CreateSymmetricSecurityKey(configuration.Web.Authentication.Jwt.IssuerSigningKey) }; }); services.AddAuthorization(options => { options.AddPolicy("Instructors", policy => policy.Requirements.Add(new CourseRoleRequirement(CourseRoleType.Instructor))); options.AddPolicy("CourseAdmins", policy => policy.Requirements.Add(new CourseRoleRequirement(CourseRoleType.CourseAdmin))); options.AddPolicy("SysAdmins", policy => policy.RequireRole(new List <string> { LmsRoleType.SysAdmin.GetDisplayName() })); foreach (var courseAccessType in Enum.GetValues(typeof(CourseAccessType)).Cast <CourseAccessType>()) { var policyName = courseAccessType.GetAuthorizationPolicyName(); options.AddPolicy(policyName, policy => policy.Requirements.Add(new CourseAccessRequirement(courseAccessType))); } }); }