I'm using ASP.NET Core 2.1 with the new Identity framwork from .NET. The regular Authorization
attribute works as long as no role specific role is requested.
Do I need some extending / customized policies to use roles? Below is a minimized sample of my code:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// Does not change anything
// services.AddAuthorization();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
HomeController.cs
public async Task<IActionResult> Index()
{
if (!await _roleManager.RoleExistsAsync("Admin"))
{
await _roleManager.CreateAsync(new IdentityRole("Admin"));
}
var user = await _userManager.FindByEmailAsync("danny.meier@tpcag.ch");
if (!await _userManager.IsInRoleAsync(user, "Admin"))
{
await _userManager.AddToRoleAsync(user, "Admin");
await _userManager.UpdateAsync(user);
}
return View();
}
[Authorize]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[Authorize(Roles = "Admin")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}