1

I have controllers with role based Authorize attribute, below is an example. I want to test authorization role setting for each controller, for example only "company admin", "group admin" can access UserController. what is the best way to do it?

    [Authorize(Roles = ("company admin", "group admin")]
    [Route("api/v1/")]
    [ApiController]
    public class UserController : ControllerWithLog
    {

thanks!

  • Hi, first this is will be not a unit testing this will be integration functional testing! to test authorization you need to bring up in your test all infrastructure! and make a http request with specific token – Sergey K Feb 09 '21 at 22:47
  • Check up this https://stackoverflow.com/questions/48562403/unit-testing-an-authorizeattribute-on-an-asp-net-core-mvc-api-controller and this https://medium.com/asos-techblog/testing-authorization-scenarios-in-asp-net-core-web-api-484bc95d5f6f – Sergey K Feb 09 '21 at 22:50
  • I have this integration tests in place, with claim set up for each request. However, I tried to find a way to test Authorize roles setting for its own, rather than testing accessibility for each endpoint with different roles. It is just like you would put [Authorize(Roles = ("company admin", "group admin")] on controller level, rather than on each route level. – user12855329 Feb 09 '21 at 23:58
  • If you just want to make sure that on your controller or API method there is Authorize attribute with specific parameters I would use the reflection and will scan all the controllers and obtain the custom attributes and check if it correct role is assigned and that's it! – Sergey K Feb 10 '21 at 00:40
  • thanks, that is one of the options I thought about, but am wondering if there is other way to test it – user12855329 Feb 10 '21 at 00:44

0 Answers0