首页 > 解决方案 > 如何将 cookie 值转换为 Ocelot 中的标头值

问题描述

我在 dotnet core 中使用微服务架构。我将 Ocelot 作为 api-gateway (BFF) 放在前面。我的主要 Web 应用程序使用 cookie 身份验证和 cookie 中的 jwt 令牌。这是为了向后兼容。我所有的新 API 都使用不记名身份验证。我想在 Ocelot 中从 cookie 中获取值并将其插入到标题中。

我已经看到在配置文件中添加了标头值。然而,由于动态特性,这将需要代码实现。实施此建议的方法是什么?

标签: .net-coreapi-gatewayocelot

解决方案


我们需要更改访问令牌的标头,因此在 Ocelot 中我们这样做了:

public class SecurityTokenHandler : DelegatingHandler
    {
        private const string Racoon = "Badger";

        private readonly IHttpContextAccessor contextAccessor;

        public SecurityTokenHandler(IHttpContextAccessor contextAccessor)
        {
            this.contextAccessor = contextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var httpRequest = this.contextAccessor.HttpContext.Request;

            var securityToken = httpRequest.GetSecurityTokenFromHeader();

            if (!string.IsNullOrWhiteSpace(securityToken))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue(Racoon , securityToken);

                request.Headers.Remove(Constants.OurOldAccessToken);
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }

像这样注册:

services.AddDelegatingHandler<SecurityTokenHandler>(true);

效果很好,单点处理,我们所有的 BFF、MS 都不在乎!


推荐阅读