我有一个允许匿名用户的 ASP.NET Core MVC 应用程序。这个应用程序正在调用一个受 Identity Server 4 保护的 ASP.NET Web API。我在 Identity Server 中创建了一个客户端,描述了 MVC 应用程序(客户端),并为其授予了对 api 范围的访问权限,如下所示:
new Client
{
ClientId = "my-mvc-client-app",
AllowedGrantTypes = GrantTypes.ClientCredentials,
RequireConsent = false,
ClientSecrets = new List<Secret> { new Secret("this-is-my-secret".Sha256()) },
AllowedScopes = new List<string>
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
StandardScopes.OfflineAccess.Name,
"my-protected-api"
},
RedirectUris = new List<string>
{
"http://localhost:5009/signin-oidc",
}
}
在我的 MVC 应用程序中,我TokenClient
用来获取一个令牌,在向受保护的 API 发出请求时可以使用该令牌,如下所示:
var disco = await DiscoveryClient.GetAsync("http://localhost:5010");
var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("hrmts-test-candidate-api-scope");
这很好用,但我在每次请求时都从 Identity Server 请求新令牌,这可能不是一个好主意。
处理令牌的最佳做法是什么?如何将它们持久保存在客户端(MVC 应用程序)上,如何处理刷新令牌以确保客户端在必要时获得新令牌?