Search code examples
.net.net-coreidentityserver4

Adding an API to IdentityServer4


I have an API and client that I created using the quickstart for Identity Server and it's working. In the config file I have the API called api1 that I have set as the allowed scope for a user I created called Admin. In turn this allows me to call the controller in the API project called IdentityController. This returns some data about the claims. Works great. I added a new controller called MsgController with authorize, and it to can be called without a problem. However I need some guidance on the following:

  1. I want to give a new user the allowed scope of api2 and then only allow that scope to call MsgController
  2. How do I prevent the allowed scope "api1" from being used in MsgController, and prevent "api2" (the new scope I want to create) from using the IdentityController.

Ideally I need to create a test with two logins and show that they cannot access the other controller based on their scope. I thought that the name of the scope would correlate with the name of the controller, but that doesn't seem to be the case. I think this is my lack of understanding on how to apply scopes to api's.

Thanks.


Solution

  • You simply need to restrict the controllers using policies.

    in your startup.cs ConfigureService() add the following extension

    services.AddAuthorization(options =>
    {
        //policy1
        options.AddPolicy("api1Policy", builder =>
        {
            builder.RequireClaim("scope", "api1");
        });
    
        //policy2
        options.AddPolicy("api2Policy", builder =>
        {
            builder.RequireClaim("scope", "api2");
        });
    });
    

    For more complex policy validations you can use, builder.RequireAssertion();

    In your controllers add the annotation like this.

    [Authorize(Policy = "api2Policy")]
    public class MsgController: Controller
    {
       //Users with api2 scope will be allowed in here. Likewise, do the same for others.
    }
    

    For more details about refer, Reference1 Reference2