调用
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