IdentityServer4 配置负载均衡

本文探讨了使用IdentityServer4实现授权服务负载均衡时遇到的问题及解决方案。详细介绍了影响access_token生成的因素,如scope、lifetime等,并解释了如何正确设置issuername以确保负载均衡下多个授权服务的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果使用 IdentityServer4 做授权服务的负载均衡,默认情况下是不可以的,比如有两个授权服务站点,一个资源服务绑定其中一个授权服务(Authority配置),如果通过另外一个授权服务获取access_token,然后拿这个access_token去访问资源服务,会报 401 未授权错误,为什么?原因在这:

By default an access token will contain claims about the scope, lifetime (nbf and exp), the client ID (client_id) and the issuer name (iss).

归纳一下,生成access_token受影响的因素:

scope(授权范围):服务包含在 scope 内,生成的access_token,才能访问本服务。
lifetime(生命周期):过期的access_token,无效访问。
client ID (client_id):不同的客户端 ID,生成不同对应的access_token。
issuer name (iss):翻译过来“发行者名称”,类似于主机名。
RSA 加密证书(补充):不同的加密证书,生成不同对应的access_token。
要让负载均衡下的两个授权服务,可以正常使用的话,需要确保两台授权服务以上五种因素完全一致,除了 issuer name (iss),其他因素都是一样的。

IdentityServer4 怎么设置 issuer name (iss)呢?答案是通过IssuerUri:

IssuerUri:Set the issuer name that will appear in the discovery document and the issued JWT tokens. It is recommended to not set this property, which infers the issuer name from the host name that is used by the clients, If not set, the issuer name is inferred from the request.
说明中不建议我们进行设置,默认情况下,IdentityServer4 会从客户端的主机名中获取,可以认为,默认情况下,issuer name(IssuerUri)就是授权服务的主机名(比如http://10.9.1.1:5000)。

手动设置IssuerUri代码:

var builder = services.AddIdentityServer(x => x.IssuerUri = "http://111.12.2.21:8000"); //slb 地址
资源服务授权配置修改:

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://111.12.2.21:8000", //slb 地址
ApiName = "trade_refund",
RequireHttpsMetadata = false
});

获取access_token示例代码:

var client = new DiscoveryClient("http://111.12.2.21:8000"); //必须是 slb 地址,如果是单独的授权服务地址,会报错误(Value cannot be null. Parameter name: address)
client.Policy.RequireHttps = false;
var disco = await client.GetAsync();
var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);
var tokenResponse = tokenClient.RequestClientCredentialsAsync(scope);
var accessToken = tokenResponse.AccessToken;
通过 HTTP Post 获取access_token(不通过 slb,直接请求单独的授权服务),可以授权访问资源服务,获取access_token示例:

参考资料:

Protecting an API using Client Credentials
IdentityServer Options

引用:http://www.cnblogs.com/xishuai/p/identityserver4-slb.html

转载于:https://www.cnblogs.com/littlewrong/p/10653267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值