使用PostMan Canary測試受Identity Server 4保護的Web Api
- 2022 年 2 月 27 日
- 筆記
- c#, Identity Server, Identity Server 4, postman, Web Api
在《Asp.Net Core: Swagger 與 Identity Server 4》一文中介紹了如何生成受保護的Web Api的Swagger文檔,本文介紹使用PostMan Canary測試受Identity Server 4保護的Web Api。
首先搭建一下Identity Server 4的環境,並且創建一個測試用的Web Api和訪問Web Api的客戶端,這部分在系列文章《Identity Server 4 從入門到落地》中有詳細的介紹。
Identity Server 4 Admin的程式碼和測試用Web Api和Client的程式碼可以從Github下載:
//github.com/zhenl/IDS4Admin
//github.com/zhenl/IDS4ClientDemo
這裡只列出測試用Web Api項目appsettings.json中的配置項:
"IdentityServer4Api": {
"Authority": "//host.docker.internal:4010",
"CorsOrgins": [
"//host.docker.internal:5291"
],
"Policies": [
{
"Name": "ApiScope",
"RequireAuthenticatedUser": "true",
"Claims": [
{
"ClaimType": "scope",
"AllowValues": [ "testapi" ]
}
]
}
],
訪問這個Web Api的測試用Web應用appsettings.json中相關配置項:
"IdentityServer4Client": {
"Authority": "//host.docker.internal:4010",
"ClientId": "testclient",
"ClientSecret": "secret",
"ResponseType": "code",
"SaveTokens": "true",
"RequireHttpsMetadata": "false",
"Scopes": [ "openid", "profile", "testapi" ],
"JsonKeys": []
}
我們使用最新的PostMan Canary進行測試,下載地址//www.postman.com/downloads/canary/。安裝完成後,就可以訪問Web Api了。
如果直接訪問 Web Api,會提示401錯誤:
我們需要在PostMan中實現認證,才能訪問受保護的Web Api。我們已經在認證中心設置了可以訪問Web Api的Client,資訊如下:
Client ID | testclient |
Client Secret | secret |
Callback URL | //host.docker.internal:5291/signin-oidc |
Web Api Scope | Scope |
現在,在PostMan中進入Authorization分頁:
選擇認證類型為OAuth2.0:
在右邊出現認證需要的參數表單,其中Grant Type選擇Authorization Code(With PKCE),說明我們使用OpenID Connect。其它參數參考已經配置的Client 參數。
還需要說明的是,認證的地址為:[認證服務地址]/connect/authorize,在這個例子中這個地址為//host.docker.internal:4010/connect/authorize。獲取Token的URL為[認證服務地址]/connect/token,在這個例子中地址為://host.docker.internal:4010/connect/token 。
參數填寫完成後,點擊Get Access Token按鈕:
如果設置正確的話,會彈出認證頁面,輸入用戶名,密碼,認證完成後,PostMan關閉認證頁面,並返回Access Token:
點擊Use Token,Token被自動填寫到訪問頁面:
這時再次按Send訪問Web Api,可以正確地獲取返回數據了: