Course contentsShow
← C#
Lesson 1221 of 1,90811. Identity, Security, and ClaimsFree lesson

Securing Web APIs with Scopes

Use OAuth scopes to limit API access on behalf of users or service principals.

In this lesson, you will learn how to implement OAuth scopes to enforce the principle of least privilege in your Web APIs.

Understanding Scopes vs. Roles

While you are already familiar with Role-Based Access Control (RBAC), Scopes function differently. Where a role defines who a user is (e.g., "Admin"), a scope defines what specific action a client application is authorized to perform on the user's behalf (e.g., read:reports or write:orders). This is essential for microservices and third-party integrations, as it prevents a compromised application from performing actions the user never intended to grant.

Enforcing Scopes in ASP.NET Core

In ASP.NET Core, scopes are passed via the scp claim inside the JWT access token. To restrict an API endpoint to a specific scope, you can use the [Authorize] attribute combined with a policy that checks for the presence of that scope claim.

First, define a policy in Program.cs:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ReadReportsPolicy", policy => 
        policy.RequireClaim("scope", "reports.read"));
});

Then, apply this policy to your controller or specific action:

[ApiController]
[Route("api/[controller]")]
public class ReportsController : ControllerBase
{
    [HttpGet]
    [Authorize(Policy = "ReadReportsPolicy")]
    public IActionResult GetReport()
    {
        return Ok("Sensitive report data.");
    }
}

Why This Matters

If you simply used [Authorize(Roles = "User")], the calling client would have broad access to everything a "User" is allowed to do. By requiring the reports.read scope, you ensure that even if the user has permission to read reports, the API will reject the request if the specific access token presented by the client does not explicitly include the reports.read scope. This creates a granular security boundary, protecting your API from over-privileged clients.

Key Takeaway: Scopes act as a "permission-to-act" mechanism that limits what a client application can do on behalf of a user, providing a secondary, more granular layer of defense beyond standard role-based access control.