您好,欢迎来到画鸵萌宠网。
搜索
您的当前位置:首页.NET6 WEBAPI实现JWT

.NET6 WEBAPI实现JWT

来源:画鸵萌宠网

步骤1,在配置文件配置一下内容

// 配置身份验证方案为 JWT
builder.Services.AddAuthentication(options =>
{
    // 设置默认的身份验证和挑战方案为 JwtBearer
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
// 配置 JWT Bearer 选项
.AddJwtBearer(options =>
{
    // 配置 Token 验证参数
    options.TokenValidationParameters = new TokenValidationParameters
    {
        // 验证发行者
        ValidateIssuer = true,
        // 验证受众
        ValidateAudience = true,
        // 验证令牌有效期
        ValidateLifetime = true,
        // 验证签名密钥
        ValidateIssuerSigningKey = true,
        // 发行者
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        // 受众
        ValidAudience = builder.Configuration["Jwt:Audience"],
        // 签名密钥
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});
builder.Services.AddAuthorization();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        // 如果需要,可以在此处配置Swagger UI以显示OAuth客户端ID等信息
    });
}
// 启用身份验证中间件
app.UseAuthentication();
// 启用授权中间件
app.UseAuthorization();

步骤2,在配置文件配置Swagger的JWT验证,方便测试

//配置Swagger的JWT验证
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
​
    // 添加JWT认证的安全定义
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "Enter JWT token in the format: Bearer {token}.",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT"
    });
    // 添加全局安全要求
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

步骤3,创建一个类,把生成token的方法封装在里面,不封装也行

​
    public class CreateToken
    {
        private readonly IConfiguration _configuration;
​
        public CreateToken(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        // 生成 JWT 令牌的方法
        public string GenerateJwtToken(string account)
        {
            // 从配置中读取JWT密钥、发行者和接受者  
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
​
            // 创建声明,包含用户标识和令牌唯一标识  
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, account),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };
​
            // 设置令牌过期时间为30分钟  
            var expires = DateTime.UtcNow.AddMinutes(30);
​
            // 创建JWT令牌  
            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                expires: expires,
                signingCredentials: credentials);
​
            // 返回令牌字符串  
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }

步骤4,在appsettings.json文件写入一下内容,都改成自己的

"Jwt": {
    "Key": "key", // 签名密钥
    "Issuer": "Issuer", // JWT 发行者
    "Audience": "Audience" // JWT 受众
  }

步骤5,调用方法获取token,返回给前端

var token = new CreateToken(_configuration).GenerateJwtToken(login_Dto.Account);

步骤6,在需要的控制器或方法上标明[Authorize], 在控制器动作上使用[Authorize]属性来指示该动作需要验证Token。当请求到达这些受保护的动作时,.NET Core框架会自动使用配置的TokenValidationParameters来验证Token的有效性。

前端代码,这是我封装成API的代码

return request.get('MenuInfo/getMenuInfo',{
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type':'application/json'
        },
        data:data
      })

我前端是用defineStore把后端传过来的token存起来的

import { defineStore } from 'pinia'
export const useStoreLogin = defineStore('login', {
    state: () => {
        return {
            name: '',
            token:''
        }
    },
    getters: {},
    actions: {
        changeName(val,val2) {
            this.name = val,
            this.token = val2
        },
    },
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: localStorage,
                paths: ['name']
            },
            {
                key: 'JWT',
                storage: localStorage,
                paths: ['token']
            }
        ]
    }
})

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo8.com 版权所有 湘ICP备2023022238号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务