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.

64 lines
2.5 KiB

using HuiXin.Gateway.Ocelot.Authorizers;
using HuiXin.Gateway.Ocelot.Configurations;
using HuiXin.Gateway.Ocelot.Middlewares;
using Ocelot.Authorization;
using Ocelot.DependencyInjection;
using Ocelot.Infrastructure.Claims.Parser;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using System.Security.Claims;
namespace HuiXin.Gateway.Ocelot.Extensions
{
public static class OcelotExtensions
{
public static IServiceCollection AddMyOcelot(this IServiceCollection services, IConfiguration configuration)
{
services.AddOcelot().AddConsul();
services.AddSingleton<IRolesAuthorizer, HttpRolesAuthorizer>();
services.Configure<RolesAuthorizerConfiguration>(configuration.GetSection("RolesAuthorizer"));
return services;
}
public static IApplicationBuilder UseMyOcelot(this WebApplication app)
{
app.UseMiddleware<AccessLoggingMiddleware>();
app.UseOcelot(new OcelotPipelineConfiguration
{
PreQueryStringBuilderMiddleware = async (context, next) =>
{
var claimsParser = app.Services.GetRequiredService<IClaimsParser>();
var values = claimsParser.GetValuesByClaimType(context.User.Claims, ClaimsIdentity.DefaultRoleClaimType);
if (values.IsError)
{
context.Items.UpsertErrors(values.Errors);
return;
}
if (values.Data == null || values.Data.Count == 0)
{
context.Items.SetError(new UserDoesNotHaveClaimError("token中未包含角色信息"));
return;
}
var downstreamRoute = context.Items.DownstreamRoute();
var url = downstreamRoute.DownstreamPathTemplate.Value;
context.Items.TemplatePlaceholderNameAndValues().ForEach(nv =>
{
url = url.Replace(nv.Name, nv.Value);
});
var rolesAuthorizer = app.Services.GetRequiredService<IRolesAuthorizer>();
var result = await rolesAuthorizer.Authorize(values.Data, url);
if (result.IsError)
{
context.Items.UpsertErrors(result.Errors);
return;
}
await next.Invoke();
}
}).Wait();
return app;
}
}
}