我不能授予管理员访问用户管理页面的权限
我正在研究ASP .Net Core,但目前仍处于停滞状态。我已经检查了代码,确保相同的名称引用了类,并测试了Startup.cs服务的不同配置,但找不到方法。 我正在遵循名为“ The Little ASP.NET Core Book”的教程。我被困在“角色授权”这一点上
这是我的控制器:
namespace ASPDotNetCoreTodo.Controllers
{
//La configuración de la propiedad Roles en el atributo
//[Authorize] garantizará que el usuario tenga que iniciar sesión y se le
//asigne el rol de Administrador para poder ver la página.
[Authorize(Roles = Constants.AdministratorRole)]
public class ManageUsersController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public ManageUsersController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
var admins = (await _userManager
.GetUsersInRoleAsync("Administrator"))
.ToArray();
var everyone = await _userManager.Users
.ToArrayAsync();
var model = new ManageUsersViewModel
{
Administrators = admins,
Everyone = everyone
};
return View(model);
}
}
模型:
namespace ASPDotNetCoreTodo.Models
{
public class ManageUsersViewModel
{
public ApplicationUser[] Administrators { get; set; }
public ApplicationUser[] Everyone { get; set; }
}
}
Startup.cs文件:
namespace ASPDotNetCoreTodo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
// services.AddIdentity<ApplicationUser, IdentityRole>()
// .AddEntityFrameworkStores<ApplicationDbContext>()
// .AddDefaultTokenProviders();
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
;
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;
});
//Añadimos servicio de aplicaciones
services.AddScoped<ITodoItemService, TodoItemService>();
services.AddAuthentication();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
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?}");
});
}
}
重点是,我在获取ManageUsersController的授权时遇到了麻烦。当在类上方使用[Authorize(Roles = Constants.AdministratorRole)]行时,即使使用相同的常量来过滤数据库和菜单中的用户帐户,我的测试管理员帐户也无法访问该页面。并按预期将它们放在表中(在ManageUsers视图内)。
我将.NET Core更新为2.2,并将项目更新为...
无论如何,这是我的GitHub:https://github.com/erniker/LearningASPNETCoreAndTests
答案 0 :(得分:0)
您是否具有管理员登录功能?或验证用户身份的方法?
如果不是这样,这是为什么的原因,因为在从cookie进行身份验证时(因为您使用过cookie身份验证),应用程序试图访问Role = Constants.AdministratorRole的功能,但是在身份验证尝试检查当前用户时,将发现没有经过身份验证的用户,该用户将不允许客户端访问页面。
请考虑以下操作:
首先在startup.cs中添加身份验证后添加cookie策略(显然顺序很重要),并将身份验证方案设置为cookie身份验证,以告知应用程序使用cookie中的身份验证。我通常使用以下内容:
//add authentication service with an encrypted cookie
services.AddAuthentication(options => {
options.DefaultScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options => {
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.Cookie.Name = "ClientCookie";
});
考虑添加登录功能以将用户认证为admin,以便该应用可以正确认证用户。我用这样的东西:
public class AuthController : Controller
{
private readonly string authScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
[HttpPost("[action]")]
public IActionResult Login([FromBody]JObject body)
{
//Gets inputs from Request Body
string userName = body[UserModelConstants.Username].ToString();
string password = body[UserModelConstants.Password].ToString();
//use the username and password to check if the user is ok or not
//then get his claim from database or fill them yourself but make sure to have a role type claim with the value "Administrator" for the admin user
List<Claim> claims = getUserClaims();
//now you have to create the user identity and principle
ClaimsIdentity CI = new ClaimsIdentity(claims, Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme,
ClaimTypes.Name, ClaimTypes.Role);
ClaimsPrincipal CP = new ClaimsPrincipal(CI);
return SignIn(CP, authScheme);//sign in the user so it can be checked when the user is being authorized to access the function.
}
每次我创建一个项目时,这对我来说都很好,但是也许您想根据自己的喜好对它进行一些调整,或者选择其他类型的身份验证。
答案 1 :(得分:0)
好吧,由于任何原因,将.net Core升级到2.2版本之后,似乎仍然失败,但是,从VS2019运行项目而不是VSCode,看来该项目很好用。