IdentityServer4_3.ASP.NET Core和API访问
3、ASP.NET Core和API访问
在之前的快速入门中,我们探讨了API访问和用户身份验证。现在我们想把这二部分放在一起。
OIDC和OAuth2.0组合的美妙之处在于,你可以通过单个协议和令牌服务的单个交换来实现
到目前位置,我们只在令牌请求期间请求身份资源,一旦我们开始还包括API资源,IdentityServer将返回两个令牌;包含身份验证和会话信息的身份令牌,以及代表访问API的访问令牌登录用户。
修改客户端配置
在IdentityServer中更新客户端配置很简单--我们只需要将api1资源添加到允许的范围列表中。此外,我们通过AllowOfflineAccess属性启用对刷新令牌的支持:
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"
}
}
修改MVC客户端
现在客户端要做的就是通过 scope 参数请求额外的资源。这是在 OpenID Connect 处理程序配置中完成的:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.SaveTokens = true;
options.Scope.Add("api1");
options.Scope.Add("offline_access");
});
由于SaveTokens已启用,ASP.NET Core 将自动将生成的访问和刷新令牌存储在身份验证会话中。您应该能够检查打印出您之前创建的会话内容的页面上的数据。
使用访问令牌
您可以使用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>
确保 API 正在运行,启动 MVC 客户端并/home/CallApi在身份验证后调用。

浙公网安备 33010602011771号