为了授权终端用户应用程序和守护程序,您可以使用 ASP.NET Core 的内置身份验证和授权系统。首先,您需要在 Startup.cs 文件中添加以下授权服务:
services.AddAuthorization(options =>
{
options.AddPolicy("EndUserAppPolicy", policy =>
policy.RequireAuthenticatedUser()
.RequireClaim("app_type", "end_user"));
options.AddPolicy("DaemonAppPolicy", policy =>
policy.RequireAuthenticatedUser()
.RequireClaim("app_type", "daemon"));
});
在上面的代码中,我们添加了两个政策:“EndUserAppPolicy”和“DaemonAppPolicy”。第一个政策要求每个经过身份验证的用户都必须具有名为“app_type”的声明,其值为“end_user”。第二个政策要求同样必须含有“app_type”声明,但这次要求其值为“daemon”。
在终端用户应用程序和守护程序中,您需要添加身份验证逻辑以获得访问令牌。下面是一个针对终端用户应用程序的示例:
using Microsoft.AspNetCore.Authentication;
var client = new HttpClient();
var discoveryDocument = await client.GetDiscoveryDocumentAsync("");
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = discoveryDocument.TokenEndpoint,
ClientId = "",
ClientSecret = "",
UserName = "",
Password = "",
Scope = ""
});
if (tokenResponse.IsError)
{
// Handle error
return;
}
var accessToken = tokenResponse.AccessToken;
// Set access token in the HTTP authorization header for further requests
client.SetBearerToken(accessToken);
在上面的代码中,我们使用 IdentityModel 库中的 PasswordToken