2
votes

I'm working on a small application that uses Blazor and Authentication / Authorization and for the most part the Roles based authorization is perfect. However, I have a couple of scenarios where I need to authorize multiple roles within the AuthorizeView component, and I'm not sure I'm doing it the best way. I'm trying to avoid hard coding the string values into the components, so I started by setting up a static class to manage the string values like so:

public static class Roles
{
    public const string Admin = "Admin"; 
    public const string CanManageClients = "CanManageClients"; 
    public const string CanManageProjects = "CanManageProjects"; 
}

Now I can use these values anywhere I need them, and for standard attribute based authorization I extended the AuthorizeAttribute class to allow me to pass multiple values in as needed. Now i have an [AuthorizeRoles] attribute to use. No problem so far. I can decorate an entire page with something like this:

@attribute [AuthorizeRoles(Roles.Admin, Roles.CanManageClients)]

and the related method decoration as needed:

[AuthorizeRoles(Roles.Admin, Roles.CanManageClients)]
public void DoTheThing()
{
    //Doing things
}

When it comes to the Blazor AuthorizeView component however, things get tricky. The Razor syntax isn't allowing me to chain multiple roles together or interpolate a string, so I found a workaround that gets the job done:

<AuthorizeView Roles="@rolesList">
    <Authorized>
        //View related code once authorized
    </Authorized>
</AuthorizeView>

And the related code block that produces the comma separated string that the component expects:

@code {
    string rolesList => $"{Roles.Admin}, {Roles.CanManageClients}";
}

This works like it's supposed to and gets me where I need to be, but it looks and feels hacky to me. I've avoided the dreaded magic string scenario, but I have an odd looking backing field in another part of the code that supports the component. I know I could solve this by moving to a policy based or claims based system, but that would honestly be way overkill for this little application as I only have a handful of use cases. Any feedback from the community would be greatly appreciated, maybe I'm not thinking of something and maybe this is just fine the way it is?

1

1 Answers

9
votes

This may help you

<AuthorizeView Roles="@($"{Roles.Admin}, {Roles.CanManageClients}")">