Search code examples
c#asp.net-corecontrollerasp.net-core-webapiauthorize

Get [Authorize] data from controller


I have code:

[Authorize(Roles = "SuperAdministrators")]
public class ButtonStyleController : ControllerBase
{

in other place:

[Authorize(Roles = "SuperAdministrators,CompanyAdministrators")]
public class BankController : ControllerBase
{

and even:

[Authorize(Roles = "CompanyAdministrators")]
public class DriverController : ApiControllerBase
{

I need to check which roles are allowed for current controller in code. Is it possible?


Solution

  • You can use the following code to get an attribute, of type AuthorizeAttribute, from a class then access the Roles property.

    AuthorizeAttribute currentAuthorizeAttribute = (AuthorizeAttribute)Attribute.GetCustomAttribute(typeof(DriverController), typeof(AuthorizeAttribute));
    string roles = currentAuthorizeAttribute.Roles;