Exemplo n.º 1
0
        public async Task <object> GetJwtToken([FromBody] FMLogin model)
        {
            var jm = new AdminUiCallBack();

            if (string.IsNullOrEmpty(model.userName) || string.IsNullOrEmpty(model.password))
            {
                jm.msg = "用户名或密码不能为空";
                return(new JsonResult(jm));
            }

            model.password = CommonHelper.Md5For32(model.password);

            var user = await _sysUserServices.QueryByClauseAsync(p => p.userName == model.userName && p.passWord == model.password);

            if (user != null)
            {
                if (user.state == 1)
                {
                    jm.msg = "您的账户已经被冻结,请联系管理员解锁";
                    return(new JsonResult(jm));
                }
                var userRoles = await _sysUserServices.GetUserRoleNameStr(model.userName, model.password);

                //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
                var claims = new List <Claim> {
                    new Claim(ClaimTypes.Name, user.userName),
                    new Claim(JwtRegisteredClaimNames.Jti, user.id.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_permissionRequirement.Expiration.TotalSeconds).ToString())
                };
                claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

                // ids4和jwt切换
                // jwt
                if (!Permissions.IsUseIds4)
                {
                    var data = await _sysRoleMenuServices.RoleModuleMaps();

                    var list = (from item in data
                                orderby item.id
                                select new PermissionItem
                    {
                        Url = item.menu?.component,
                        RouteUrl = item.menu?.path,
                        Authority = item.menu?.authority,
                        Role = item.role?.roleCode,
                    }).ToList();

                    _permissionRequirement.Permissions = list;
                }

                //用户标识
                var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                identity.AddClaims(claims);

                var token = JwtToken.BuildJwtToken(claims.ToArray(), _permissionRequirement);

                jm.code = 0;
                jm.msg  = "认证成功";
                jm.data = new
                {
                    token,
                    loginUrl = "Panel.html"
                };

                //插入登录日志
                var log = new SysLoginRecord();
                log.username   = model.userName;
                log.ip         = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                log.os         = RuntimeInformation.OSDescription;
                log.browser    = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent];
                log.operType   = (int)GlobalEnumVars.LoginRecordType.登录成功;
                log.createTime = DateTime.Now;
                await _sysLoginRecordRepository.InsertAsync(log);

                return(new JsonResult(jm));
            }
            else
            {
                //插入登录日志
                var log = new SysLoginRecord();
                log.username   = model.userName;
                log.ip         = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                log.os         = RuntimeInformation.OSDescription;
                log.browser    = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent];
                log.operType   = (int)GlobalEnumVars.LoginRecordType.登录失败;
                log.createTime = DateTime.Now;
                await _sysLoginRecordRepository.InsertAsync(log);

                jm.msg = "账户密码错误";
                return(new JsonResult(jm));
            }
        }
Exemplo n.º 2
0
        // 重写异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            var httpContext = _accessor.HttpContext;

            if (!requirement.Permissions.Any())
            {
                var data = await _sysRoleMenuServices.RoleModuleMaps();

                var list = new List <PermissionItem>();

                if (Permissions.IsUseIds4)
                {
                    list = (from item in data
                            orderby item.id
                            select new PermissionItem
                    {
                        Url = item.menu?.component,
                        RouteUrl = item.menu?.path,
                        Authority = item.menu?.authority,
                        Role = item.role?.id.ObjectToString(),
                    }).ToList();
                }
                else
                {
                    list = (from item in data
                            orderby item.id
                            select new PermissionItem
                    {
                        Url = item.menu?.component,
                        RouteUrl = item.menu?.path,
                        Authority = item.menu?.authority,
                        Role = item.role?.roleCode,
                    }).ToList();
                }
                requirement.Permissions = list;
            }

            //请求Url
            if (httpContext != null)
            {
                //
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }
                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        // 获取当前用户的角色信息
                        var currentUserRoles = new List <string>();

                        // ids4和jwt切换
                        // ids4
                        if (Permissions.IsUseIds4)
                        {
                            currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == "role"
                                                select item.Value).ToList();
                        }
                        else
                        {
                            // jwt
                            currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == requirement.ClaimType
                                                select item.Value).ToList();
                        }

                        var isMatchRole      = false;
                        var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
                        foreach (var item in permisssionRoles)
                        {
                            try
                            {
                                //权限中是否存在请求的url
                                if (Regex.Match(questUrl, item.Url.ObjectToString().ToLower()).Value == questUrl)
                                {
                                    isMatchRole = true;
                                    break;
                                }
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }

                        //验证权限
                        if (currentUserRoles.Count <= 0 || !isMatchRole)
                        {
                            context.Fail();
                            return;
                        }
                        var isExp = false;

                        // ids4和jwt切换
                        // ids4
                        if (Permissions.IsUseIds4)
                        {
                            isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) != null && DateHelper.StampToDateTime(httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) >= DateTime.Now;
                        }
                        else
                        {
                            // jwt
                            isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now;
                        }
                        if (isExp)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            context.Fail();
                            return;
                        }
                        return;
                    }
                }
                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))
                {
                    context.Fail();
                    return;
                }
            }

            context.Succeed(requirement);
        }