首页 > 其他分享 >使用 JWT 生成token

使用 JWT 生成token

时间:2024-06-04 15:48:53浏览次数:16  
标签:string JWT 生成 secretKey token new var using

安装 Nuget包:

Microsoft.AspNetCore.Authentication.JwtBearer
System.IdentityModel.Tokens.Jwt

2. 然后,配置JWT服务和认证:在 Program.cs 文件中

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;


// 添加JWT验证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "Issuer", //与签发token时的Issuer匹配
            ValidAudience = "Audience",//与签发token时的Audience匹配
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("I4T0O/RW4zOfO42Hbv9jROUWfwr19LlVazJWkcHM3rc=")) //与签发token时的密钥匹配
}; });
builder.Services.AddControllers(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization();

3. 接下来,创建一个控制器来处理用户登录并生成token:

using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Zhaoxi.Shopping.Admin.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class GetTokenController : ControllerBase
    {

        [HttpPost]
        public IActionResult Login(string username, string password)
        {
        // 验证用户身份,这里简化为直接通过
            var secretKey = "I4T0O/RW4zOfO42Hbv9jROUWfwr19LlVazJWkcHM3rc=";
            var issuer = "Issuer";
            var audience = "Audience";

            var token = GenerateJwtToken(username, secretKey, issuer, audience);
            return Ok(new { token });
        }

        private string GenerateJwtToken(string username, string secretKey, string issuer, string audience)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(30), // 设置token有效期
                signingCredentials: creds);

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

 

secretKey  密钥可以使用 : 你可以使用C#的RNGCryptoServiceProvider类来生成随机的字节数组,然后将其转换为Base64编码的字符串作为JWT的秘钥。
using System;
using System.Security.Cryptography;

namespace YourNamespace
{
    public class JwtKeyGenerator
    {
        public static string GenerateJwtSecretKey(int keySize)
        {
            byte[] secretKeyBytes = new byte[keySize];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(secretKeyBytes);
            }
            return Convert.ToBase64String(secretKeyBytes);
        }

        public static void Main(string[] args)
        {
            // 生成256位(32字节)的随机秘钥
            string secretKey = GenerateJwtSecretKey(32);
            Console.WriteLine("Generated JWT Secret Key:");
            Console.WriteLine(secretKey);
        }
    }
}

 

 

标签:string,JWT,生成,secretKey,token,new,var,using
From: https://www.cnblogs.com/tlfe/p/18230656

相关文章

  • Lumière:开创性的视频生成模型及其应用
    视频内容创造领域迎来了突破性进展,但视频生成模型由于运动引入的复杂性而面临更多挑战。这些挑战主要源自运动的引入所带来的复杂性。时间连贯性是视频生成中的关键要素,模型必须确保视频中的运动在时间上是连贯和平滑的,避免出现不自然的跳跃或断裂。空间关系的准确性也至关重要......
  • .netCore System.Drawing.Common 发布,在CentOS 运行报错,生成图片流时。会因为不支持在
    报错:System.PlatformNotSupportedException:System.Drawing.Commonisnotsupportedonnon-Windowsplatforms.Seehttps://aka.ms/systemdrawingnonwindowsformoreinformation. >System.PlatformNotSupportedException:System.Drawing.Commonisnotsupported......
  • TS 小技巧: 使用元组生成联合类型
    前言在我们使用TypeScript开发业务的时候,也许你会遇到一个这样的问题:我们如何根据一个数组的值得到一个联合类型?这里向大家介绍一个开发小技巧:使用元组生成联合类型开发场景我们看下面一段ts代码:constcolors=['red','green','orange','blue'];//这里ts解析......
  • mybatis逆向生成文件攻略
    pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache......
  • 博客园文章目录生成脚本v1.0:支持多级、过滤空行、可指定文章、自定义插入点
    使用说明:1.设置-申请JS权限,等待审核通过2.设置-页脚HTML代码,代码贴进去保存 样式说明:1.默认目录插到文章顶部,可以加入<divid="toc"></div>标签自定义插入位置。2.H1和H2是加粗体,其他的是正常体。自定义功能:catalogue(true):给所有文章生成目录catalogue(false):只......
  • webf 开发工具:数据库持久层基础文件生成工具
    WZW.SqlMapHelpForJava是运行在.NetFramework4.0上的数据库持久层基础文件生成工具,支持多种关系型数据库的持久层基础文件、Java类的生成以及对配置文件的更新,与webf框架进行紧密配合,减少了数据库持久层基础文件编写工作量,提高持久层代码的有效及准确性。WZW.SqlMapHelpFo......
  • Excel生成sql语句&Python写入数据到数据库
    一、Excel生成sql语句直接按下图步骤操作即可二、Python插入数据库表数据参考博客:https://blog.csdn.net/Q821869063/article/details/1365660211、用excel表准备一份需要插入的数据,如下图2、代码源码如下#--coding=utf-8#导入读取Excel的库fromopenpyxlimportlo......
  • 数据治理--数据接入 批量接入脚本生成工具 判断增量全量,过滤
             表变化频率比较低的表覆盖     数据接入工具           ......
  • Amazon Q Developer 实战:从新代码生成到遗留代码优化(下)
    简述本文是使用AmazonQDeveloper探索如何在VisualStudioCode集成编程环境(IDE),从新代码生成到遗留代码优化的续集。在上一篇博客《AmazonQDeveloper实战:从新代码生成到遗留代码优化(上)》中,我们演示了如何使用AmazonQDeveloper编写新代码和优化遗留代码。正如我们在上......
  • MACSHA256加密生成签名
    再水一篇,也是业务测试中遇到的一种加密方式,这里示例就直接使用相同的加密规则了,可以根据业务场景自行调整加密前字符串加密规则  所有API的请求参数(除去Sign参数),参数名转小写后根据参数名称的AscII表顺序排序;    将排序号的参数名和参数值拼装在一起得到新的字符串A; ......