简体   繁体   中英

Creating And Validating JWT Tokens In C# .NET

I am using C# asp.net I want to use jwt token for my webpage. So whenever the page loads, i have to use jwt, im a beginner so i dont have much idea, i know how it works, but i dont know where to start from or how to implement exactly. i have a login page and i only need jwt for "online id/admin/username". Using these SymmetricSecurityKey SigningCredentials JwtHeader JwtPayload JwtSecurityToken JwtSecurityTokenHandler WriteToken var token = handler.ReadJwtToken(tokenString); and googling gives my result for .net core which is not what i want, can someone help me? Thankyou

I tried some code snippets but im sure im not doing it the right way

To authenticate using JWT, you must first register the user and store it in your database. When logging in and validating the user with database information, use the following code to create a JWT token.

    public static string GenerateJwtToken()
    {
        DateTime value = DateTime.Now.AddMinutes(20.0);
        byte[] bytes = Encoding.ASCII.GetBytes("MIIBrTCCAaGg ...");
        SigningCredentials signingCredentials = new SigningCredentials(new SymmetricSecurityKey(bytes), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256");
        SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
        {
            Expires = value,
            SigningCredentials = signingCredentials
        };
        JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
        SecurityToken token = jwtSecurityTokenHandler.CreateToken(tokenDescriptor);
        return jwtSecurityTokenHandler.WriteToken(token);
    }

Then, in the actions that have the Authorize attribute, you must send the token created above in the request header.

[HttpPost]
[Authorize]
public async Task<IActionResult> Test(TestRequest input)
{
    .
    .
    .
}

I wrote a simple example, you can see the complete implementation example with JWT from this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM