首页 > 解决方案 > 在 C# 中延长 JWT 时间

问题描述

我有这个过滤器(如下),我想延长令牌的时间(通过替换令牌并为用户重新编写一个新的)......有人可以帮我实现这个吗?

这是标准过滤器,没有任何自定义更改或任何东西,我已经处理了令牌到期,现在我想在令牌到期时间内发出请求时更新令牌

public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
{
    public string Realm { get; set; }
    public bool AllowMultiple => false;

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var request = context.Request;
        var authorization = request.Headers.Authorization;

        if (authorization == null || authorization.Scheme != "Bearer")
            return;

        if (string.IsNullOrEmpty(authorization.Parameter))
        {
            context.ErrorResult = new AuthenticationFailureResult("Missing Jwt Token", request);
            return;
        }

        var token = authorization.Parameter;
        var principal = await AuthenticateJwtToken(token);

        if (principal == null)
            context.ErrorResult = new AuthenticationFailureResult("Invalid token", request);

        else
            context.Principal = principal;

          // HERE SHOULD BE THE IMPLEMENTATION FOR TOKEN RENEWAL
    }



    private static bool ValidateToken(string token, out string username)
    {
        username = null;

        var simplePrinciple = JwtManager.GetPrincipal(token);
        var identity = simplePrinciple?.Identity as ClaimsIdentity;

        if (identity == null)
            return false;

        if (!identity.IsAuthenticated)
            return false;

        var usernameClaim = identity.FindFirst(ClaimTypes.Name);
        username = usernameClaim?.Value;

        if (string.IsNullOrEmpty(username))
            return false;

        // More validate to check whether username exists in system

        return true;
    }

    protected Task<IPrincipal> AuthenticateJwtToken(string token)
    {
        string username;

        if (ValidateToken(token, out username))
        {
            // based on username to get more information from database in order to build local identity
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username)
                // Add more claims if needed: Roles, ...
            };

            var identity = new ClaimsIdentity(claims, "Jwt");
            IPrincipal user = new ClaimsPrincipal(identity);

            return Task.FromResult(user);
        }

        return Task.FromResult<IPrincipal>(null);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        Challenge(context);
        return Task.FromResult(0);
    }

    private void Challenge(HttpAuthenticationChallengeContext context)
    {
        string parameter = null;

        if (!string.IsNullOrEmpty(Realm))
            parameter = "realm=\"" + Realm + "\"";

        context.ChallengeWith("Bearer", parameter);
    }
}

标签: c#jwt

解决方案


推荐阅读