.netauthenticationasp.net-web-apiattributesauthorization

Authentication on actions not controller


I have a controller which it is like the following code :

[Route("api/[controller]")]
[ApiController]
[Authorize("Admin, OtherRole")]
public class MyController : ControllerBase
{
    public MyController()
    {
    }

    [HttpGet("GetAll")]
    [?]
    public async Task<ActionResult<List<RandomType>>> GetAll()
    {
       // returns an action result
    }

    [HttpPost("Add")]
    public async Task<ActionResult<int>> Add([FromBody] SocietyViewModel req)
    {
       // returns an action result and added record's ID       
    }
}

I want access to GetAll method to be available for all users and all roles, but for the Add method, only the access set on the controller is possible.

In fact, for the GetAll method, we want authentication to be applied, but authorization not to be applied.

What attribute should we put instead of the question mark?


Solution

  • In this scenario I would use [AllowAnonymous][1] attribute on the GetAll method. Since you still want authentication to be applied for the GetAll method but without specific role auth, you should configure the auth policy in your authentication setup. This will ensure that only authenticated users can access the GetAll method without specifying roles.

    Here's how you can change your controller:

    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Roles = "Admin, OtherRole")]
    public class MyController : ControllerBase
    {
        public MyController()
        {
        }
    
        [HttpGet("GetAll")]
        [AllowAnonymous]
        public async Task<ActionResult<List<RandomType>>> GetAll()
        {
            // Check if the user is authenticated
            if (!User.Identity.IsAuthenticated)
            {
                return Unauthorized();
            }
    
            // returns an action result
        }
    
        [HttpPost("Add")]
        public async Task<ActionResult<int>> Add([FromBody] SocietyViewModel req)
        {
            // returns an action result and added record's ID       
        }
    }