1
@attribute [Authorize(Roles = "Admin")]
@attribute [Authorize(Roles = NavigationManager.QueryString("level"))]

I have added this code on my page level, the first authorize attribute works fine, since it is just a constant value "Admin" but not the second authorize attribute.

I am trying to grant access based on the query string, but this code NavigationManager.QueryString("level") will have this error "An object reference is required for the nonstatic field, method, or property 'member'"

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0120?f1url=%3FappId%3Droslyn%26k%3Dk(CS0120)

Is there anyway to fix this?

Lucas Chan
  • 87
  • 6
  • You can do this with a policy. If I get time ill come back and write an answer. The policy name will be "Static" however you can write the logic. – Brian Parker Oct 25 '21 at 21:10

1 Answers1

1

Short answer: you cannot do this. An attribute argument needs to be a compile time constant.

Long answer: don't do this. Checking for authorization using query string is inherently unsecure.

If you have complicated authorization, check out Policy based authorization. This is a good explainer in general. Check out this for a more Blazor WASM specific example

Mayur Ekbote
  • 1,700
  • 1
  • 11
  • 14
  • oh, because this is just front end, it does not matter if its insecure, the backend is protected anyway – Lucas Chan Oct 25 '21 at 17:19
  • May be then you can just accept the query parameter and build logic around it? Say if("level"==something) then NavigationManager.NavigateTo("/Login")? – Mayur Ekbote Oct 25 '21 at 18:09
  • on code level, I could do something like if ( !user.IsInRole(NavigationManager.QueryString("level")) ) { someUnauthorizedProcess() } I have a for display, but I don't know how to make it display in code level. – Lucas Chan Oct 25 '21 at 18:32
  • Just create a razor component and use it 1) under and 2) another page (say "/NotAuthorized") – Mayur Ekbote Oct 25 '21 at 18:38
  • can I display NotAuthorized without changing URL? means it will still stay on same URL showing that component – Lucas Chan Oct 26 '21 at 02:01
  • You can use similar logic https://stackoverflow.com/a/69609157/9910440 – Mayur Ekbote Oct 26 '21 at 11:40