locked
How can I use jwtsecuritytoken in my project ? RRS feed

  • Question

  • User-978659149 posted

    Hi, 

    I create a project which need session tokens. User who is in the application connect with an authentication key after that for any module he wants to use, I will have a token, this token have an expiration date of 5 minutes for exemple and if there is no error have to be refresh.

    I start to code something but I don't understand how to use JwtSecurityToken and i'm new in c#.

    private string GenerateToken()
    {
        SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ijustwanttotestsomething"));
    
        Claim[] claims = new Claim[]
         {
             new Claim(ClaimTypes.Name , "test")
         };
    
         JwtSecurityToken jwt = new JwtSecurityToken(
             issuer : "Blinkingcaret",
             audience : "Everyone",
             claims : claims,
             notBefore : DateTime.UtcNow,
             expires : DateTime.UtcNow.AddMinutes(1),
             signingCredentials : new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
         );
    
         return new JwtSecurityTokenHandler().WriteToken(jwt);
    }
    
    [HttpPost]
    public ActionResult<string> Create()
    {
        return GenerateToken();
    }

    Can i have help to implement expiration and refresh in my project please ?

    Wednesday, November 13, 2019 2:58 PM

All replies

  • User765422875 posted

    Expiration is implemented by setting the expires property, which you set to:

    DateTime.UtcNow.AddMinutes(1)

    JSON web tokens are used for Authorization and Information Exchange.

    Refer to the following post on guidance.

    https://www.meziantou.net/jwt-authentication-with-asp-net-core.htm

    Wednesday, November 13, 2019 6:49 PM
  • User-978659149 posted

    Finally how can I test if the token is expired ?

    I try the sample in your link but I have an error.

    Friday, November 15, 2019 8:59 AM
  • User665608656 posted

    Hi soleyne,

    Finally how can I test if the token is expired ?

    I suggest you set the expiration time to be shorter. When the time is up, if you can't get the token, that's prove the token has expired.

    I try the sample in your link but I have an error.

    Can you provide your detailed error information?

    You can aslo refer this link for more details:

    JSON Web Token in ASP.NET Web API 2 using Owin

    Best Regards,

    YongQing.

    Tuesday, November 19, 2019 8:54 AM