Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Integration Test for Identity Server 4 in asp.net mvc core

I am having a web api using Identity server 4. I dont know where to start writing Integration test. I am having a Login Controller taking in Username and password which is used for ResourceOwnerPassword Grant type. Below is my code.

Controller.

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

Class to generate 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();
}
like image 307
maxspan Avatar asked Jan 25 '17 02:01

maxspan


People also ask

What is integration test in .NET Core?

Integration tests ensure that an app's components function correctly at a level that includes the app's supporting infrastructure, such as the database, file system, and network. ASP.NET Core supports integration tests using a unit test framework with a test web host and an in-memory test server.


1 Answers

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.

like image 175
Espen Medbø Avatar answered Oct 25 '22 20:10

Espen Medbø