...

/

Solution Review: Enforcing Role-Based Authorization

Solution Review: Enforcing Role-Based Authorization

Review the solution of the "Enforcing Role-based Authorization" challenge.

Overview

The complete solution is available in the following playground below:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DemoApp.Controllers;

[Authorize(Roles = "admin")]
[Route("api/[controller]")]
[ApiController]
public class ManagementController : ControllerBase
{
    [HttpGet()]
    public IActionResult GetManagementConsole()
    {
        return Ok("Management console opened.");
    }

    [AllowAnonymous]
    [HttpGet("health")]
    public IActionResult GetApplicationHealth()
    {
        return Ok("Application is running.");
    }

    [HttpPost()]
    public IActionResult UpdateSettings()
    {
        return Ok("Settings updated.");
    }

    [HttpGet("users/{userId}")]
    public IActionResult GetUserDetails(int userId)
    {
        return Ok($"Details retrieved for user {userId}.");
    }

    [Authorize("superadmin")]
    [HttpDelete("users/{userId}")]
    public IActionResult DeleteUser(int userId)
    {
        return Ok($"User {userId} deleted.");
    }
}
Complete solution

Solving the challenge

Here are the changes we should apply to each controller.

The ContentController controller class

This controller is represented by the ContentController.cs file inside the Controllers folder. On line 6, ...