Search code examples
c#jsonoauth-2.0openid-connectidentityserver4

Json to Authenticate User From IdentityServer4


I have set IdentityServer4 which implements oAuth and OpenId Connect, Simple Implementation looks like this

services.AddIdentityServer()
    .AddTemporarySigningCredential()
    .AddInMemoryIdentityResources(Config.GetIdentityResources())
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryClients(Config.GetClients())
    .AddTestUsers(Config.GetTestUsers());

We have our Clients setup like so:

new Client
{
    ClientId = "oauthClient",
    ClientName = "Example Client Credentials Client Application",
    AllowedGrantTypes = GrantTypes.ClientCredentials,
    ClientSecrets = new List<Secret> {
        new Secret("superSecretPassword".Sha256())},
           AllowedScopes = new List<string> {"customAPI.read"}
    }

I'm trying to figure out how to create the login request for a user I'm passing this json in a post body to gain access to an authentication token

{
   grant_type:client_credentials,
   scope=customAPI.read,
   client_id=oauthClient
   client_secret=superSecretPassword
}

I'm looking for a way to do this but pass user information assuming I had a

username: admin password: root

What parameters do I have to modify in my json to login as a user? How do I pass the username, password and what is my Grant_Type?


Solution

  • My Issue was the setup of my client, My client was only accepting grant types of client credentials, I needed to also Include ResourceOwnerPassword.

    I need to change my Grant Types in the clients to look like so

    new Client
    {
        ClientId = "oauthClient",
        ClientName = "Example Client Credentials Client Application",
        AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
        ClientSecrets = new List<Secret> {
            new Secret("superSecretPassword".Sha256())},
        AllowedScopes = new List<string> {"customAPI.read"}
    }
    

    Now we can form out Post Body Json like so

    url: localhost/connect/token
    Content-Type: application/x-www-form-urlencoded,
    data: {
        grant_type: 'password',
        scope: 'customAPI.read',
        client_id: 'oauthClient',
        client_secret:'superSecretPassword',
        username:'admin',
        password: 'root'
    }
    

    Edit

    Using the ResourceOwnerPassword is not reccomended anymore apparently according to the IdentityServer4 Documentation

    The spec recommends using the resource owner password grant only for “trusted” (or legacy) applications. Generally speaking you are typically far better off using one of the interactive OpenID Connect flows when you want to authenticate a user and request access tokens.