重定向时授权 header 丢失
Authorization header is lost on redirect
下面是执行身份验证、生成授权 header 并调用 API.
的代码
不幸的是,我在 API 上的 GET
请求后收到 401 Unauthorized
错误。
但是,当我在 Fiddler 中捕获流量并重放时,对 API 的调用成功并且我可以看到所需的 200 OK
状态代码。
[Test]
public void RedirectTest()
{
HttpResponseMessage response;
var client = new HttpClient();
using (var authString = new StringContent(@"{username: ""theUser"", password: ""password""}", Encoding.UTF8, "application/json"))
{
response = client.PostAsync("http://host/api/authenticate", authString).Result;
}
string result = response.Content.ReadAsStringAsync().Result;
var authorization = JsonConvert.DeserializeObject<CustomAutorization>(result);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorization.Scheme, authorization.Token);
client.DefaultRequestHeaders.Add("Accept", "application/vnd.host+json;version=1");
response =
client.GetAsync("http://host/api/getSomething").Result;
Assert.True(response.StatusCode == HttpStatusCode.OK);
}
当我 运行 此代码时,授权 header 丢失。
但是在Fiddler中header是通过成功的
知道我做错了什么吗?
您遇到此行为的原因是设计。
大多数 HTTP 客户端(默认情况下)在进行重定向时删除授权 header。
一个原因是安全。客户端可能会被重定向到不受信任的第三方服务器,您不希望向其透露您的授权令牌。
您可以做的是检测是否发生了重定向,然后直接向正确的位置重新发出请求。
您的 API 返回 401 Unauthorized
表明授权 header 丢失(或不完整)。如果授权信息存在于请求中但只是不正确(错误的用户名/密码),我将假设相同的 API returns 403 Forbidden
。
如果是这种情况,您可以检测'redirect / missing authorization header'组合并重新发送请求。
这里是重写的问题代码:
[Test]
public void RedirectTest()
{
// These lines are not relevant to the problem, but are included for completeness.
HttpResponseMessage response;
var client = new HttpClient();
using (var authString = new StringContent(@"{username: ""theUser"", password: ""password""}", Encoding.UTF8, "application/json"))
{
response = client.PostAsync("http://host/api/authenticate", authString).Result;
}
string result = response.Content.ReadAsStringAsync().Result;
var authorization = JsonConvert.DeserializeObject<CustomAutorization>(result);
// Relevant from this point on.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorization.Scheme, authorization.Token);
client.DefaultRequestHeaders.Add("Accept", "application/vnd.host+json;version=1");
var requestUri = new Uri("http://host/api/getSomething");
response = client.GetAsync(requestUri).Result;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// Authorization header has been set, but the server reports that it is missing.
// It was probably stripped out due to a redirect.
var finalRequestUri = response.RequestMessage.RequestUri; // contains the final location after following the redirect.
if (finalRequestUri != requestUri) // detect that a redirect actually did occur.
{
if (IsHostTrusted(finalRequestUri)) // check that we can trust the host we were redirected to.
{
response = client.GetAsync(finalRequestUri).Result; // Reissue the request. The DefaultRequestHeaders configured on the client will be used, so we don't have to set them again.
}
}
}
Assert.True(response.StatusCode == HttpStatusCode.OK);
}
private bool IsHostTrusted(Uri uri)
{
// Do whatever checks you need to do here
// to make sure that the host
// is trusted and you are happy to send it
// your authorization token.
if (uri.Host == "host")
{
return true;
}
return false;
}
请注意,您可以保存 finalRequestUri
的值并将其用于以后的请求,以避免重试中涉及的额外请求。然而,由于这是一个临时重定向,您应该每次都将请求发送到原始位置。
我遇到了类似的问题,但不完全相同。就我而言,我也遇到了重定向问题,但安全性是通过 OAuth 实现的,它也有次要但相关的问题,即令牌有时会过期。
出于这个原因,我希望能够配置 HttpClient
以在收到 401 Unauthorized
响应时自动刷新 OAuth 令牌,而不管发生这种情况是否是因为重定向或令牌过期。
Chris O'Neill 发布的解决方案显示了要采取的一般步骤,但我想将该行为嵌入到 HttpClient
object 中,而不是必须包围我们所有的 HTTP 代码带有命令式检查。我们有很多使用共享 HttpClient
object 的现有代码,因此如果我可以更改 object.[=23] 的行为,重构我们的代码会容易得多=]
以下看起来有效。到目前为止,我只是制作了它的原型,但它似乎在工作。我们的大部分代码库都在 F# 中,因此代码在 F# 中:
open System.Net
open System.Net.Http
type TokenRefresher (refreshAuth, inner) =
inherit MessageProcessingHandler (inner)
override __.ProcessRequest (request, _) = request
override __.ProcessResponse (response, cancellationToken) =
if response.StatusCode <> HttpStatusCode.Unauthorized
then response
else
response.RequestMessage.Headers.Authorization <- refreshAuth ()
inner.SendAsync(response.RequestMessage, cancellationToken).Result
这是一个小 class,它负责在收到 401 Unauthorized
响应时刷新 Authorization
header。它使用注入的 refreshAuth
函数进行刷新,该函数的类型为 unit -> Headers.AuthenticationHeaderValue
.
由于这仍然是原型代码,我将内部 SendAsync
调用设为阻塞调用,从而将其作为 reader 的练习,以使用异步工作流正确实现它。
给定一个名为 refreshAuth
的刷新函数,您可以像这样创建一个新的 HttpClient
object:
let client = new HttpClient(new TokenRefresher(refreshAuth, new HttpClientHandler ()))
Chris O'Neill 发布的答案仔细检查新 URL 是否仍然被认为是安全的。我在这里跳过了安全考虑,但您应该强烈考虑在重试请求之前包括类似的检查。
我会关闭自动重定向行为并创建一个隐藏处理临时重定向的代码的客户端处理程序。 HttpClient
class 允许您安装 DelegatingHandler
s,您可以从中修改响应请求。
public class TemporaryRedirectHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
var location = response.Headers.Location;
if (location == null)
{
return response;
}
using (var clone = await CloneRequest(request, location))
{
response = await base.SendAsync(clone, cancellationToken);
}
}
return response;
}
private async Task<HttpRequestMessage> CloneRequest(HttpRequestMessage request, Uri location)
{
var clone = new HttpRequestMessage(request.Method, location);
if (request.Content != null)
{
clone.Content = await CloneContent(request);
if (request.Content.Headers != null)
{
CloneHeaders(clone, request);
}
}
clone.Version = request.Version;
CloneProperties(clone, request);
CloneKeyValuePairs(clone, request);
return clone;
}
private async Task<StreamContent> CloneContent(HttpRequestMessage request)
{
var memstrm = new MemoryStream();
await request.Content.CopyToAsync(memstrm).ConfigureAwait(false);
memstrm.Position = 0;
return new StreamContent(memstrm);
}
private void CloneHeaders(HttpRequestMessage clone, HttpRequestMessage request)
{
foreach (var header in request.Content.Headers)
{
clone.Content.Headers.Add(header.Key, header.Value);
}
}
private void CloneProperties(HttpRequestMessage clone, HttpRequestMessage request)
{
foreach (KeyValuePair<string, object> prop in request.Properties)
{
clone.Properties.Add(prop);
}
}
private void CloneKeyValuePairs(HttpRequestMessage clone, HttpRequestMessage request)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
}
您可以像这样实例化 HttpClient:
var handler = new TemporaryRedirectHandler()
{
InnerHandler = new HttpClientHandler()
{
AllowAutoRedirect = false
}
};
HttpClient client = new HttpClient(handler);
下面是执行身份验证、生成授权 header 并调用 API.
的代码不幸的是,我在 API 上的 GET
请求后收到 401 Unauthorized
错误。
但是,当我在 Fiddler 中捕获流量并重放时,对 API 的调用成功并且我可以看到所需的 200 OK
状态代码。
[Test]
public void RedirectTest()
{
HttpResponseMessage response;
var client = new HttpClient();
using (var authString = new StringContent(@"{username: ""theUser"", password: ""password""}", Encoding.UTF8, "application/json"))
{
response = client.PostAsync("http://host/api/authenticate", authString).Result;
}
string result = response.Content.ReadAsStringAsync().Result;
var authorization = JsonConvert.DeserializeObject<CustomAutorization>(result);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorization.Scheme, authorization.Token);
client.DefaultRequestHeaders.Add("Accept", "application/vnd.host+json;version=1");
response =
client.GetAsync("http://host/api/getSomething").Result;
Assert.True(response.StatusCode == HttpStatusCode.OK);
}
当我 运行 此代码时,授权 header 丢失。
但是在Fiddler中header是通过成功的
知道我做错了什么吗?
您遇到此行为的原因是设计。
大多数 HTTP 客户端(默认情况下)在进行重定向时删除授权 header。
一个原因是安全。客户端可能会被重定向到不受信任的第三方服务器,您不希望向其透露您的授权令牌。
您可以做的是检测是否发生了重定向,然后直接向正确的位置重新发出请求。
您的 API 返回 401 Unauthorized
表明授权 header 丢失(或不完整)。如果授权信息存在于请求中但只是不正确(错误的用户名/密码),我将假设相同的 API returns 403 Forbidden
。
如果是这种情况,您可以检测'redirect / missing authorization header'组合并重新发送请求。
这里是重写的问题代码:
[Test]
public void RedirectTest()
{
// These lines are not relevant to the problem, but are included for completeness.
HttpResponseMessage response;
var client = new HttpClient();
using (var authString = new StringContent(@"{username: ""theUser"", password: ""password""}", Encoding.UTF8, "application/json"))
{
response = client.PostAsync("http://host/api/authenticate", authString).Result;
}
string result = response.Content.ReadAsStringAsync().Result;
var authorization = JsonConvert.DeserializeObject<CustomAutorization>(result);
// Relevant from this point on.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorization.Scheme, authorization.Token);
client.DefaultRequestHeaders.Add("Accept", "application/vnd.host+json;version=1");
var requestUri = new Uri("http://host/api/getSomething");
response = client.GetAsync(requestUri).Result;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// Authorization header has been set, but the server reports that it is missing.
// It was probably stripped out due to a redirect.
var finalRequestUri = response.RequestMessage.RequestUri; // contains the final location after following the redirect.
if (finalRequestUri != requestUri) // detect that a redirect actually did occur.
{
if (IsHostTrusted(finalRequestUri)) // check that we can trust the host we were redirected to.
{
response = client.GetAsync(finalRequestUri).Result; // Reissue the request. The DefaultRequestHeaders configured on the client will be used, so we don't have to set them again.
}
}
}
Assert.True(response.StatusCode == HttpStatusCode.OK);
}
private bool IsHostTrusted(Uri uri)
{
// Do whatever checks you need to do here
// to make sure that the host
// is trusted and you are happy to send it
// your authorization token.
if (uri.Host == "host")
{
return true;
}
return false;
}
请注意,您可以保存 finalRequestUri
的值并将其用于以后的请求,以避免重试中涉及的额外请求。然而,由于这是一个临时重定向,您应该每次都将请求发送到原始位置。
我遇到了类似的问题,但不完全相同。就我而言,我也遇到了重定向问题,但安全性是通过 OAuth 实现的,它也有次要但相关的问题,即令牌有时会过期。
出于这个原因,我希望能够配置 HttpClient
以在收到 401 Unauthorized
响应时自动刷新 OAuth 令牌,而不管发生这种情况是否是因为重定向或令牌过期。
Chris O'Neill 发布的解决方案显示了要采取的一般步骤,但我想将该行为嵌入到 HttpClient
object 中,而不是必须包围我们所有的 HTTP 代码带有命令式检查。我们有很多使用共享 HttpClient
object 的现有代码,因此如果我可以更改 object.[=23] 的行为,重构我们的代码会容易得多=]
以下看起来有效。到目前为止,我只是制作了它的原型,但它似乎在工作。我们的大部分代码库都在 F# 中,因此代码在 F# 中:
open System.Net
open System.Net.Http
type TokenRefresher (refreshAuth, inner) =
inherit MessageProcessingHandler (inner)
override __.ProcessRequest (request, _) = request
override __.ProcessResponse (response, cancellationToken) =
if response.StatusCode <> HttpStatusCode.Unauthorized
then response
else
response.RequestMessage.Headers.Authorization <- refreshAuth ()
inner.SendAsync(response.RequestMessage, cancellationToken).Result
这是一个小 class,它负责在收到 401 Unauthorized
响应时刷新 Authorization
header。它使用注入的 refreshAuth
函数进行刷新,该函数的类型为 unit -> Headers.AuthenticationHeaderValue
.
由于这仍然是原型代码,我将内部 SendAsync
调用设为阻塞调用,从而将其作为 reader 的练习,以使用异步工作流正确实现它。
给定一个名为 refreshAuth
的刷新函数,您可以像这样创建一个新的 HttpClient
object:
let client = new HttpClient(new TokenRefresher(refreshAuth, new HttpClientHandler ()))
Chris O'Neill 发布的答案仔细检查新 URL 是否仍然被认为是安全的。我在这里跳过了安全考虑,但您应该强烈考虑在重试请求之前包括类似的检查。
我会关闭自动重定向行为并创建一个隐藏处理临时重定向的代码的客户端处理程序。 HttpClient
class 允许您安装 DelegatingHandler
s,您可以从中修改响应请求。
public class TemporaryRedirectHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
var location = response.Headers.Location;
if (location == null)
{
return response;
}
using (var clone = await CloneRequest(request, location))
{
response = await base.SendAsync(clone, cancellationToken);
}
}
return response;
}
private async Task<HttpRequestMessage> CloneRequest(HttpRequestMessage request, Uri location)
{
var clone = new HttpRequestMessage(request.Method, location);
if (request.Content != null)
{
clone.Content = await CloneContent(request);
if (request.Content.Headers != null)
{
CloneHeaders(clone, request);
}
}
clone.Version = request.Version;
CloneProperties(clone, request);
CloneKeyValuePairs(clone, request);
return clone;
}
private async Task<StreamContent> CloneContent(HttpRequestMessage request)
{
var memstrm = new MemoryStream();
await request.Content.CopyToAsync(memstrm).ConfigureAwait(false);
memstrm.Position = 0;
return new StreamContent(memstrm);
}
private void CloneHeaders(HttpRequestMessage clone, HttpRequestMessage request)
{
foreach (var header in request.Content.Headers)
{
clone.Content.Headers.Add(header.Key, header.Value);
}
}
private void CloneProperties(HttpRequestMessage clone, HttpRequestMessage request)
{
foreach (KeyValuePair<string, object> prop in request.Properties)
{
clone.Properties.Add(prop);
}
}
private void CloneKeyValuePairs(HttpRequestMessage clone, HttpRequestMessage request)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
}
您可以像这样实例化 HttpClient:
var handler = new TemporaryRedirectHandler()
{
InnerHandler = new HttpClientHandler()
{
AllowAutoRedirect = false
}
};
HttpClient client = new HttpClient(handler);