Issue access token to IdentityServer 4 from IdentityServer 4

You need sometimes IdentityServer 4 to interact with other services and to need information from them. And in many cases the same instance of the IdentityServer is the one that authorizes the access to those other services. Wee need to issue an access token to our-self in order to get/post the necessary information.

In my case I needed to create a corresponding object in another service on new user registration. To get the access token needed I have used IdentityServerTooks class provided by IdentityServer 4. It is already registered in the dependency injection (DI) container in ASP.NET, so you can just use it.

public class RegisterModel : PageModel
{
	public RegisterModel(
		...
		IdentityServerTools identityServerTools,
		...)
	{
		...
		_identityServerTools = identityServerTools;
		...
	}
	
	private async Task<string> GetBearerToken(string identityId)
	{
		// self issue a token
		var token = await _identityServerTools
			.IssueClientJwtAsync(
				"ClientId",
				100,
				new[] { "scope1", "scope2" },
				new[] { "Audience" },
				new []
				{
					new Claim("sub", identityId)
				} );

		return token;
	}
	
	
    private readonly IdentityServerTools _identityServerTools;
}

Since the token issuing is internal you are already in the right security context, so no need of credentials.