Auth Policy Checking Scope

I needed a way to create Policies that checked for a scope which is provided to my API via JWT. The encoded JWT could look like the below, this I created at https://jwt.io/

1
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJzY29wZSI6WyJmb28iLCJiYXIiXX0.4xcnT8dVtguK2TsiyDvHtMkZAdzoEbGyiYUyON9F2qQ

Initially I thought I had to create AuthorizationRequirement and Handlers but after looking at Claims-based authorization and Extensions.RequireScope Method I realized I could just add a policy that is built from a delegate with the provided name.

The decoded JWT’s payload data looks like the below, so a scope Im looking for is foo

1
2
3
4
5
6
7
8
9
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"scope": [
"foo",
"bar"
]
}
  1. Register the policy in the applications services registration, here the builder is of type WebApplicationBuilder, “CheckForFooPolicy” is the policy name and I pass an Action deligate to .AddPolicy calling the .RequireScope extension instructing it to check for “foo”
1
2
3
4
builder
.Services
.AddAuthorizationBuilder()
.AddPolicy("CheckForFooPolicy", p => p.RequireScope("foo"));
  1. Add the AuthorizeAttribute Class specifiying the policy
1
2
3
4
5
6
7
[ApiController]
public class SweetController : ControllerBase
{
[Authorize(Policy = "CheckForFooPolicy")]
[HttpGet(Name = "SweetGet")]
public async Task<ActionResult<Guid>> GetTheThing(CancellationToken cancellationToken)
{

If you are one of the leet nerds using endpoints because, you know controllers are dinosaurs, you can specify the Authorize as a parameter. See Tutorial: Implement a protected endpoint to your API for more details.

1
2
app.MapGet("/sweetget", [Authorize(Policy = "CheckForFooPolicy")] () =>
{

References