Search code examples
asp.net-core-mvcidentityserver4thinktecture-ident-server

Access token for API controller inside Identity server itself


I have created an identity server 4 project and a mvc client project. Authentication flow works as expected. I have added an API controller in the same project as identity server and i want to hit this api resource from mvc client.Essentially,i need both identity server middleware and token validation middle inside the idenity server project.


Solution

  • If you haven't already, add these Nuget packages to your already established IdentityServer app/site:

    IdentityServer4.AccessTokenValidation
    Microsoft.AspNetCore.Mvc
    

    Add another Api Resource to your resources list:

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API"), 
            new ApiResource("api2", "IdentityServer API")
        };
    }
    

    Update your client configuration to allow api2:

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "mvc",
    
                ... omitted
    
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api2"
                }
            }
        };
    }
    

    In the IdentityServer's Configure method in Startup add:

    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "http://localhost:5000",
        RequireHttpsMetadata = false,
    
        ApiName = "api2"
    });