Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何验证用户';用户使用标识登录时的角色_C#_Asp.net_Asp.net Core_Asp.net Identity - Fatal编程技术网

C# 如何验证用户';用户使用标识登录时的角色

C# 如何验证用户';用户使用标识登录时的角色,c#,asp.net,asp.net-core,asp.net-identity,C#,Asp.net,Asp.net Core,Asp.net Identity,大家早上好,向大家问好 当用户使用标识登录时,如何验证其角色? 第一步寄存器 第二步,登录,但当我尝试访问具有“管理员”权限的视图时,它会显示“访问被拒绝。您无权访问此资源。” 我希望每个注册的用户都具有管理员角色 我做错了什么 [Authorize(Roles = "Admin")] public IActionResult About() { ViewData["Message"] = "Your application description page."; return

大家早上好,向大家问好

当用户使用标识登录时,如何验证其角色? 第一步寄存器 第二步,登录,但当我尝试访问具有“管理员”权限的视图时,它会显示“访问被拒绝。您无权访问此资源。” 我希望每个注册的用户都具有管理员角色

我做错了什么

[Authorize(Roles = "Admin")]
public IActionResult About()
{
    ViewData["Message"] = "Your application description page.";

    return View();
}
//DBContext
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace test.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });
            modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "User", NormalizedName = "User".ToUpper() });
            base.OnModelCreating(modelBuilder);
        }
        public DbSet<Test> Test { get; set; }
    }
}




//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    //DataBase Connection
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    // Library Identity
    services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
    // IdentityOptions
    services.Configure<IdentityOptions>(options =>
    {
        // Default SignIn settings.
        options.SignIn.RequireConfirmedEmail = false;
        options.SignIn.RequireConfirmedPhoneNumber = false;
        // Password settings.
        options.Password.RequireDigit = false;
        options.Password.RequireLowercase = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
        options.Password.RequiredLength = 4;
        options.Password.RequiredUniqueChars = 0;

        // Lockout settings.
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = true;

        // User settings.
        options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
        options.User.RequireUniqueEmail = false; // ojo con esto
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication(); //  Use Authentication
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
// Register.cs
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
        var result = await _userManager.CreateAsync(user, Input.Password);
        if (result.Succeeded)
        {
            var UserRole = "Admin"; // Admin Role
            var x = await _userManager.AddToRoleAsync(user, UserRole); // Assignment of the role to the registered user
            _logger.LogInformation("User created a new account with password.");
        }
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
    }
    // If we got this far, something failed, redisplay form
    return Page();
}
[Authorize(Roles=“Admin”)]
公共IActionResult About()
{
ViewData[“消息”]=“您的应用程序描述页。”;
返回视图();
}
//DBContext
使用Microsoft.AspNetCore.Identity;
使用Microsoft.AspNetCore.Identity.EntityFrameworkCore;
使用Microsoft.EntityFrameworkCore;
名称空间测试模型
{
公共类ApplicationDbContext:IdentityDbContext
{
公共应用程序DBContext(DbContextOptions选项):基本(选项){}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity();
modelBuilder.Entity();
基于模型创建(modelBuilder);
}
公共数据库集测试{get;set;}
}
}
//Startup.cs
public void配置服务(IServiceCollection服务)
{
//数据库连接
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“DefaultConnection”);
//图书馆身份
services.AddDefaultIdentity().AddRoles()
.AddEntityFrameworkStores();
//识别选项
配置(选项=>
{
//默认登录设置。
options.SignIn.RequireConfirmedEmail=false;
options.SignIn.RequireConfirmedPhoneNumber=false;
//密码设置。
options.Password.RequireDigit=false;
options.Password.RequireLowercase=false;
options.Password.RequireNonAlphanumeric=false;
options.Password.RequireUppercase=false;
options.Password.RequiredLength=4;
options.Password.RequiredUniqueChars=0;
//锁定设置。
options.Lockout.DefaultLockoutTimeSpan=TimeSpan.FromMinutes(5);
options.locket.MaxFailedAccessAttempts=5;
options.locket.AllowedForNewUsers=true;
//用户设置。
options.User.AllowedUserName字符=
“ABCDEFGHIJKLMNOPQRSTUVXYZABCDFGHIJKLMNOPQRSTUVXYZ0123456789-.@+”;
options.User.RequireUniqueEmail=false;//ojo con esto
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();//使用身份验证
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
//Register.cs
公共异步任务OnPostAsync(字符串returnUrl=null)
{
returnUrl=returnUrl??Url.Content(“~/”);
if(ModelState.IsValid)
{
var user=newapplicationuser{UserName=Input.Email,Email=Input.Email};
var result=await\u userManager.CreateAsync(用户,输入,密码);
if(result.successed)
{
var UserRole=“Admin”;//管理员角色
var x=await _userManager.AddToRoleAsync(user,UserRole);//将角色分配给注册用户
_logger.LogInformation(“用户使用密码创建了一个新帐户”);
}
foreach(result.Errors中的变量错误)
{
AddModelError(string.Empty,error.Description);
}
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回页();
}

这是2.1版本中的一个已知错误。看这里

我听从了他的建议,现在它工作得完美无缺

使用旧式api配置标识:

services.AddIdentity<ApplicationUser, IdentityRole>()
       .AddRoleManager<RoleManager<IdentityRole>>()
       .AddDefaultUI()
       .AddDefaultTokenProviders()
       .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity()
.AddRoleManager()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores();

这是2.1版本中的一个已知错误。看这里

我听从了他的建议,现在它工作得完美无缺

使用旧式api配置标识:

services.AddIdentity<ApplicationUser, IdentityRole>()
       .AddRoleManager<RoleManager<IdentityRole>>()
       .AddDefaultUI()
       .AddDefaultTokenProviders()
       .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity()
.AddRoleManager()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores();
。向下滚动到该部分的末尾。。向下滚动到该部分的末尾。