Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get access token from Identity Server by passing username and password?

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.

like image 376
Osanda Deshan Avatar asked Jul 29 '17 14:07

Osanda Deshan


People also ask

How do I get my access token?

To request an access token, send a POST request containing your authorization code to the DocuSign authentication service. Note: The obtained authorization code is only viable for two minutes.

How can I get authorization token from request?

The authorization code grant is used when an application exchanges an authorization code for an access token. After the user returns to the application via the redirect URL, the application will get the authorization code from the URL and use it to request an access token.


1 Answers

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:

Postman bearer token

like image 79
Matt Avatar answered Sep 29 '22 11:09

Matt