Get user token and user info from IdentityServer4

IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core.

Use the PasswordTokenRequest and RequestPasswordTokenAsync to get the access token. replace clientId and secret with the values from your Identity Server, then use the UserInfoRequest and pass your access token to GetUserInfoAsync to get the user claims:

public class TokenService
{
    private DiscoveryDocumentResponse _discDocument { get; set; }
    public TokenService()
    {
        using (var client = new HttpClient())
        {
            _discDocument = client.GetDiscoveryDocumentAsync("http://localhost:5000/.well-known/openid-configuration").Result;
        }
    }
    public async Task<TokenResponse> GetToken(string userName, string password)
    {
        using (var client = new HttpClient())
        {
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = _discDocument.TokenEndpoint,
                ClientId = "clientId",
                ClientSecret = "secret",
                Scope = "openid",
                GrantType = "password",
                UserName = userName,
                Password = password
            });

            if (tokenResponse.IsError)
            {
                throw new Exception("Token Error");
            }
            return tokenResponse;
        }
    }

    public async Task<string> GetUserInfo(string accessToken)
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetUserInfoAsync(new UserInfoRequest()
            {
                Address = _discDocument.UserInfoEndpoint,
                Token = accessToken
            });

            if (response.IsError)
            {
                throw new Exception("Invalid username or password");
            }
            return response.Raw;
        }
    }
}