.net核心身份2.1角色授权不起作用

cdu*_*rth 9 asp.net-core-mvc asp.net-core asp.net-core-identity

我已经在2.1之前多次实现了基于角色的身份验证。按照步骤搭建新的2.1身份。

我扩展了IdentityUser模型以添加其他字段,登录工作正常,并且存在新字段。

startup.cs配置服务包含

         services.AddDefaultIdentity<AppUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

我播下了角色

         IdentityRole role = new IdentityRole();
         role.Name = "Administrator";
         IdentityResult roleResult = roleManager.
         CreateAsync(role).Result;
Run Code Online (Sandbox Code Playgroud)

然后创建一个用户并添加到角色中

        AppUser user = new AppUser();
        user.UserName = "Admin";
        user.Email = "admin@admin.com";
        user.Name = "Administrator";
        user.LockoutEnabled = false;
        user.EmailConfirmed = true;

        IdentityResult result = userManager.CreateAsync(user, "password").Result;

        if (result.Succeeded)
        {
            userManager.AddToRoleAsync(user, "Administrator").Wait();
        }
Run Code Online (Sandbox Code Playgroud)

一切都成功了,数据库看起来还不错(AspNetUserRoles有链接)

但是,用角色装饰控制器将始终返回未经授权的状态

       [Authorize(Roles = "Administrator")]
Run Code Online (Sandbox Code Playgroud)

但是,带有[Authorize](无角色)的简单登录检查将起作用。

如何解决此问题/最简单的方法来合并源代码,以便我可以逐步/调试[Authorize]代码?

bau*_*aur 8

在我的 ASP.NET Core 3(预览版)+ Angular 的情况下,解决方案是在AddAuthentication

services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
});
Run Code Online (Sandbox Code Playgroud)


itm*_*nus 7

怎么修

但是,用角色装饰控制器将始终返回未经授权的状态

  [Authorize(Roles = "Administrator")]
Run Code Online (Sandbox Code Playgroud)

这是的版本中的已知错误2.1。在这里查看问题

我遵循使用HaoK和C-BERBER建议的旧api的建议,现在它可以完美工作了。

这是我的DbContext

public class ApplicationDbContext : IdentityDbContext<AppUser,IdentityRole,string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

使用旧式api配置身份:

services.AddIdentity<AppUser, IdentityRole>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddDefaultUI()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

最后,注销并重新登录,它现在将按预期工作。

如何调试源代码

我猜您不想调试AuthorizeAttribe自身,因为它是在编译时处理的。如果您打算调试AuthorizeFilter,则可以按照以下步骤操作:

点击Tools-> Options->Debugging

  1. General取消选择Enable Just My Code在Visual Studio
  2. 选择 Enable Source Link Support
  3. Symbols,请确保微软符号服务器选择

现在,您可以调试源代码了。但是,由于筛选器的工作方式,您需要在MVC之前设置一个断点。我只是设置了一个虚拟的中间件,该中间件将在MVC路由器处理程序之前进行:

在此处输入图片说明

调试截图AuthorizeFiler

在此处输入图片说明