Reputation: 1557
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:
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.
Upvotes: 0
Views: 78
Reputation: 874
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
Upvotes: 1