主要是引入 ITokenService 接口,调用CreateSecurityTokenAsync方法
private readonly ITokenService _tokenService;
private readonly IConfiguration _configuration;//引入 读取.net core配置文件
private readonly ISysSettingService _identityServer4Service;//自己写的 为了获取identityserver的相关配置
#region Create Token
/// <summary>
/// 为用户创建token
/// </summary>
private async Task<TokenDto> CreateToken(Client client, CreateTokenInput input)
{
Token accessToken = await CreateAccessToken(client, input);
string token = await _tokenService.CreateSecurityTokenAsync(accessToken);
return new TokenDto()
{
AccessToken = token,
ExpiresIn = input.Lifetime > 0 ? input.Lifetime : client.AccessTokenLifetime,
TokenType = "Bearer"
};
}
/// <summary>
/// 创建生成jwt的Token所包含信息
/// </summary>
/// <param name="client"></param>
/// <param name="input"></param>
/// <returns></returns>
private async Task<Token> CreateAccessToken(Client client, CreateTokenInput input)
{
#region claims
//, string subjectId, int lifetime, params string[] scopes
var claims = new List<Claim>
{
new Claim(JwtClaimTypes.ClientId, client.ClientId),
new Claim(JwtClaimTypes.Id, input.SubjectId),
};
input.Claims?.ForEach(c => claims.Add(c));
input.Scopes?.ForEach(s => claims.Add(new Claim(JwtClaimTypes.Scope, s)));
//client scopes
claims.AddRange(client.AllowedScopes.Select(s => new Claim(JwtClaimTypes.Scope, s)));
#endregion
#region aud
var website = _configuration.GetValue<string>("AuthWebSite", "").RemoveTrailingSlash();
List<string> aud = new List<string>() { string.Concat(website, "/resources") };
//client aud:apiResourceName
var apiResourceNameList = await _identityServer4Service.GetApiResourceNames(client.AllowedScopes.ToList());
aud.AddRange(apiResourceNameList ?? new List<string>());
#endregion
var token = new Token(OidcConstants.TokenTypes.AccessToken)
{
CreationTime = DateTime.UtcNow,
Claims = claims,
Audiences = aud,
Issuer = website,
Lifetime = input.Lifetime > 0 ? input.Lifetime : client.AccessTokenLifetime,
ClientId = client.ClientId,
AccessTokenType = client.AccessTokenType,
//Scopes = client.AllowedScopes.ToList(),
};
return token;
}
#endregion