晚了将近 6 年,但仍然可能会有所帮助。基于此的解决方案:
https ://blogs.taiga.nl/martijn/2016/03/10/asp-net-web-api-owin-authenticated-integration-tests-without-authorization-server/
首先,在创建 Owin TestServer 时,您必须创建 DataProtector:
private readonly TestServer _testServer;
public IDataProtector DataProtector { get; private set; }
public Server(OwinStartup startupConfig)
{
_testServer = TestServer.Create(builder =>
{
DataProtector = builder.CreateDataProtector(
typeof(CookieAuthenticationMiddleware).FullName, DefaultAuthenticationTypes.ApplicationCookie, "v1");
startupConfig.Configuration(builder);
});
}
然后像这样生成 cookie(使用上一步中创建的 DataProtector):
public string GeterateCookie()
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Role, "your-role"),
new Claim(ClaimTypes.UserData, "user-data"),
new Claim(ClaimTypes.Name, "your-name")
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
var tdf = new TicketDataFormat(DataProtector);
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {ExpiresUtc = DateTime.UtcNow.AddHours(1)});
var protectedCookieValue = tdf.Protect(ticket);
var cookie = new CookieHeaderValue("yourCookie", protectedCookieValue)
{
Path = "/",
HttpOnly = true
};
return cookie.ToString();
}
确保设置所需的声明,根据提供给 UseCookieAuthentication 方法的设置初始化 ClaimsIdentity,并设置正确的 CookieName。
最后一步是将 CookieHeader 添加到您的请求中:
public Task<HttpResponseMessage> RequestAsync(HttpRequestMessage request)
{
request.Headers.Add("cookie", GenerateCookie());
return _client.SendAsync(request);
}