【问题标题】:How do you transform a cookie value into a header value in Ocelot如何将 cookie 值转换为 Ocelot 中的标头值
【发布时间】:2020-01-24 12:56:17
【问题描述】:

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

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

【问题讨论】:

    标签: .net-core api-gateway ocelot


    【解决方案1】:

    我们需要更改访问令牌的标头,因此在 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 都不在乎!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多