.NET Core 微服务 - API 网关之 Ocelot 自己写中间件实现自己的认证逻辑

作者:vkvi 来源:ITPOW(原创) 日期:2022-4-1

微服务的认证,有很多种模式:可以完全交给网关,可以网关完全放行交给各个 API 自行处理,还可以混合。网上很多人说 JWTIdentityServer4 这些,其实哪有那么多规矩,凭啥都要用别人的认证机制?就没有我们自己的模式与机制?

本文介绍我们自己在网关做认证的方法,当然示例仅仅是示例只是说说应用 Ocelot 中间件的方法。

派生一个 Ocelot 中间件

using Microsoft.Extensions.Caching.Memory;
using Ocelot.Logging;
using Ocelot.Middleware;


public class UrlBasedAuthenticationMiddleware : OcelotMiddleware
{
    private readonly IConfiguration _configuration;
    private readonly IMemoryCache _memoryCache;
    private readonly RequestDelegate _next;


    public UrlBasedAuthenticationMiddleware(RequestDelegate next, IConfiguration configuration, IMemoryCache memoryCache, IOcelotLoggerFactory loggerFactory) : base(loggerFactory.CreateLogger<UrlBasedAuthenticationMiddleware>())
    {
        _next = next;

        _configuration = configuration;
        _memoryCache = memoryCache;
    }


    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Query["userId"].FirstOrDefault() != "itpow")
        {
            httpContext.Response.StatusCode = 403;
            await httpContext.Response.WriteAsync("Forbidden.");
            return;
        }

        await _next.Invoke(httpContext);
    }
}

当 QueryString 中 userId 不是 itpow 时,返回 403。

Program.cs 中使用这个中间件

.Configure(app =>
{
    app.UseMiddleware<UrlBasedAuthenticationMiddleware>();
    app.UseOcelot().Wait();
})

增加了 UseMiddleware 这个。

测试

现在访问,返回 Forbidden,URL 中加上 ?userId=itpow,正常出结果。

相关文章