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 | { |
- 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 | builder |
- Add the AuthorizeAttribute Class specifiying the policy
1 | [ ] |
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 | app.MapGet("/sweetget", [Authorize(Policy = "CheckForFooPolicy")] () => |