...

/

Protecting Endpoints with a Custom Authorization Policy

Protecting Endpoints with a Custom Authorization Policy

Learn to create a custom authorization policy to protect endpoints.

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:

  1. In the Program class, let's add the following using statements:

Press + to interact
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.

  1. We'll need to eventually call an Auth0 web service, so let's make the HTTP client available in the builder.Services method:

Press + to interact
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.

  1. Let's also add an authorization policy called MustBeQuestionAuthor:

Press + to interact
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 ...