gpt4 book ai didi

asp.net-core - 如何检查数组中的 Claim 值或 Ocelot 网关中的任何值?

转载 作者:行者123 更新时间:2023-12-04 13:16:10 25 4
gpt4 key购买 nike

假设我有 2 个这样的端点

  1. 订单创建:需要在数组 ["order_create", "order_edit"]
  2. 中声明 order_perm
  3. 订单查询:只要求声明order_perm存在

在情况 1 中,我将上面的数组传递给 RouteClaimsRequirement,如下所示

"RouteClaimsRequirement": {
"order_perm": ["order_create", "order_edit"]
}

但它在应用程序启动时崩溃,在情况 2 中。我是这样设置的

"RouteClaimsRequirement": {
"order_perm": ""
}

但用户声明 "order_perm": "create_order" 授权失败。

RouteClaimsRequirement 是否支持这些用例?如果可以,我该怎么做?

最佳答案

我知道这是一个老问题,我最近陷入了同样的问题,经过大量谷歌搜索后,我在 github 上找到了这个解决方案。 .当我使用 Ocelot 16.0.1 时,我更改了一些内容以使其适用于我。ocelot.json文件

{
"DownstreamPathTemplate": "/api/{everything}/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "80"
}
],
"UpstreamPathTemplate": "/web/{everything}/{everything}",
"UpstreamHttpMethod": [ "GET" ],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Authkey",
"AllowedScopes": []
},
"RouteClaimsRequirement": {
"Role": "Admin , SuperAdmin"
},
"SwaggerKey": "myapi"

},

配置方法

public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//your code here
var configration = new OcelotPipelineConfiguration
{
AuthorisationMiddleware=async (ctx, next) =>
{
if (this.Authorize(ctx))
{
await next.Invoke();
}
else
{
ctx.Items.SetError(new UnauthorisedError($"Fail to authorize"));
}
}
};
//your code here
await app.UseOcelot(configration);
}

授权方式

 private bool Authorize(HttpContext ctx)
{
if (ctx.Items.DownstreamRoute().AuthenticationOptions.AuthenticationProviderKey == null) return true;
else
{

bool auth = false;
Claim[] claims = ctx.User.Claims.ToArray<Claim>();
Dictionary<string, string> required = ctx.Items.DownstreamRoute().RouteClaimsRequirement;
Regex reor = new Regex(@"[^,\s+$ ][^\,]*[^,\s+$ ]");
MatchCollection matches;

Regex reand = new Regex(@"[^&\s+$ ][^\&]*[^&\s+$ ]");
MatchCollection matchesand;
int cont = 0;
foreach (KeyValuePair<string, string> claim in required)
{
matches = reor.Matches(claim.Value);
foreach (Match match in matches)
{
matchesand = reand.Matches(match.Value);
cont = 0;
foreach (Match m in matchesand)
{
foreach (Claim cl in claims)
{
if (cl.Type == claim.Key)
{
if (cl.Value == m.Value)
{
cont++;
}
}
}
}
if (cont == matchesand.Count)
{
auth = true;
break;
}
}
}
return auth;
}
}

关于asp.net-core - 如何检查数组中的 Claim 值或 Ocelot 网关中的任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60300349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com