You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
2.0 KiB
49 lines
2.0 KiB
10 months ago
|
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<RolesAuthorizerConfiguration> 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<Response<bool>> Authorize(List<string> roles, string path)
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
bool pass = await _client.Request().AppendQueryParam("roles", roles).AppendQueryParam("path", path).GetJsonAsync<bool>();
|
||
|
if (pass)
|
||
|
{
|
||
|
return await ReturnAsync(new OkResponse<bool>(true));
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
return await ReturnAsync(new ErrorResponse<bool>(new HttpRolesAuthorizerFail("用户没有访问权限")));
|
||
|
}
|
||
|
}
|
||
|
catch (Exception ex)
|
||
|
{
|
||
|
Log.Error(ex.Message, "验证用户角色权限出错");
|
||
|
return await ReturnAsync(new ErrorResponse<bool>(new HttpRolesAuthorizerError("验证用户角色权限出错")));
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public class HttpRolesAuthorizerError(string message) : Error(message, OcelotErrorCode.UnableToCompleteRequestError, 500){}
|
||
|
public class HttpRolesAuthorizerFail(string message) : Error(message, OcelotErrorCode.UnauthorizedError, 403){}
|
||
|
}
|