[原創(chuàng)] IdentityServer4權(quán)限控制---簡化客戶端對API的訪問 (五)
官網(wǎng)的標(biāo)題可不這么叫,我斗膽按照自己淺薄的理解起了個這樣的名字,官網(wǎng)的標(biāo)題叫這個:ASP.NET Core and API access 我們花了這么多時間搭建了服務(wù)器,其實客戶端只干了兩件事,首先申請TOKEN,接下來才用這個TOKEN訪問API。是不是每次都要這么麻煩,在訪問API之前都要先申請一遍TOKEN才行?答案是NO!
OpenID Connect 和 OAuth 2.0 組合的美妙之處在于,您可以使用單一協(xié)議和令牌服務(wù)的單一交換來實現(xiàn)。我們打開IDS4SERVER,在注冊服務(wù)端的時候做一些簡單的配置
修改(IDS4SERVER)客戶端配置:
// interactive ASP.NET Core MVC client
new Client
{
ClientId = "mvc",
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Code,
// where to redirect to after login
RedirectUris = { "https://localhost:5002/signin-oidc" },
// where to redirect to after logout
PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },
AllowOfflineAccess = true,//啟用對令牌刷新的支持
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"http://將 api1 資源添加到允許的范圍列表中,加上開啟令牌刷新的支持,就可以只訪問一次IDS4申請TOKEN了
}
}
再在客戶端做一些設(shè)置
修改MYMVC客戶端配置:
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.SaveTokens = true; //ASP.NET Core 將自動將生成的token存儲在身份驗證會話中。
//開啟TOKEN信息刷新,支持只請求一次令牌,或者說是以免頻繁申請IDS4令牌。
options.Scope.Add("api1");
options.Scope.Add("offline_access");
});
access token 使用方法
您可以使用 Microsoft.AspNetCore.Authentication 命名空間中的標(biāo)準(zhǔn) ASP.NET Core 擴展方法訪問會話中的令牌:
var accessToken = await HttpContext.GetTokenAsync("access_token");
要使用訪問令牌訪問 API,您需要做的就是檢索令牌,并將其設(shè)置在您的 HttpClient 上:
public async Task<IActionResult> CallApi() { var accessToken = await HttpContext.GetTokenAsync("access_token"); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var content = await client.GetStringAsync("https://localhost:6001/identity"); ViewBag.Json = JArray.Parse(content).ToString(); return View("json"); }創(chuàng)建一個名為 json.cshtml 的視圖,下面那樣打印 json:
<pre>@ViewBag.Json</pre>