如何在 Ocelot 中将 cookie 值转换为 header 值
How do you transform a cookie value into a header value in Ocelot
我在 dotnet 核心中使用 micro-services 架构。
我将 Ocelot 作为 api-gateway (BFF) 放在前面。
我的主要 Web 应用程序使用 cookie 身份验证和 cookie 中的 jwt 令牌。
这是为了向后兼容。
我所有的新 api 都使用不记名身份验证。
我想在 Ocelot 中从 cookie 中获取值并将其插入 header.
我在配置文件中看到了 header 个值。
然而,由于动态特性,这将需要代码实现。
推荐的实施方法是什么?
我们需要更改我们访问令牌的header,所以在 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都不在乎!
我在 dotnet 核心中使用 micro-services 架构。 我将 Ocelot 作为 api-gateway (BFF) 放在前面。 我的主要 Web 应用程序使用 cookie 身份验证和 cookie 中的 jwt 令牌。 这是为了向后兼容。 我所有的新 api 都使用不记名身份验证。 我想在 Ocelot 中从 cookie 中获取值并将其插入 header.
我在配置文件中看到了 header 个值。 然而,由于动态特性,这将需要代码实现。 推荐的实施方法是什么?
我们需要更改我们访问令牌的header,所以在 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都不在乎!