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();
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With