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(); services.Configure(configuration.GetSection("RolesAuthorizer")); return services; } public static IApplicationBuilder UseMyOcelot(this WebApplication app) { app.UseMiddleware(); app.UseOcelot(new OcelotPipelineConfiguration { PreQueryStringBuilderMiddleware = async (context, next) => { var claimsParser = app.Services.GetRequiredService(); 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(); var result = await rolesAuthorizer.Authorize(values.Data, url); if (result.IsError) { context.Items.UpsertErrors(result.Errors); return; } await next.Invoke(); } }).Wait(); return app; } } }