【发布时间】:2014-10-15 13:28:26
【问题描述】:
我了解到 OWIN 有这个很棒的 Microsoft.Owin.Testing 库,可以让您在内存中测试您的 Web 应用程序。但是,我的站点需要在访问资源之前进行身份验证,这使得编写测试代码很复杂。
在使用 Microsoft.Owin.Testing 时,有没有一种方便的方式来“模拟”身份验证?
我希望我的单元测试不需要遇到进程外 STS,并且我不希望编写以编程方式登录内存中 STS 的代码(例如 Thinktecture.IdentityServer.v3) .
我想出的最简单的解决方案是禁用单元测试的身份验证代码,我不喜欢。
我正在使用带有 Cookie 身份验证的 OpenID Connect。这是一个包含的示例。需要为实际服务器填写 OpenId Connect 的配置字符串。
[Test]
public async void AccessAuthenthicatedResourceTest()
{
const string ClientId = "";
const string RedirectUri = "";
const string Authority = "";
TestServer server = TestServer.Create(
app =>
{
//Configure Open ID Connect With Cookie Authenthication
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = ClientId,
RedirectUri = RedirectUri,
Authority = Authority
});
// Requires Authentication
app.Use(
async ( context, next ) =>
{
var user = context.Authentication.User;
if ( user == null
|| user.Identity == null
|| !user.Identity.IsAuthenticated )
{
context.Authentication.Challenge();
return;
}
await next();
} );
app.Run( async context => await context.Response.WriteAsync( "My Message" ) );
} );
//Do or Bypass authenthication
HttpResponseMessage message = await server.CreateRequest( "/" ).GetAsync();
Assert.AreEqual("My Message", await message.Content.ReadAsStringAsync());
}
【问题讨论】:
标签: c# .net unit-testing owin katana