日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

IdentityServer4 配置负载均衡

發布時間:2025/7/14 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IdentityServer4 配置负载均衡 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

如果使用 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

轉載于:https://www.cnblogs.com/xishuai/p/identityserver4-slb.html

總結

以上是生活随笔為你收集整理的IdentityServer4 配置负载均衡的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。