I have follow piece of net core2 code in my Admin.cshtml.cs page:
[Authorize(Roles = "Admin")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPostLoadDataAsync()
{
try
{
if (ModelState.IsValid)
{
var curuser = await userManager.GetUserAsync(this.User);
(bool hasRoleUser, bool hasRoleAdmin) q1 = (
await userManager.IsInRoleAsync(curuser, RoleUser),
await userManager.IsInRoleAsync(curuser, RoleAdmin));Note that using the Authorize attribute in the controller it works as expected while in Page I can only authorize entire page but for methods it seems not work.
where the method should authorized only for an Admin role but as can be seen fromimage of the debug the 2th role grabbed by q1 is false showing that IsInRole for "Admin" is false. How this can happen ? I have missed some authorization engine activation in my startup procedure that follow ?
namespace webapp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite().AddDbContext<DBContext>(options => options.UseNpgsql(connectionString));
services.AddIdentity<User, Role>(options =>
{
options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<DBContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.Events = new CookieAuthenticationEvents()
{
OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>((a) =>
{
var task = Task.Run(new Action(() =>
{
;
}));
return task;
})
};
});
services
.AddMvc(config =>
{
})
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Admin");
});
services.AddAuthorization();
services.AddSingleton<IEmailSender, EmailSender>();
services.AddSingleton<IUserRepository, UserRepository>();
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
UserManager<User> userManager,
DBContext ctx)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
}
}