Пример #1
0
        public override async Task <bool> SyncPermissionsAsync(string authority, string clientId, string clientSecret)
        {
            // 遍历子系统中所有 HasPermissionAttribute 然后报告给 Iam
            var attributes = new List <HasPermissionAttribute>();

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (Type type in assembly.GetTypes())
                {
                    attributes.AddRange(type.GetCustomAttributes <HasPermissionAttribute>(false));

                    foreach (var mtd in type.GetMethods())
                    {
                        attributes.AddRange(mtd.GetCustomAttributes <HasPermissionAttribute>(false));
                    }
                }
            }

            SyncPermissionsDto model = new SyncPermissionsDto
            {
                ClientId    = clientId,
                Permissions = new List <PermissionDto>()
            };

            foreach (var attr in attributes)
            {
                var permsInfo = attr.Policy.Split(Constants.ColonDelimiter);
                model.Permissions.Add(new PermissionDto
                {
                    ClientId = clientId,
                    Key      = permsInfo[KEY_INDEX],
                    Name     = permsInfo[KEY_INDEX],
                    Desc     = permsInfo[DESC_INDEX],
                    Type     = PermissionType.Api
                });
            }

            // 通过 client credentials 的方式获取用于同步的 token
            _logger.LogInformation($"Get Token from {authority} before sync perms...");
            var token = await _api.GetTokenAsync(authority, nameof(SyncPermissionsAsync), clientId, clientSecret, Constants.IAM_API_SCOPE, _logger);

            _logger.LogInformation($"Start sync perms...");
            var result = await _api.SyncPermissionsAsync(model, token);

            if (result.IsSucceed)
            {
                return(true);
            }
            else
            {
                _logger.LogWarning($"子系统({clientId})同步权限失败!{result.Message}");
                return(false);
            }
        }
Пример #2
0
        /// <summary>
        /// 同步权限
        /// </summary>
        /// <param name="model"></param>
        /// <param name="accessToken">当前登陆用户的 access token,默认不需要提供,如果需要使用其他 access token 才需要提供</param>
        /// <returns></returns>
        internal async Task <ApiResult> SyncPermissionsAsync(SyncPermissionsDto model, string accessToken = null)
        {
            if (model == null)
            {
                return(new ApiResult
                {
                    IsSucceed = true
                });
            }

            if (accessToken == null)
            {
                if (_httpContextAccessor.HttpContext == null)
                {
                    return(new ApiResult
                    {
                        IsSucceed = false,
                        Message = "HttpContext 为空"
                    });
                }

                accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

                if (accessToken == null)
                {
                    return(new ApiResult
                    {
                        IsSucceed = false,
                        Message = "Access Token 为空"
                    });
                }
            }

            _httpClient.SetBearerToken(accessToken);

            int statusCode = -1;

            try
            {
                StringContent body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
                var           resp = await _httpClient.PutAsync($"{_options.Authority.TrimEnd('/')}/admin/api/permissionbatch", body);

                statusCode = (int)resp.StatusCode;

                await resp.WhenResponseSuccess();

                _logger.LogInformation("Sync Perm Succeeded.");

                return(new ApiResult
                {
                    IsSucceed = true,
                    StatusCode = (int)resp.StatusCode
                });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, $"调用 IamApi 的 {nameof(SyncPermissionsAsync)} 失败");
                return(new ApiResult
                {
                    IsSucceed = false,
                    StatusCode = statusCode,
                    Message = ex.Message
                });
            }
        }