identityserver4+.net core之自定义生成Token

7 篇文章 0 订阅

主要是引入 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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值