We are using identity server to generate access token for our web services. We have added swagger also. But the problem we faced is, to generate an access token by using a code snippet for API automation. Is there any automated way to get access token by using the username and password?
Thank You.
The way I've tackled this is to add a client credentials client if there is a configured test client secret, I configure this secret only in the test environments but obviously not in higher environments meaning the client never gets added there.
So either in your appsettings.{appropriate_environment}.settings or via an environment variable set up a client secret, then in your IdentityServer config you can add:
//attempt to get the test client secret
var testClientSecret = configuration["TestClientSecret"];
if (!String.IsNullOrWhiteSpace(testClientSecret))
{
clients.Add(new Client
{
ClientId = "MyTestClient",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret(testClientSecret.Sha256())
},
AllowedScopes = { "MyApiScope", "MyOtherApiScope", "etc." }
});
};
Then I have a Postman collection of tests which first POSTs to:
https://{{idp_base_url}}/connect/token
Using basic auth with username of the test client name and password as the client secret (where {{idp_base_url}} is a postman environment variable containing the IdentityServer host appropriate for the environment).
Then I run a few tests but also store the access token to the API:
//tests...
var tokenData = JSON.parse(responseBody);
//more tests...
postman.setEnvironmentVariable("cc_token", tokenData.access_token);
Subsequent tests in the collection can then run your API tests using this token with a bearer token auth header using the above Postman environment variable: