Search code examples
c#asp.net-coreidentityserver4jwt

IdentityServer4 .net core, is it possible to protect controllers on the same IdentityServer with a token generated from the same server?


Normally when we use IdentityServer4 we would use this setup: enter image description here

Where we would have an

  • Authorization Server (Identity Server)
  • A Client (which will request a token)
  • A Web Api (Protected with authorize)

Say we have this setup, but I need to add Protected Api's on the Authorization Server (identity server), by protected I mean with the authorize attribute. Is this possible? cause I haven't found any samples online, and I have been trying to implement it by adding the JwtBearer code on the IdentityServer (JwtBearer is normally added on the WebApi project that you want protected, with Authority set as your IdentityServer domain).

In short what i'm trying to achieve is have the Protected Resource on the same Authorization Server. Is this possible?

enter image description here

Thanks in advance


Solution

  • It is possible with some additional configuration. There is an argument against doing this, but I've had use cases where it was necessary.

    For local API authentication you need the following additional configuration in Startup:

    public void ConfigureServices(IServiceCollection services)
    {
      ....
      // After services.AddIdentityServer()
      services.AddLocalApiAuthentication();
    }
    

    For reference see the docs.

    You also need to configure the local resource:

      public static IEnumerable<ApiResource> Apis =>
        new ApiResource[]
        {
          // your other resources....
          new ApiResource(IdentityServerConstants.LocalApi.ScopeName)
        };
    

    For the client you need to add the local API scope:

      AllowedScopes =
      {
        // your other scopes....
        IdentityServerConstants.LocalApi.ScopeName
      }
    

    And then you need to specify the local API policy as part of the Authorize attribute on your API:

    [Authorize(LocalApi.PolicyName)]
    

    See a local API example.