首页 > 解决方案 > Ocelot 文档 - 身份验证

问题描述

我正在尝试学习并考虑将我当前的 asp.net api 拆分为一堆较小的 api,以尝试制作微服务应用程序(主要用于学习目的)。我使用 Ocelot 作为网关,我发现 Ocelot 很不错且易于设置。但是,我发现很难找到合适的文档,例如如何添加身份验证,因为 ocelot.readthedocs.io 在这方面感觉很糟糕。我很难确定是否应该在网关 api 中创建注册和登录方法,还是仍然将其单独保存在保存用户数据库的微服务中?也许我应该将网关 api 连接到用户数据库以进行直接交互?(感觉它违背了微服务的目的)。

对我来说,与在单体应用程序中对 http 方法进行身份验证相比,仅对重新路由进行身份验证听起来有点不安全。但我可能只是错过了重点。否则,如果你们知道任何重要的信息来源,那就太好了,因为我很难找到有关 ocelot 和 asp.net 微服务的文章、教程、课程或任何类似性质的东西。

标签: asp.netasp.net-coreasp.net-web-apiocelot

解决方案


我们正在使用相同的微服务方法,并通过覆盖标准的 ocelot 身份验证中间件来解决它。

在配置部分的启动(.net core)中,我们实现它如下:

 public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            OcelotPipelineConfiguration ocelotConfig = new OcelotPipelineConfiguration
            {
                AuthenticationMiddleware = async (ctx, next) =>
                {
                    try
                    {
                        AuthenticationClient.Authenticate(Configuration, ctx.HttpContext, new List<string>());
                        IEnumerable<string> allowedRoles = ctx.DownstreamReRoute.RouteClaimsRequirement.Select(e => e.Value).ToList();
                        if(allowedRoles != null && allowedRoles.Count() > 0)
                        {
                            string userId= AuthenticationClient.Authenticate(Configuration, ctx.HttpContext, allowedRoles);
                            ctx.DownstreamReRoute.AddHeadersToDownstream.Add(new AddHeader("userId", userId));
                        }
                    }catch(ApiGateway.Core.Exceptions.ForbiddenException e)
                    {
                        ctx.Errors.Add(new ApiGateway.WebApi.Exceptions.ForbiddenException(e.Message, Ocelot.Errors.OcelotErrorCode.UnauthorizedError));
                    }
                    catch(Exception e)
                    {
                        ctx.Errors.Add(new UnauthenticatedError(e.Message));
                    }
                    await next.Invoke();
                },
                AuthorisationMiddleware = async (ctx, next) =>
                {
                    await next.Invoke();
                }
            };


解释:

首先,用户使用bearer-jwt-tokenhttp-Header 中的(或 Basic)进行身份验证。

然后从 Ocelot-Settings (Section ) 中读取允许的角色/权限(我们将活动目录组作为角色RouteClaimsRequirement)。

如果用户具有允许的角色/权限之一,我们将获取 userId 并将其添加到转发到相应服务的 http-request 标头中。因此,目标服务了解用户。

To me, it also sounds kind of insecure to only authenticate the reroutes,

通常微服务本身不能直接访问,并且部署在后面的服务器层。只允许 API-Gateway 访问它们。优点是,您的微服务不需要关心身份验证、授权等。

希望它能澄清你的问题。


推荐阅读