Search code examples
asp.net-coreasp.net-identityidentityserver4

IdentityServer4 as Web API


I'm newbie in IdentityServer4. Now I try to realize microservices with JWT-authorization (by passing tokens each request to the API). So, the schema is primitive - IDS4 server as an auth server, ASP.NET Identity + MSSQL for client data usage and storage, other services use auth service for token validation. So, I've looked many articles, but found none of example, where I can customize IDS4 behavior. For example, I want client to call AuthorizeByLogin(AuthorizeView model) API method, realized in the IDS4 project, where model is an object of 2 fields: Username, Password. In this method I want to check user in the Database and generate access_token, which is passed to the client for working with protected API. But there is nowhere an example how to do this (call API method, pass the object and receive token). Most of it says "use */connect/token for this".

Could anyone give me an example of code in which this way is realized well? Or maybe tell me which interfaces I should implement and correctly pass to the services in ASP.NET Core app for Authentication Web API + IdentityServer4 realization?

Thank you.


Solution

  • You can find a plethora of quickstart examples in the Identity Server 4 docs. Also from what I understand, you are wanting to use ResourceOwnerCredentials grant type. You won't be able to easily modify the endpoints that issue the tokens without reimplementing majority of Identity Server 4 but you can implement IResourceOwnerPasswordValidator interface and setup a client with an appropriate allowed grant type:

        new Client
        {
            ClientId = "your_client",
            AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
    
            ClientSecrets =
            {
                new Secret("your_password".Sha256())
            },
            AllowedScopes = { ... }
        }
    

    After that, the clients can call connect\token endpoint by providing user name and password of a given user alongside their own credentials:

    var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
    {
        Address = disco.TokenEndpoint,
        ClientId = "ro.client",
        ClientSecret = "secret",
    
        UserName = "alice",
        Password = "password",
        Scope = "api1"
    });