我有一个 OAuthServerProvider 在验证用户名和密码后发出令牌。当用户名或密码无效时,我拒绝 owin 上下文,默认情况下它将400 Bad Request
作为状态码返回。
但我想回应401 Unauthorized
为了实现这一点,我编写了一个中间件,它将检查标头并查看是否存在自定义标头,如果存在则将状态代码替换为 401。
if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey(Constants.OwinChallengeFlag))
{
var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag);
context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
context.Response.Headers.Remove(Constants.OwinChallengeFlag);
}
当我用 fiddler 击中它时,这绝对可以正常工作,但是我在下面编写的单元测试总是得到 400。不知何故,当我用单元测试发出请求时,中间件被跳过了。
[TestFixture]
public class UnitTest1
{
private TestServer _server;
[SetUp]
public void SetUp()
{
_server = TestServer.Create<Startup>();
}
[Test]
public void ShouldReturnUnauthorizedResponse()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/token");
//wrong password
var requestContent = "grant_type=password&UserName=foo&Password=bar";
request.Content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = _server.HttpClient.SendAsync(request).Result;
//This assert fails, but shouldn't
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
}
}
需要知道我在这里做错了什么。