Ejemplo n.º 1
0
        public async Task <MessageModel <TokenInfoViewModel> > GetJwtToken3(string UserLog, string UserPwd)
        {
            string jwtStr = string.Empty;

            if (string.IsNullOrEmpty(UserLog) || string.IsNullOrEmpty(UserPwd))
            {
                return(new MessageModel <TokenInfoViewModel>()
                {
                    success = false,
                    msg = "用户名或密码不能为空",
                });
            }

            UserPwd = MD5Helper.MD5Encrypt32(UserPwd);
            var user = await _userInfo.GetList(UserLog, UserPwd);

            if (user != null)
            {
                var userRoles = await _userInfo.GetUserRoleNameStr(UserLog, UserPwd);

                //如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
                var claims = new List <Claim> {
                    new Claim(ClaimTypes.Name, UserLog),
                    new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().uID.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
                };
                claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
                // ids4和jwt切换
                var idetity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                idetity.AddClaims(claims);
                // jwt
                if (!Permissions.IsUseIds4)
                {
                    var data = await _roleModulePermissionServices.GetRoleModule(user.FirstOrDefault().uID.ObjToInt());

                    var list = (from item in data
                                where item.IsDeleted == false
                                orderby item.Id
                                select new PermissionItem
                    {
                        Url = item.Module?.LinkUrl,
                        Role = item.Role?.Name.ObjToString(),
                    }).ToList();

                    _requirement.Permissions = list;
                }
                var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                return(new MessageModel <TokenInfoViewModel>()
                {
                    success = true,
                    msg = "获取成功",
                    response = token
                });
            }
            else
            {
                return(new MessageModel <TokenInfoViewModel>()
                {
                    success = false,
                    msg = "认证失败",
                });
            }
        }