asp.net-core - 将用户分配给 asp.net core 中的角色将返回此错误“您无权访问此资源”。
问题描述
我创建了一个使用个人用户帐户的新 asp.net 核心 Web 应用程序。现在我正在尝试实现一个简单的角色分配方案。
所以我注册了一个测试用户,该用户被添加到 AspNetUser 表中:-
然后我在 AspNetRole 中添加一个名为“Administrator”的新角色:-
然后我添加了一个新的 AspNetUserRole 来将用户链接到角色:-
然后我在 About 操作方法上添加了以下 Authorize 注释:-
[Authorize(Roles = "Administrator")]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
但是当我尝试使用用户访问 About 操作方法时,我收到了这个错误:-
您无权访问此资源。”
编辑
这是startup.cs
我没有修改过的,所以我认为它包含内置代码:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication2.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApplication2
{
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.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>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// 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?}");
});
}
}
}
解决方案
AspNetUserRole
我猜您在创建 user 后手动在 table 中创建角色和链接角色。请不要忘记注销用户并再次登录,因此角色声明将获取/更新新添加的角色。
推荐阅读
- c - 在此 C 代码中,哪个部分的性能成本最高?
- python-3.x - 标准化后将嵌套列表从列表中取出
- macos - 作为 root 时如何访问不同用户的 NSUserDefaults?
- git - Github页面,帖子不可见
- python - 为什么我在拉动 df.index 时没有得到正确的索引?
- arrays - 如何在 swift4 中初始化字典,键为字符串,值为二维数组?
- php - 从数组中,使用 PHP 根据键值对项目进行分组
- python - 熊猫在 groupby 之后获得累积总和
- reporting-services - 如果我们不能在“页眉或页脚”中包含表格标题,如何在多个页面中显示表格标题
- java - How to solve stack memory problems?