简体   繁体   English

在 C# .NET 中创建和验证 JWT 令牌

[英]Creating And Validating JWT Tokens In C# .NET

I am using C# asp.net I want to use jwt token for my webpage.我正在使用 C# asp.net 我想为我的网页使用 jwt 令牌。 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.因此,每当页面加载时,我都必须使用 jwt,我是初学者所以我不太了解,我知道它是如何工作的,但我不知道从哪里开始或如何准确实施。 i have a login page and i only need jwt for "online id/admin/username".我有一个登录页面,我只需要 jwt 作为“在线 ID/管理员/用户名”。 Using these SymmetricSecurityKey SigningCredentials JwtHeader JwtPayload JwtSecurityToken JwtSecurityTokenHandler WriteToken var token = handler.ReadJwtToken(tokenString);使用这些 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?谷歌搜索给出了 .net 核心的结果,这不是我想要的,有人可以帮助我吗? 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.要使用 JWT 进行身份验证,您必须首先注册用户并将其存储在您的数据库中。 When logging in and validating the user with database information, use the following code to create a JWT token.登录并使用数据库信息验证用户时,使用以下代码创建一个 JWT 令牌。

    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.然后,在具有授权属性的操作中,您必须在请求 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我写了一个简单的例子,你可以从这个链接看到完整的实现例子 JWT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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