首页 > 其他分享 >NetCore 生成JWT

NetCore 生成JWT

时间:2022-09-26 16:33:18浏览次数:58  
标签:NetCore app JWT 生成 using var new builder

调用

        private readonly IESP_UsersBLL _UsersBLL;
        private readonly IConfiguration _configuration;
        private JWTService _jwtService;

        public SysUserController(IConfiguration configuration, IESP_UsersBLL _IUsersBLL)
        {
            _UsersBLL = _IUsersBLL;
            _configuration = configuration;
            _jwtService = new JWTService(_configuration);
        }


            string strToken = "";
            try
            {
                //根据用户编号生成JWT
                strToken = _jwtService.GenerateToken(users.UserId, users.Id.ToString().ToUpper(), users.Roles);

                //加入登录信息
                _UsersBLL.AddUserLog(users, ip);

            }
            catch (Exception ex)
            {
                throw new MyArgumentException(106);
            }

 

生成JWT

    public class JWTService
    {

        private readonly IConfiguration _configuration;
        public JWTService(IConfiguration configuration)
        {
            _configuration = configuration;
        }



        /// <summary>
        /// JWT生成
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="expireMinutes"></param>
        /// <returns></returns>
        public string GenerateToken(string userId, string userGuid = "",string roles="", int expireMinutes = 30)
        {
            var issuer = _configuration.GetValue<string>("JwtSettings:Issuer");
            var signKey = _configuration.GetValue<string>("JwtSettings:SignKey");

            //要加入到 JWT Token 中的Claims
            var claims = new List<Claim>();

            // 在 RFC 7519 規格
            claims.Add(new Claim(JwtRegisteredClaimNames.Iss, issuer));
            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, userId));
            claims.Add(new Claim(JwtRegisteredClaimNames.Aud, "The Audience"));
            claims.Add(new Claim(JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddMinutes(expireMinutes).ToUnixTimeSeconds().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, userGuid.ToString()));


            //角色
            claims.Add(new Claim("roles", roles));
           // claims.Add(new Claim("roles", "Users"));

            var userClaimsIdentity = new ClaimsIdentity(claims);

            // JWT签章
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey));

            // HmacSha256
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            // 建立 SecurityTokenDescriptor
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Issuer = issuer,
                NotBefore = DateTime.Now,
                IssuedAt = DateTime.Now,
                Subject = userClaimsIdentity,
                Expires = DateTime.Now.AddDays(1).AddMinutes(expireMinutes),
                SigningCredentials = signingCredentials
            };

            //JWT securityToken 物件
            var tokenHandler = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            var serializeToken = tokenHandler.WriteToken(securityToken);

            return serializeToken;
        }


}


 

 

 

 

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Claims;

 

program:

using Autofac;
using Autofac.Extensions.DependencyInjection;
using ESP.BLL;
using ESP.BLL.CustomizeException;
using ESP.JWT.Service;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Text;


var builder = WebApplication.CreateBuilder(args);



// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
 



//AutoFac容器注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    Assembly assembly = Assembly.Load(ServiceCore.GetAssemblyName());
    builder.RegisterAssemblyTypes(assembly)
           .AsImplementedInterfaces()
           .InstancePerDependency();
});

//2022-05-07 注册异常自定义过滤器
builder.Services.AddControllers(o => o.Filters.Add(typeof(CustomizeExceptionAttribute)));


#region 读取配置信息
//注入JWT配置文件
builder.Services.Configure<JWTConfig>(builder.Configuration.GetSection("JWT"));
JWTConfig config = new JWTConfig();
builder.Configuration.GetSection("JWT").Bind(config);
 
#endregion

builder.Services.AddControllers();


//2022-07-27 zny LOG4日志注册
builder.Services.AddLogging(cfg =>
{
    cfg.AddLog4Net();
});


var corsPolicyName = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: corsPolicyName,
                      builder =>
                      {
                          /*builder.WithOrigins("http://localhost", "*")
                            .AllowAnyHeader()
                            .AllowAnyMethod();*/
                         builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                      });
});

var app = builder.Build();


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI();
      app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "OpenCore.JWT.Server v1"));

}

app.UseHttpsRedirection();



app.UseCors(corsPolicyName);

app.MapControllers();



//下面的app添加这个  和这个长得很像  app.UseAuthorization();
app.UseAuthentication();//在前开户认证
app.UseAuthorization();//在后授权中间件
app.UseHttpsRedirection(); 
app.UseRouting(); 
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
app.Run();

 

 

 

 

 

"JwtSettings": {
"Issuer": "JwtAut**********",
"SignKey": "1Zl4h9*********************Eb"
},

 

标签:NetCore,app,JWT,生成,using,var,new,builder
From: https://www.cnblogs.com/znyCoding/p/16731403.html

相关文章

  • YApi to TypeScript(简称 ytt)根据swagger生成api代码放入项目中
    这个工具每次执行脚本内容都会覆盖代码文件,他可以用于yapi和swagger,关于yapiapi的教程可以查看官方文档,https://fjc0k.github.io/yapi-to-typescript/handbook/这里主要......
  • JWT
      官网:https://jwt.io/  JWT是标准化的token,全称为JsonWebToken,是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准(RFC7519)  从本质上讲JWT也......
  • spring boot项目用maven插件执行package打包命令后不生成target文件夹
    用maven插件执行package打包命令后不生成target文件夹点击>Reloadfromdisk后搞定唔这应该是idea的bug吧......
  • JWT:拥有我,即拥有权力
     Hi,这里是桑小榆。 上篇文章中,我们一起探讨了OAuth协议的原理以及授权认证流程,本次我们一起探讨jwt令牌作为授权协议的传输介质。OAuth协议规范了几个参与角色的......
  • aardio + Python 可视化快速开发桌面程序,一键生成独立 EXE
    网络上大家分享的aardio+Python混合开发的文章很多,不得不说aardio与Python混合开发是真的简单!▶ 快速入门推荐几个快速上手教程:《aardio+Python开发桌面软......
  • 微信小程序生成页面太阳码及分享海报
    @目录效果图实现方式踩坑代码效果图实现方式后端node获取小程序token及太阳码参考文章点我生成海报使用插件painter地址点我小程序生成太阳码文档点我踩坑千......
  • Protobu生成文件报错
    报错信息:user@C02FP58GML7Hpbfile%protoc--go_out=././user.protoprotoc-gen-go:programnotfoundorisnotexecutablePleasespecifyaprogramusingabso......
  • .netcore 下搭建本地nuget服务器
    1.首先创建一个普通的项目这个项目后面会放入我们自定义的nuget服务器给予其他项目应用2.我们对这个项目进行一下设置1)项目->属性选中构建nuget包2)项目点击发布......
  • CAP事件总线在NetCore中的应用+MySql存储队列信息
    上一篇链接:https://www.cnblogs.com/fei686868/p/16721769.html在上一篇中,我们介绍了CAP基于内存存储的应用。本篇我们介绍下,把存储做到mysql中,队列还是使用内存队列。my......
  • 寻找领域不变量:从生成模型到因果表征
    1领域不变的表征在迁移学习/领域自适应中,我们常常需要寻找领域不变的表征(Domain-invariantRepresentation)[1],这种表示可被认为是学习到各领域之间的共性,并基于此共性......