public static JwtEntity GenerarTokenJWT(string secret, string ExpiresSeconds) { JwtEntity loginResponse = new JwtEntity(); var id_token = Guid.NewGuid().ToString(); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Jti, id_token) }), Expires = DateTime.UtcNow.AddSeconds(int.Parse(ExpiresSeconds)), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); loginResponse.Token = tokenHandler.WriteToken(token); loginResponse.ExpireSeconds = ExpiresSeconds; loginResponse.RefreshToken = id_token; return(loginResponse); }
protected JwtEntity GetJwtIEntity(string header = "") { JwtEntity jwtEntity = new JwtEntity(); if (string.IsNullOrEmpty(header)) { header = base.Request.Headers["Authorization"].FirstOrDefault(); jwtEntity = JwtEntity.GetJwtEntity(header); } return(jwtEntity); }
public IActionResult Get() { JwtEntity loginResponse = new JwtEntity(); if (true) { loginResponse = JwtServices.GenerarTokenJWT(_tokenstrings.Key, _tokenstrings.ExpiresSeconds); } return(new ObjectResult(loginResponse) { StatusCode = 200 }); }
public JwtEntity ConsultarPropiedadesJwt(long Id) { try { JwtParametros j = new DJwt().ConsultarPropiedadesJwt(Id); JwtEntity jwt = new JwtEntity() { JWT_AUDIENCE_TOKEN = j.JWT_AUDIENCE_TOKEN, JWT_EXPIRE_MINUTES = j.JWT_EXPIRE_MINUTES, JWT_ISSUER_TOKEN = j.JWT_ISSUER_TOKEN, JWT_SECRET_KEY = j.JWT_SECRET_KEY }; if (jwt == null) { } return(jwt); } catch (Exception ex) { throw ex; } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //获取属性 PermissionAttribute actionAttr = filterContext.ActionDescriptor.FilterDescriptors .Where(a => a.Filter is PermissionAttribute) .Select(a => a.Filter).FirstOrDefault() as PermissionAttribute; string strNavName = string.Empty; string strActionType = string.Empty; try { if (actionAttr != null) { var perArray = actionAttr.PermissionArray;//接口需要的权限Tag var hearder = filterContext.HttpContext.Request.Headers["Authorization"].FirstOrDefault(); var jwtEntity = JwtEntity.GetJwtEntity(hearder); if (jwtEntity != null) { bool isPermission = false;//是否有权限 if (jwtEntity.UserId == 1) { //admin账号有所有权限 isPermission = true; } else if (jwtEntity.UserId == 2 && filterContext.HttpContext.Request.Method.ToUpper() != "GET") { //测试账号只有get权限 isPermission = false; filterContext.Result = new JsonResult(new ReturnMsgCode("000052", "测试账号没有操作数据权限,只有查询权限")); return; } else { //查询账号所有的角色 var roleList = RedisHelper.HGet <List <string> >(RedisKeysEnum.AdminRoleHash.GetHFMallKey(), jwtEntity.UserId.ToString()); if (roleList != null) { //查询角色下面的菜单和按钮权限 var menuStrList = RedisHelper.HMGet <string>(RedisKeysEnum.RoleMenuHash.GetHFMallKey(), roleList.ToArray()); var menuList = new List <PermissionDto>(); foreach (var item in menuStrList) { var rtopList = JSONHelper.ToList <PermissionDto>(item); menuList.AddRange(rtopList); } //判断接口所需要的权限是否在角色的权限中 if (menuList.Where(s => perArray.Contains(s.Tag)).ToList().Count > 0) { isPermission = true; } } } if (!isPermission) { filterContext.Result = new JsonResult(new ReturnMsgCode("000050", "账号没有操作权限")); return; } } else { filterContext.Result = new JsonResult(new ReturnMsgCode("000051", "无法识别的Authorization类型")); return; } } } catch (Exception ex) { throw new Exception(ex.Message); } }
public static void AddService(this IServiceCollection services, SysConfig systemConfig) { WebApiCompatShimMvcBuilderExtensions.AddWebApiConventions(services.AddMvc(opt => { opt.UseCentralRoutePrefix(new RouteAttribute(systemConfig.Name)); })) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(x => { //设置时间格式 x.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //设置转换属性 //x.SerializerSettings.ContractResolver = new ContractResolverOverload(); }); services.AddCors(opt => { opt.AddPolicy("any", builder => { builder.AllowAnyOrigin() //允许任何来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); #region JWT认证 //JWT配置注入 services.Configure <JwtSettings>(opt => { opt.Audience = systemConfig.JwtSettings.Audience; opt.Expires = systemConfig.JwtSettings.Expires; opt.Issuer = systemConfig.JwtSettings.Issuer; opt.PrivateKey = systemConfig.JwtSettings.PrivateKey; opt.PublicKey = systemConfig.JwtSettings.PublicKey; opt.Secretkey = systemConfig.JwtSettings.Secretkey; }); SysConfig systemConfig2 = systemConfig; services.AddMicroService(systemConfig2); //TODO 令牌过期后刷新,以及更改密码后令牌未过期的处理问题 services.AddAuthentication(opts => { opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(opts => { opts.Events = new JwtBearerEvents() { OnMessageReceived = context => { var header = context.Request.Headers["Authorization"].FirstOrDefault(); var jwtEntity = JwtEntity.GetJwtEntity(header); if (jwtEntity != null) { if (DateTime.Now > DateTimeExtension.ConvertToCsharpTime(jwtEntity.Exp)) { context.Fail("token已过期"); } } return(Task.CompletedTask); } }; opts.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(systemConfig.JwtSettings.Secretkey)), ValidateIssuer = true, ValidIssuer = systemConfig.JwtSettings.Issuer, ValidateAudience = true, ValidAudience = systemConfig.JwtSettings.Audience, }; }); #endregion }