Files
ww-jst/wmsjst/JSMachine.WMS.Authorization/AuthorizationConfigResolver.cs
T
2026-09-02 16:31:50 +08:00

70 lines
2.5 KiB
C#

using IdentityServer4.Models;
using JSMachine.WMS.Authorization.Model;
namespace JSMachine.WMS.Authorization
{
/// <summary>
/// 从授权配置中解析 IdentityServer 的身份资源、API 作用域和客户端信息。
/// </summary>
public class AuthorizationConfigResolver
{
private static IConfiguration _configuration;
/// <summary>
/// 设置后续解析操作使用的配置对象。
/// </summary>
/// <param name="configuration">包含 AppSettings 配置节的配置对象。</param>
public static void SetConfig(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary>
/// 获取 OpenID Connect 所需的标准身份资源。
/// </summary>
public static IEnumerable<IdentityResource> IdentityResources =>
new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
/// <summary>
/// 从 AppSettings:ApiScopes 读取 API 作用域配置。
/// </summary>
/// <returns>配置存在时返回 API 作用域集合,否则返回空值。</returns>
public static IEnumerable<ApiScope>? GetApiScopes()
{
return _configuration
.GetSection("AppSettings")
.GetSection("ApiScopes")
.Get<string[]>()
?.Select(p => new ApiScope(p));
}
/// <summary>
/// 从 AppSettings:Clients 读取客户端配置,并转换为客户端凭据模式定义。
/// </summary>
/// <returns>配置存在时返回客户端集合,否则返回空值。</returns>
public static IEnumerable<Client>? GetClients()
{
List<ClientInfo> clients = _configuration
.GetSection("AppSettings")
.GetSection("Clients")
.Get<List<ClientInfo>>();
return clients?.Select(p => new Client
{
ClientId = p.ClientId,
//用于身份验证的密钥
ClientSecrets = new Secret[] { new Secret(p.Secret.Sha256()) },
//客户端有权访问的范围
AllowedScopes = p.AllowedScopes,
//过期时间(秒)
AccessTokenLifetime = p.AccessTokenLifetime,
//没有交互式用户,使用 clientid/secret 进行身份验证
AllowedGrantTypes = GrantTypes.ClientCredentials
});
}
}
}