Example #1
0
        public async Task <object> RefreshToken(string token = "")
        {
            string jwtStr = string.Empty;

            if (string.IsNullOrEmpty(token))
            {
                return(new JsonResult(new
                {
                    success = false,
                    message = "传入的token参数不能为空!"
                }));
            }
            var tokenModel = JwtHelper.SerializeJwt(token);

            if (tokenModel != null && tokenModel.Id > 0)
            {
                var user = await _userSvc.QueryById(tokenModel.Id);

                if (user != null)
                {
                    var userRoles = await _roleSvc.GetDataByids(user.RoleIds);

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

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

                    var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                    return(new JsonResult(refreshToken));
                }
            }

            return(new JsonResult(new
            {
                success = false,
                message = "认证失败"
            }));
        }
Example #2
0
        public async Task <object> GetUserByToken(string token)
        {
            var data = new MessageModel <User>();

            if (!string.IsNullOrEmpty(token))
            {
                var tokenModel = JwtHelper.SerializeJwt(token);
                if (tokenModel != null && tokenModel.Id > 0)
                {
                    var model = await _userSvc.QueryById(tokenModel.Id);

                    if (model != null)
                    {
                        data.Response = model;
                        data.Success  = true;
                        data.Message  = "获取成功";
                    }
                }
            }
            return(data);
        }