...
/Protecting Endpoints with a Custom Authorization Policy
Protecting Endpoints with a Custom Authorization Policy
Learn to create a custom authorization policy to protect endpoints.
We'll cover the following...
At the moment, any authenticated user can update or delete questions. We are going to implement and use a custom authorization policy and use it to enforce that only the author of the question can do these operations.
Steps to implement custom authorization policy
Let's carry out the following steps:
In the
Program
class, let's add the following using statements:
using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Authorization;using QandA.Authorization;
Note that the reference to the QandA.Authorization
namespace doesn't exist yet. We'll implement this in a later step.
We'll need to eventually call an Auth0 web service, so let's make the HTTP client available in the
builder.Services
method:
builder.Services.AddAuthentication(options =>{...});...builder.Services.AddHttpClient();
The authorization policy has its requirements defined in a class called MustBeQuestionAuthorRequirement
, which we'll implement in a later step.
Let's also add an authorization policy called
MustBeQuestionAuthor
:
builder.Services.AddHttpClient();builder.Services.AddAuthorization(options =>options.AddPolicy("MustBeQuestionAuthor", policy=>policy.Requirements.Add(new MustBeQuestionAuthorRequirement())));
The authorization policy has its requirements defined in a class called ...