如何设置带有索赔(角色)的Ocelot?

时间:2019-04-26 21:44:36

标签: .net-core claims ocelot

我正在尝试在Api网关中设置Ocelot,但仍处于授权状态。我已经成功设置了声明,并且可以在控制器中对其进行授权。我向这样的用户添加了声明:

await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, configuration["InitialAdmin:Role"]));

然后我使用以下配置设置Ocelot:

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/home/user",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/home/user",
      "RouteClaimsRequirement": {
          "Role": "user"
      }
    },
    {
      "DownstreamPathTemplate": "/api/home/admin",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/api/home/admin",
      "RouteClaimsRequirement": {
        "Role": "SuperAdmin"
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:5000"
  }
}

这是我的ConfigureServices方法:

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.AddIdentity<CondatoUser, IdentityRole>(options =>
    {
        //Signin config
        options.SignIn.RequireConfirmedEmail = true;

        //Password config
        options.Password.RequiredLength = 8;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireLowercase = false;
        options.Password.RequireUppercase = false;

        //User config
        options.User.RequireUniqueEmail = true;
    })
    .AddDefaultUI()
    .AddEntityFrameworkStores<UserManagementDbContext>();
           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddOcelot(Configuration);
}

然后我登录此网关Api(这是一个具有默认UI的MVC项目,用于登录/注册/等),并尝试访问以下URL:

https://localhost:5000/api/home/admin

但是,我总是得到403状态。当我删除RouteClaimsRequirement时,它起作用了。因此,我想我缺少了一些东西,但是我不知道RouteClaimsRequirement的文档是多么稀疏。

有人可以帮我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

事实证明,使用ClaimTypes中的预定义System.Security.Claims无法做到这一点。这是由于(app)settings json解析无法处理字典键中的冒号(:)所致。请参阅Ocelot存储库上的this issue

解决方案是使用自定义声明类型,例如“角色”而不是System.Security.Claims.Role,其结果是“ http://schemas.microsoft.com/ws/2008/06/identity/claims/role