[原创] IdentityServer4权限控制---简化客户端对API的访问 (五)
官网的标题可不这么叫,我斗胆按照自己浅薄的理解起了个这样的名字,官网的标题叫这个:ASP.NET Core and API access 我们花了这么多时间搭建了服务器,其实客户端只干了两件事,首先申请TOKEN,接下来才用这个TOKEN访问API。是不是每次都要这么麻烦,在访问API之前都要先申请一遍TOKEN才行?答案是NO!
OpenID Connect 和 OAuth 2.0 组合的美妙之处在于,您可以使用单一协议和令牌服务的单一交换来实现。我们打开IDS4SERVER,在注册服务端的时候做一些简单的配置
修改(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"//将 api1 资源添加到允许的范围列表中,加上开启令牌刷新的支持,就可以只访问一次IDS4申请TOKEN了
}
}
再在客户端做一些设置
修改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 命名空间中的标准 ASP.NET Core 扩展方法访问会话中的令牌:
var accessToken = await HttpContext.GetTokenAsync("access_token");
要使用访问令牌访问 API,您需要做的就是检索令牌,并将其设置在您的 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"); }创建一个名为 json.cshtml 的视图,下面那样打印 json:
<pre>@ViewBag.Json</pre>