Search code examples
c#asp.net-mvcasp.net-coreidentityserver4

How to write Integration Tests for IdentityServer4 in aspnetcore mvc


I have a webapi using Identity server 4. I dont know where to start writing Integration test. I have a Login Controller taking in username and password which is used for ResourceOwnerPassword Grant type. Below is my code.

[Route("Authentication/Login")]
public async Task<IActionResult> WebApiLogin(string username, string password)
{
    var accessToken = await UserAccessToken.GenerateToken(username, password);
    return new JsonResult(accessToken);
}

test code to generate a token

public async Task<string> GenerateToken(string username, string password)
{
    //discover endpoint for metadata
    var disco = await DiscoveryClient.GetAsync("http://localhost:5000");

    //request token
    var clientToken = new TokenClient(disco.TokenEndpoint, "client", "secret");
    //var tokenResponse = await clientToken.RequestClientCredentialsAsync("Payment");
    var tokenResponse = await clientToken.RequestResourceOwnerPasswordAsync(username, password, "IntegrapayAPI");

    if (tokenResponse.IsError)
    {
        //Error tokenResponse.Error
        return tokenResponse.Error;
    }
    return tokenResponse.Json.ToString();
}

IdentityServer Project startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddTemporarySigningCredential()
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients());
    //.AddTestUsers(Config.GetUsers());

    services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();

    // Add framework services.
    //services.AddMvc();
}

Solution

  • You can take a look at this answer: https://stackoverflow.com/a/39409789/147041 Disclaimer: my own question, my answer. It contains a link to a GitHub repo where integration tests are set up against an API, but it will work for MVC as well of course. The essence is to use an in-memory IdentityServer to act as your token generator and validator.

    Besides that, you should not mix your API with IdentityServer. Use IdentityServer to generate your tokens, then your API will validate those tokens agains the identityserver.

    There are a lot of good samples out there to get you started.