How do you transform a cookie value into a header value in Ocelot

感情迁移 提交于 2021-02-10 14:14:32

问题


I am using a micro-services architecture in dotnet core. I am putting Ocelot in front as an api-gateway (BFF). My main web application uses cookie auth with the jwt token in the cookie. This is for backwards compatibility. All my new apis use bearer auth. I would like to in Ocelot get the value out of the cookie and insert it into the header.

I have seen header values added in the configuration file. This however will need a code implementation due to the dynamic nature. What is the recommended approach for implementing this?


回答1:


We had a requirement to change the header for our access token so in Ocelot we did this:

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);
        }
    }

Register like this:

services.AddDelegatingHandler<SecurityTokenHandler>(true);

Works great, single point to deal with, all our BFFs, MSs do not care!



来源:https://stackoverflow.com/questions/58079641/how-do-you-transform-a-cookie-value-into-a-header-value-in-ocelot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!