I have learned that OWIN has this great Microsoft.Owin.Testing
library that lets you test your web application in-memory. However, my site requires authentication before accessing resources which has complicated writing test code.
Is there a convenient way to "mock" authentication when using Microsoft.Owin.Testing?
I would like my unit tests to not need to hit an out-of-process STS and I would prefer not to need to write code that programmatically signs in against an in-memory STS (such as Thinktecture.IdentityServer.v3).
The easiest solution I come up with is to disable the authentication code for the unit tests, of which I am not a fan.
I am using OpenID Connect with Cookie Authentication. Here is a contained example. The configuration strings for the OpenId Connect would need to be filled in for an actual server.
[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());
}