| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Authentication;
- using Ocelot.Configuration;
- using Ocelot.Logging;
- using Ocelot.Middleware;
- using System.Threading.Tasks;
- using Ocelot.DownstreamRouteFinder.Middleware;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Caching.Memory;
- using System.Collections.Generic;
- using System.Linq;
- namespace QM.Gateway.Uses
- {
- /// <summary>
- /// 中间件,授权白名单
- /// </summary>
- public class AllowAnonymousMiddleware : OcelotMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly IConfiguration _configuration;
- private readonly IMemoryCache _memoryCache;
- public AllowAnonymousMiddleware(RequestDelegate next,
- IConfiguration configuration,
- IMemoryCache memoryCache,
- IOcelotLoggerFactory loggerFactory)
- : base(loggerFactory.CreateLogger<AuthenticationMiddleware>())
- {
- _next = next;
- _configuration = configuration;
- _memoryCache = memoryCache;
- }
- public async Task Invoke(HttpContext httpContext)
- {
- var downstreamRoute = httpContext.Items.DownstreamRoute();
- //添加配置,如果路由为白名单就直接过
- if (IsAllowAnonymous(httpContext))
- {
- Logger.LogInformation($"路由白名单:{httpContext.Request.Path}");
- await _next.Invoke(httpContext);
- }
- else if (httpContext.Request.Method.ToUpper() != "OPTIONS" && IsAuthenticatedRoute(downstreamRoute))
- {
- Logger.LogInformation($"{httpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated");
- var result = await httpContext.AuthenticateAsync(downstreamRoute.AuthenticationOptions.AuthenticationProviderKey);
- httpContext.User = result.Principal;
- if (httpContext.User.Identity.IsAuthenticated)
- {
- Logger.LogInformation($"Client has been authenticated for {httpContext.Request.Path}");
- await _next.Invoke(httpContext);
- }
- else
- {
- var error = new UnauthenticatedError(
- $"Request for authenticated route {httpContext.Request.Path} by {httpContext.User.Identity.Name} was unauthenticated");
- Logger.LogWarning($"Client has NOT been authenticated for {httpContext.Request.Path} and pipeline error set. {error}");
- httpContext.Items.SetError(error);
- }
- }
- else
- {
- Logger.LogInformation($"No authentication needed for {httpContext.Request.Path}");
- await _next.Invoke(httpContext);
- }
- }
- private static bool IsAuthenticatedRoute(DownstreamRoute route)
- {
- return route.IsAuthenticated;
- }
- /// <summary>
- /// 是否白名单
- /// </summary>
- /// <param name="httpContext"></param>
- /// <returns></returns>
- private bool IsAllowAnonymous(HttpContext httpContext)
- {
- var alls = _memoryCache.Get("AllowAnonymous");
- List<string> list = new List<string>();
- if(alls == null)
- {
- IConfigurationSection myArraySection = _configuration.GetSection("AllowAnonymous");
- list = myArraySection.AsEnumerable().Where(t => t.Value != null).Select(t => t.Value.ToLower().Trim()).ToList();
- _memoryCache.Set("AllowAnonymous", list);
- }
- else
- {
- list = alls as List<string>;
- }
- var res = list.Contains(httpContext.Request.Path.Value.ToLower().Trim());
- return res;
- }
- }
- }
|