Example #1
0
        public async Task <object> GetJwtToken3(string name = "", string pass = "")
        {
            string jwtStr = string.Empty;

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass))
            {
                return(new JsonResult(new
                {
                    Status = false,
                    message = "用户名或密码不能为空"
                }));
            }

            //pass = MD5Helper.MD5Encrypt32(pass);

            var user = await _sysUserInfoServices.Query(d => d.UserName == name && d.UserPWD == pass);

            if (user.Count > 0)
            {
                var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(name, pass);

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

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

                var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                return(new JsonResult(token));
            }
            else
            {
                return(new JsonResult(new
                {
                    success = false,
                    message = "认证失败"
                }));
            }
        }