Protecting endpoints
We are going to start this section by protecting the questions
endpoint for adding, updating, and deleting questions as well as posting answers so that only authenticated users can do these operations. We will then move on to implement and use a custom authorization policy so that only the author of the question can update or delete it.
Protecting endpoints with simple authorization
Let's protect the questions
endpoint for the POST
, PUT
, and DELETE
HTTP methods by carrying out these steps:
- Open
QuestionsController
and add the followingusing
statement:using Microsoft.AspNetCore.Authorization;
- To secure the actions, we decorate them with an
Authorize
attribute. Add this attribute to thePostQuestion
,PutQuestion
,DeleteQuestion
, andPostAnswer
methods:[Authorize] [HttpPost] public async ... PostQuestion(QuestionPostRequest questionPostRequest) ... [Authorize] [HttpPut("{questionId}")] public async ... PutQuestion(int questionId,...