IdentityServer4 配置负载均衡
如果使用 IdentityServer4 做授權(quán)服務(wù)的負(fù)載均衡,默認(rèn)情況下是不可以的,比如有兩個(gè)授權(quán)服務(wù)站點(diǎn),一個(gè)資源服務(wù)綁定其中一個(gè)授權(quán)服務(wù)(Authority配置),如果通過(guò)另外一個(gè)授權(quán)服務(wù)獲取access_token,然后拿這個(gè)access_token去訪(fǎng)問(wèn)資源服務(wù),會(huì)報(bào) 401 未授權(quán)錯(cuò)誤,為什么?原因在這:
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(授權(quán)范圍):服務(wù)包含在 scope 內(nèi),生成的access_token,才能訪(fǎng)問(wèn)本服務(wù)。
- lifetime(生命周期):過(guò)期的access_token,無(wú)效訪(fǎng)問(wèn)。
- client ID (client_id):不同的客戶(hù)端 ID,生成不同對(duì)應(yīng)的access_token。
- issuer name (iss):翻譯過(guò)來(lái)“發(fā)行者名稱(chēng)”,類(lèi)似于主機(jī)名。
- RSA 加密證書(shū)(補(bǔ)充):不同的加密證書(shū),生成不同對(duì)應(yīng)的access_token。
要讓負(fù)載均衡下的兩個(gè)授權(quán)服務(wù),可以正常使用的話(huà),需要確保兩臺(tái)授權(quán)服務(wù)以上五種因素完全一致,除了 issuer name (iss),其他因素都是一樣的。
IdentityServer4 怎么設(shè)置 issuer name (iss)呢?答案是通過(guò)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.
說(shuō)明中不建議我們進(jìn)行設(shè)置,默認(rèn)情況下,IdentityServer4 會(huì)從客戶(hù)端的主機(jī)名中獲取,可以認(rèn)為,默認(rèn)情況下,issuer name(IssuerUri)就是授權(quán)服務(wù)的主機(jī)名(比如http://10.9.1.1:5000)。
手動(dòng)設(shè)置IssuerUri代碼:
var builder = services.AddIdentityServer(x => x.IssuerUri = "http://111.12.2.21:8000"); //slb 地址資源服務(wù)授權(quán)配置修改:
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 地址,如果是單獨(dú)的授權(quán)服務(wù)地址,會(huì)報(bào)錯(cuò)誤(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;通過(guò) HTTP Post 獲取access_token(不通過(guò) slb,直接請(qǐng)求單獨(dú)的授權(quán)服務(wù)),可以授權(quán)訪(fǎng)問(wèn)資源服務(wù),獲取access_token示例:
參考資料:
- Protecting an API using Client Credentials
- IdentityServer Options
轉(zhuǎn)載于:https://www.cnblogs.com/xishuai/p/identityserver4-slb.html
總結(jié)
以上是生活随笔為你收集整理的IdentityServer4 配置负载均衡的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: H3 BPM微信接入配置
- 下一篇: 关于JavaScript中的同步(SYN