c# - [Authorize]对ocelot网关后面的内部服务没有用吗?
问题描述
鉴于我已经根据ocelot 文档设置了 ocelot 并与 IdentityServer4 集成,我是否应该从这些内部服务中删除[Authorize]
属性和身份验证相关代码(例如UseAuthentication
中间件)?Startup
如果删除
[Authorize]
相关代码,这些内部服务如何获得User.Claims
?以及如何保护这些服务免受来自内部的线程的影响?如果保留
[Authroize]
相关代码,那么将 IdentityServer4 与 Ocelot 集成有什么意义?我能看到的唯一好处是防止无效请求到达内部服务。
长篇大论:
我设置了 Ocelot 网关并与 IdentityServer4 集成。我所有的内部 Api 服务(例如 ServiceA、ServiceB)都在网关后面。
为了保证内部服务的安全,我AuthenticationOptions
按照 ocelot 官方文档中的说明进行了设置。
例如 ocelot 网关配置:
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{version}/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"LoadBalancerOptions": {
"Type": "LeastConnection"
},
"UpstreamPathTemplate": "/serviceA/api/{version}/{everything}",
"UpstreamHttpMethod": [],
"AuthenticationOptions": {
"AuthenticationProviderKey": "ApiGwAuth",
"AllowedScopes": []
}
}
]
}
public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication()
.AddJwtBearer("ApiGwAuth", x =>
{
x.Authority = Configuration["IdentityServiceSettings:Url"];
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidAudiences = new[] { "serviceA", "serviceB" }
};
});
services.AddOcelot(Configuration);
}
需要保护的服务A:
[Authorize]
[HttpGet]
public ActionResult GetProtectedInfo()
{
// e.g.
return Ok(User.Claims.Select(itm => itm.ToString()));
}
User.Claims
如果[Authorize]
删除了相关代码,如何获取?
解决方案
如果您删除 UseAuthentication(),您将丢失 User.Identity。如果要生成 User.Identity 但没有 Ocelot 通过的 JWT 验证,请尝试以下操作:
配置服务
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = CreateTokenValidationParameters();
});
配置
app.UseAuthentication();
和
private TokenValidationParameters CreateTokenValidationParameters() //we ignore token validation because gateway validates it
{
var result = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = false,
SignatureValidator = delegate (string token, TokenValidationParameters parameters)
{
var jwt = new JwtSecurityToken(token);
return jwt;
},
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
result.RequireSignedTokens = false;
return result;
}
推荐阅读
- javascript - 使用 Express 路由错误请求呼叫时出现意外错误
- python - 在Python中将一长串位作为半字节转换为十进制
- python-3.x - 名称“模型”未定义 Keras
- google-apps-script - 发送带有附加电子表格的电子邮件
- python - Python 2.7 (urllib2)。如何使用 SSL HTTPS 代理?
- reactjs - React-如何防止登录后返回登录页面?
- java - 如何在JAVA中解决SQL“'字段列表'中的未知列'c'”,而实际上没有语法问题
- swift - iOS 应用程序 - 收到推送通知时在屏幕上显示自定义交互视图,如系统警报
- javascript - 获取JS中两个小时之间的时间范围有多少时间
- java - 如何跳过访问(重复)值的索引?