问题
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