0

To simplify my life I've disabled the authorization policy for all the controllers in a .Net Core 3.1 Web API project when the environment is equal to development by adding some configuration in the startup file.

The controllers are secured by adding [Authorize(AuthenticationSchemes = "Bearer")] on top of them.

Everything works fine, but there is also some piece of code inside all actions of the controllers that retrieve the username of the logged user to log the request.

Is there a way to check inside the method if the controller requires authorization (I'm in production) or not (I'm in development)?

This will be useful also for unit testing.

Giox
  • 4,785
  • 8
  • 38
  • 81
  • 1
    Check for the existence of the attribute on the class? – gunr2171 Apr 30 '21 at 18:30
  • @gunr2171 How? I've tried to explore the whole ControllerContext but I haven't found anything reliable to check – Giox Apr 30 '21 at 18:31
  • https://stackoverflow.com/questions/6538366/access-to-the-value-of-a-custom-attribute/46341017 – gunr2171 Apr 30 '21 at 18:33
  • `when the environment is equal to development`, you can this in controller as well if it is enough for you – Alexander Apr 30 '21 at 18:47
  • @Alexander sorry not clear, I haven't understood what you mean – Giox Apr 30 '21 at 18:51
  • What did you do in startup to check if authorization is needed? Checked `hostingEnvironment.IsDevelopment()`? If so, you can do the same thing in controller – Alexander Apr 30 '21 at 18:54
  • Do you know how to use reflection? And can you use it? – JHBonarius Apr 30 '21 at 19:14
  • But why? That seems like a bad idea because you can't ensure your policies are enforced until you release to another environment. Can't you just add perms for the devs in dev? – ChiefTwoPencils Apr 30 '21 at 19:50

1 Answers1

0

Is there a way to check inside the method if the controller requires authorization (I'm in production) or not (I'm in development)?

I would suggest injecting IWebHostEnvironment in your controller and then use its extension method in your action as

if (env.IsDevelopment())
 {
   // Do this 
 }

Or If you want to find if Authorize attribute is applied to the controller then you can access it as, in your action method

var AuthorizedAttribute = typeof(MyController).CustomAttributes
                .SingleOrDefault(x => x.AttributeType.FullName
                .Contains("Microsoft.AspNetCore.Authorization.AuthorizeAttribute"));

            if (AuthorizedAttribute == null)
            {
                //Do this or Don't do this
            }
Sayyed Dawood
  • 607
  • 7
  • 15