using Flurl; using Flurl.Http; using HuiXin.Gateway.Ocelot.Configurations; using Microsoft.Extensions.Options; using Ocelot.Errors; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Responses; using Serilog; namespace HuiXin.Gateway.Ocelot.Authorizers { public class HttpRolesAuthorizer : RolesAuthorizerBase, IRolesAuthorizer { private readonly string _url; private readonly FlurlClient _client; public HttpRolesAuthorizer(IClaimsParser claimsParser, IOptions configuration) : base(claimsParser, configuration) { _url = _configs.Url ?? throw new Exception("未配置角色验证的Url地址"); _client = new FlurlClient(_url); _client.Settings.Timeout = TimeSpan.FromMilliseconds(_configs.Timeout); _client.Settings.Redirects.Enabled = false; } public async Task> Authorize(List roles, string path) { try { bool pass = await _client.Request().AppendQueryParam("roles", roles).AppendQueryParam("path", path).GetJsonAsync(); if (pass) { return await ReturnAsync(new OkResponse(true)); } else { return await ReturnAsync(new ErrorResponse(new HttpRolesAuthorizerFail("用户没有访问权限"))); } } catch (Exception ex) { Log.Error(ex.Message, "验证用户角色权限出错"); return await ReturnAsync(new ErrorResponse(new HttpRolesAuthorizerError("验证用户角色权限出错"))); } } } public class HttpRolesAuthorizerError(string message) : Error(message, OcelotErrorCode.UnableToCompleteRequestError, 500){} public class HttpRolesAuthorizerFail(string message) : Error(message, OcelotErrorCode.UnauthorizedError, 403){} }