Shielding the server

Now that our client is more or less ready, it's time to shield our .NET API controllers from unauthorized requests as well. We can easily do that using the [Authorize] attribute, which can be used to restrict access to any controller and/or controller method we don't want to open to unauthorized access.

To implement the required authorization behavior, it can be wise to use it on the Put, Post and Delete methods of all our BaseApiController extended classes, as follows:

[...]

[HttpPut]
[Authorize]
public IActionResult Put([FromBody]QuizViewModel model)

[...]

[HttpPost]
[Authorize]
public IActionResult Post([FromBody]QuizViewModel model)

[...]

[HttpDelete("{id}")]
[Authorize]
public IActionResult Delete(int id)

[...]

The preceding code is taken from the QuizController, but we need to perform the exact same upgrade on QuestionController, AnswerController, and ResultController as well. Don't forget to add the following required namespace reference at the beginning of each of these files:

using Microsoft.AspNetCore.Authorization; 

Now all these action methods are protected against unauthorized access, as they will accept only requests coming from logged-in users/clients with a valid JWT token; those who don't have it will receive a 401 - Unauthorized HTTP error response.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.17.139