首页 > 解决方案 > dotnet core IdentityServer 添加角色

问题描述

请提前接受我的道歉。这个话题遍布整个互联网,包括 SO,我在几天内查看了数百篇文章,但我似乎无法跨过这最后一道障碍。

我正在使用带有 Identity 的开箱即用的 dotnet react 项目。(dotnet 5.0)。我还添加了 Microsoft 登录。

身份验证工作得很好。对于任一登录类型,我都可以使用 [Authorize] 保护资源。

但是尽我所能,每次添加角色时都会出现403错误;即[授权(角色=“管理员”)]

我添加了一些虚拟用户来尝试一下,然后添加了一些代码来添加角色。这是代码:

public async Task SetupRoles()
    {
        string[] roleNames = { "Admin", "Office" };
        
        foreach (var roleName in roleNames)
        {
            var roleExist = await _roleManager.RoleExistsAsync(roleName);
            if (!roleExist)
            {
                var newRole = new IdentityRole(roleName);
                //await _roleManager.CreateAsync(newRole);
                //await _roleManager.AddClaimAsync(newRole, new Claim(ClaimTypes.Role, roleName));       
            }
        }
        var user = await _userManager.FindByEmailAsync("me@me.com");
        if (user != null)
        {
            var result = await _userManager.AddToRoleAsync(user, "Admin");
            await _userManager.AddToRoleAsync(user, "Office");
            //await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "Admin"));
            //await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "Office"));
        }
    }

我在尝试添加失败的代码中留下了注释。这段代码在标准 MVC 项目中完美运行,因为我从那里复制了它!

我添加了一个来自 SO 的 IProfileService 类:

public class MyProfileService : IProfileService
{
    public MyProfileService()
    { }

    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        //get role claims from ClaimsPrincipal 
        var claims = context.Subject.FindAll(JwtClaimTypes.Role);
        
        //add your role claims 
        context.IssuedClaims.AddRange(claims);
        return Task.CompletedTask;
    }

    public Task IsActiveAsync(IsActiveContext context)
    {
        // await base.IsActiveAsync(context);
        return Task.CompletedTask;
    }
}

我在 ConfigureServices 中的 Startup.cs 看起来像这样:

       services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDbContext <OfficeManagerContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        
        services.AddDatabaseDeveloperPageExceptionFilter();

        services.AddDefaultIdentity<ApplicationUser>(options => 
                      options.SignIn.RequireConfirmedAccount = true)
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();


        services.AddIdentityServer()
          .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
          .AddProfileService<MyProfileService>();

        services.AddAuthentication()
            .AddIdentityServerJwt()

            .AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId = Configuration["AzureAd:ClientId"];
                microsoftOptions.ClientSecret = Configuration["AzureAd:ClientSecret"];
            });

        services.AddAuthorization();
        ...

这是在 API 调用中发送的令牌:

{
  "nbf": 1627003083,
  "exp": 1627006683,
  "iss": "https://localhost:44340",
  "aud": "OfficeManager.AlphaAPI",
  "client_id": "OfficeManager.Alpha",
  "sub": "*******-b0ac3839766c",
  "auth_time": 1627003080,
  "idp": "local",
  "role": [
    "Office",
    "Admin"
  ],
  "jti": "***",
  "sid": "***",
  "iat": 1627003083,
  "scope": [
    "OfficeManager.AlphaAPI",
    "openid",
    "profile"
  ],
  "amr": [
    "pwd"
  ]
}

最后,这是控制器,即股票 WeatherForecastController

[ApiController]
[Authorize(Roles = "Admin")]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    ....

重复一遍,如果我删除 Authorize 的 Roles 部分,它工作正常。使用角色,我收到 403 错误。

画面越来越模糊!!!请帮忙 !!!

我已经合并了我能找到的所有内容,并且从所有方面来看,这应该可以工作,但显然我是个白痴并且遗漏了一些东西。

谢谢

标签: .net-corejwtidentityserver4claims-based-identity

解决方案


推荐阅读