侧边栏

Ocelot中文文档-认证(转)

原文地址:https://www.cnblogs.com/snaildev/articles/9151703.html

为了验证ReRoutes并随后使用Ocelot的任何基于声明的功能,如授权或使用令牌中的值修改请求。 用户必须像往常一样在他们的Startup.cs中注册认证服务,但他们给每个注册提供了一个方案(认证提供商密钥),例如

1
2
3
4
5
6
7
8
9
public void ConfigureServices(IServiceCollection services)
{
    var authenticationProviderKey = "TestKey";
 
    services.AddAuthentication()
        .AddJwtBearer(authenticationProviderKey, x =>
        {
        });
}

在此示例中,TestKey是此提供程序已注册的方案。 然后,我们将其映射到配置中的ReRoute,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"ReRoutes": [{
        "DownstreamHostAndPorts": [
            {
                "Host""localhost",
                "Port": 51876,
            }
        ],
        "DownstreamPathTemplate""/",
        "UpstreamPathTemplate""/",
        "UpstreamHttpMethod": ["Post"],
        "ReRouteIsCaseSensitive"false,
        "DownstreamScheme""http",
        "AuthenticationOptions": {
            "AuthenticationProviderKey""TestKey",
            "AllowedScopes": []
        }
    }]

当Ocelot运行时,它会查看此ReRoutes的AuthenticationOptions.AuthenticationProviderKey并检查是否存在给定密钥注册的身份验证提供程序。 如果没有,那么Ocelot不会启动,如果有的话ReRoute将在执行时使用该提供者。

如果ReRoute配置了认证,Ocelot在执行认证中间件时将调用与其相关的任何验证方案。 如果请求认证失败,Ocelot返回http状态码401。

JWT令牌

如果您想使用JWT令牌进行身份验证,例如Auth0等提供商,您可以使用正常的方式注册你的身份验证中间件,

网关程序需要需要引用Nuget包:Microsoft.AspNetCore.Authentication.JwtBearer

Program:

 
 
 
 
 
 
 
 
 
 
 

ar audienceConfig = builder.Configuration.GetSection("Audience");

var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Secret"]));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = audienceConfig["Iss"],
ValidateAudience = true,
ValidAudience = audienceConfig["Aud"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};

builder.Services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = "TestKey";
})
.AddJwtBearer("TestKey", x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = tokenValidationParameters;
});

builder.Services.AddOcelot(builder.Configuration);
builder.WebHost.UseUrls("http://*:9000");

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();// UseAuthentication();

app.UseOcelot().Wait();
app.UseAuthorization();

然后将身份验证提供程序密钥映射到配置中的Routes,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"Routes": [{
        "DownstreamHostAndPorts": [
            {
                "Host""localhost",
                "Port": 51876,
            }
        ],
        "DownstreamPathTemplate""/",
        "UpstreamPathTemplate""/",
        "UpstreamHttpMethod": ["Post"],
        "ReRouteIsCaseSensitive"false,
        "DownstreamScheme""http",
        "AuthenticationOptions": {
            "AuthenticationProviderKey""TestKey",
            "AllowedScopes": []
        }
    }]

实际的Api服务中Program

 

var audienceConfig = builder.Configuration.GetSection("Audience");
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Secret"]));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = audienceConfig["Iss"],
ValidateAudience = true,
ValidAudience = audienceConfig["Aud"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};

builder.Services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = "TestKey";
})
.AddJwtBearer("TestKey", x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = tokenValidationParameters;
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();

 

 

Identity Server 承载令牌

为了使用IdentityServer承载令牌,请按照惯例在ConfigureServices 中使用方案(密钥)注册您的IdentityServer服务。 如果您不明白如何操作,请访问IdentityServer文档。

网关服务Program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void ConfigureServices(IServiceCollection services)
{
    var authenticationProviderKey = "TestKey";
    var options = o =>
        {
            o.Authority = "https://whereyouridentityserverlives.com";
            o.ApiName = "api";
            o.SupportedTokens = SupportedTokens.Both;
            o.ApiSecret = "secret";
        };
 
    services.AddAuthentication()
        .AddIdentityServerAuthentication(authenticationProviderKey, options);
 
    services.AddOcelot();
}

然后将身份验证提供程序密钥映射到配置中的Routes,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"Routes": [{
        "DownstreamHostAndPorts": [
            {
                "Host""localhost",
                "Port": 51876,
            }
        ],
        "DownstreamPathTemplate""/",
        "UpstreamPathTemplate""/",
        "UpstreamHttpMethod": ["Post"],
        "ReRouteIsCaseSensitive"false,
        "DownstreamScheme""http",
        "AuthenticationOptions": {
            "AuthenticationProviderKey""TestKey",
            "AllowedScopes": []
        }
    }]

api服务中Program:

复制代码
 1 IdentityServerConfig identityServerConfig = new IdentityServerConfig();
 2 builder.Configuration.Bind("IdentityServerConfig", identityServerConfig);
 3 builder.WebHost.UseUrls("http://*:8001");
 4 builder.Services.AddAuthentication(identityServerConfig.IdentityScheme)
 5     .AddIdentityServerAuthentication(options =>
 6     {
 7         options.RequireHttpsMetadata = false;
 8         options.Authority = $"http://{identityServerConfig.IP}:{identityServerConfig.Port}";
 9         options.ApiName = identityServerConfig.ResourceName;
10     }
11     );
12 var app = builder.Build();
13 
14 // Configure the HTTP request pipeline.
15 if (app.Environment.IsDevelopment())
16 {
17     app.UseSwagger();
18     app.UseSwaggerUI();
19 }
20 
21 app.UseAuthentication();
22 app.UseAuthorization();
复制代码

 

允许的范围

如果将范围添加到AllowedScopes,Ocelot将获得类型范围的所有用户声明(从令牌中),并确保用户具有列表中的所有范围。

这是一种基于范围限制对ReRoute访问的方式。

如需转载,请在显眼处标明本文链接,谢谢。
posted @   我有我的骄傲  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示