中间件
public class CustomOcelotMiddleware : Ocelot.Middleware.OcelotMiddleware { private readonly RequestDelegate _next; public IConfiguration _configuration; private readonly IAuth _authUtil; private readonly SysLogApp _logApp; private readonly RemoteAccountService _remoterService; /// <summary> /// /// </summary> /// <param name="next"></param> /// <param name="configuration"></param> /// <param name="responder"></param> /// <param name="authUtil"></param> /// <param name="logApp"></param> /// <param name="remoterService"></param> /// <param name="loggerFactory"></param> public CustomOcelotMiddleware(RequestDelegate next, IConfiguration configuration, IAuth authUtil, SysLogApp logApp, RemoteAccountService remoterService, IOcelotLoggerFactory loggerFactory) : base(loggerFactory.CreateLogger<CustomOcelotMiddleware>()) { _next = next; _configuration = configuration; _authUtil = authUtil; _remoterService = remoterService; _logApp = logApp; } /// <summary> /// /// </summary> /// <param name="httpContext"></param> /// <returns></returns> public async Task Invoke(HttpContext httpContext) { //验证token if (!_authUtil.CheckLogin()) { httpContext.Response.ContentType = "text/plain; charset=utf-8"; httpContext.Response.StatusCode = 401; await httpContext.Response.WriteAsync("认证失败,请提供认证信息", Encoding.UTF8); return; } await _next.Invoke(httpContext); } }
使用
app.UseMiddleware<CustomOcelotMiddleware>(); //后台默认登陆,远程登录用来做普通账号核远程服务的通信,方便实现普通用户查看客户池等相关功能。 var task = remoterService.RemoteLogin(); app.UseOcelot().Wait();
最后验证
替换当前token为调用的下级api的token,也可以在上面那个中间件写
public class RequestAuthoritarianHandler : DelegatingHandler { private readonly RemoteAccountService _remoterService; /// <summary> /// /// </summary> public RequestAuthoritarianHandler(RemoteAccountService remoteAccountService) { _remoterService = remoteAccountService; } /// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var newValue = await _remoterService.GetRemoteAuthorization(); request.Headers.Remove(HeaderAuthenticationDefaults.AuthenticationSchema); request.Headers.Add(HeaderAuthenticationDefaults.AuthenticationSchema, newValue); var result = await base.SendAsync(request, cancellationToken); return result; } }
使用在
services.AddOcelot(Configuration) .AddConsul() .AddDelegatingHandler<RequestAuthoritarianHandler>(true);
标签:authUtil,自定义,private,token,ocelot,httpContext,remoterService,public From: https://www.cnblogs.com/shuaimeng/p/18215535