Search code examples
.net-coreasp.net-core-mvcasp.net-identityopenid-connect

Faking authentication during development


In my current asp.net MVC core application we use OpenId Connect to authenticate with our corporation's identity provider. However during local development we cannot reach the the provider. Also we would like to easily change claim values for development and unit testing purposes.

I tried swapping my service binding for IHttpContextAccessor to a DevelopmentHttpContextAccessor that fills up the HttpContext's Identity with the desired claims. This is a bit of a roundabout way and it also doesn't work as the claims are emptied when I check them in my Service.

What is the standard way of handling this during development and unit testing? What am I missing?


Solution

  • The answer was not faking IHttpContextAccessor, but setting a custom ClaimsPrincipal to the identity property. In your Startup.Configure you can add a middleware step:

    app.Use((httpContext, nextMiddleware) => {
        var claims = new[] {
            // Your claims here
        };
        var claimsIdentity = new ClaimsIdentity(claims);
        var user = new ClaimsPrincipal(claimsIdentity);
    
        httpContext.User = user;
    
        return nextMiddleware();
    });