[英]Access Denied for Admin User
我一直在嘗試將策略添加到Web應用程序的管理區域中,並且已將我的管理員用戶和管理員角色同時添加到我的AspNetUsers
, AspNetRoles
和AspNetUserRoles
表中,但是我無法驗證已簽名的用戶是否和管理員一樣。
AspNetUsers
表
Id | UserName | NormalizedUserName | Email | NormalizedEmail
_______________________________________________________________________________________________
123 | WebAdmin | WEBADMIN | admin@mysite.com | ADMIN@MYSITE.COM
AspNetRoles
表
Id | Name | NormalizedName
_______________________________________
123 | Admin | ADMIN
_______________________________________
321 | User | USER
AspNetUserRoles
表
UserId | RoleId
______________________
123 | 123
我已經將Identity
包含在Startup
類的ConfirgureServices
中
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">Services to configure</param>
public void ConfigureServices(IServiceCollection services)
{
// Regular Cookie Policy stuff
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;
});
// Mailing service setup
services.AddScoped<SmtpClient>((serviceProvider) =>
{
return new SmtpClient
{
Host = this.Configuration.GetValue<string>("Email:Smtp:Host"),
Port = this.Configuration.GetValue<int>("Email:Smtp:Port"),
UseDefaultCredentials = false,
Credentials = new NetworkCredential(
this.Configuration.GetValue<string>("Email:Smtp:Username"),
this.Configuration.GetValue<string>("Email:Smtp:Password")),
EnableSsl = true
};
});
// Connect to the Database
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<WebSiteContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
// Identity Stuff
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
// Configure Authorization
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Authorization
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
}
我也在我的Configure
方法中使用了所有這些
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">App being configured</param>
/// <param name="env">Environment the app is running in</param>
/// <param name="context">Injected <see cref="DbContext"/></param>
/// <param name="userManager">Injected <see cref="UserManager{TUser}"/></param>
/// <param name="roleManager">Injected <see cref="RoleManager{TRole}"/></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext context, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
// Set up the usings
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
// Seed the Database on Startup
Seeder.SeedDb(context, userManager, roleManager);
// Use MVC
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我的管理員部分的ManageController
控制器具有Authorize
聲明
/// <summary>
/// ManageController - Controller for Managing Admin Stuff
/// </summary>
[Area("admin")]
[Route("admin/[controller]")]
[Authorize(Policy = "RequireAdminRole")]
public class ManageController : Controller
{
/// <summary>
/// Private instance of the <see cref="EmailViewModel"/> class
/// </summary>
private EmailViewModel emailViewModel;
private SmtpClient smtpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ManageController"/> class
/// </summary>
/// <param name="smtpClient"></param>
public ManageController(SmtpClient smtpClient)
{
this.smtpClient = smtpClient;
}
/// <summary>
/// HomePage for the admin management area
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
return View();
}
}
但是,當我以WebAdmin身份登錄並導航到admin/Manage
區域時,出現以下錯誤:
拒絕訪問-您無權訪問此資源
在NET Core中檢查角色時,我是否缺少某些東西?
我已經解決了這個問題。 問題在於配置身份服務。 我需要使用AddIdentity<IdentityUser, IdentityRole>()
而不是AddDefaultIdentity<IdentityUser>()
我變了
// Identity Stuff
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
至
// Identity Stuff
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
而且有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.