首页 > 解决方案 > How can I refresh my jwtsecuritytoken in my project?

问题描述

I create a .net core api which will send a jwtsecuritytoken to client. Connected user to use a functionality of the application have to have a token for each functionality, this token have an expiration date of 5 minutes for exemple and the token have to be refresh after his expiration (if there is no error).

I start to code something but I don't know how to do the refresh of my token ?

[Route("api/[controller]")]
[ApiController]
public class TokenController : ControllerBase
{

    private string GenerateToken(string username)
    {
        SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ijustwanttotestsomething"));

        Claim[] claims = new Claim[]
        {
            new Claim(ClaimTypes.Name , username)
        };

        JwtSecurityToken jwt = new JwtSecurityToken(
            claims: claims,
            notBefore: DateTime.UtcNow,
            expires: DateTime.UtcNow.AddMinutes(5),
            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
        );

        return new JwtSecurityTokenHandler().WriteToken(jwt);
    }

    [HttpPost]
    public ActionResult<string> Create(string username)
    {
        return GenerateToken(username);
    }

    [HttpGet]
    public ActionResult<JwtSecurityToken> TokenExpired (string token)
    {
        var stream = token ;
        var handler = new JwtSecurityTokenHandler();
        var jsonToken = handler.ReadToken(stream);
        JwtSecurityToken tokenS = handler.ReadToken(stream) as JwtSecurityToken;

        DateTime dateTimeToken = DateTime.UtcNow;

        if (dateTimeToken > tokenS.ValidTo)
            return BadRequest("EXPIRED");

        return Ok(tokenS);
    }

    [HttpGet("[Action]")]
    public ActionResult<JwtSecurityToken> RefreshToken (string token)
    {
        // CODE SOMETHING
    }
}

标签: c#jwtclienttokenasp.net-core-webapi

解决方案


推荐阅读