0

Why Authorize Attribute policy parameter are restricted to const "compile time" ?

because this restriction disallow to use string concatenation like the below example , There is any reason to restrict it.

 [Authorize($"{Privilege1},{Privilege2}")]
 [HttpPost()]
 public async Task<IActionResult> Testpost()
 {
        return Ok();
 }
Osama AbuSitta
  • 3,521
  • 4
  • 31
  • 47

2 Answers2

1

Yes, sadly you can't use string interpolation in constants and you have to use constants in attributes like Authorize. Interpolated strings are interpolated at runtime and constants need to be created at compile time.

You can however concatenate the strings in this way, which the compiler will be able to make into constant:

 private const string privilege1 = "Privilege1";
 private const string privilege2 = "Privilege2";

 [Authorize(privilege1 + "," + privilege2)]
 [HttpPost()]
 public async Task<IActionResult> Testpost()
 {
        return Ok();
 }
mortb
  • 7,874
  • 3
  • 21
  • 38
0

The attribute parameter has to be known in the compile time to put it into the assembly metadata. That's how attributes work. In your case, the ${} means the value is only known at the run time.

It's not about concatenation, you can safely have "a" + ",b" there which clearly is a concatenation but still uses string values known at compile time.

Try to create your own security policy or inherit the AuthorizeAttribute. In your custom logic, you can refer to any roles, static or dynamic.

Wiktor Zychla
  • 44,107
  • 6
  • 65
  • 91
  • for your quick response, I understand it is more about runtime value, but why we need authorization attribute to be compile time – Osama AbuSitta Jun 09 '20 at 09:01
  • @OsamaAbuSitta: it is the same for all attributes. If the attribute has a parameter (like privilege in your example) it needs to be a constant. Attributes are part of the C#-language and work that way. The constant value will be compiled into your output assembly (.dll-file). String interpolation may for example call methods, making the value a non compile time constant. If you don't want to use the attribute it is possible to write authorization logic inside the `TestPost()` method instead. – mortb Jun 09 '20 at 09:05