【问题标题】:How to set up Ocelot with claims (roles)?如何使用声明(角色)设置 Ocelot?
【发布时间】:2019-09-16 10:04:55
【问题描述】:

我正在尝试在 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(这是一个 MVC 项目,具有用于登录/注册/等的默认 UI)并尝试访问以下 URL:

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

但是,我总是返回 403 状态。当我删除 RouteClaimsRequirement 时,它可以工作。所以我想我遗漏了一些东西,但我不知道RouteClaimsRequirement 的文档有点稀疏。

有人可以帮我吗?谢谢。

【问题讨论】:

  • 你有办法解决这个问题吗?我也有同样的问题。
  • 不,但我设法让 Azure API 管理服务启动并运行。我们将我们的应用程序专门托管在 Azure 上,因此集成效果很好。
  • 好的,谢谢。我发布了一条回复(如下),我认为它很好地回答了这个问题。随意标记为正确;)干杯!

标签: .net-core claims ocelot


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多