Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        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);
            }
        }
Esempio n. 3
0
        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
        }