Practical ASP.NET

How to Authorize Users in Blazor Declaratively

When it comes to controlling which users can access which functionality in a Blazor application you not only have access to all of the user’s authentication you can authorize the user’s actions without writing any code.

Let me be clear: You can't authenticate users in Blazor -- that has to happen on the server (though you can certainly gather user information and credential information in a Blazor app and send it to some authentication source). What you can do in Blazor is use the information associated with the user through the authentication process to authorize what a user is (or isn't) allowed to do. Some of that authorization process even looks very much like what you may be used to if you have experience in creating ASP.NET MVC applications.

Sharing Authorization Information
In Blazor, if you want to pass information down through a set of components, you use a CascadingParameter. For sharing authorization information related to the current user, Blazor includes a special CascadingAuthenticationState component whose sole purpose is to pass authorization information about the current user down through the components it wraps.

You could wrap any component in this parameter but that leaves open the possibility that authorization information might not be available in some component in your application. The easiest way to ensure that you always have authorization information available everywhere is to wrap the routing component that handles delivering components to your users.

The routing component is usually kept in the App.cs folder in your project. Typically, that's also the component you invoke in your Blazor app's host page, usually with code like this:
@(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))

If you wrap that routing component in your App.cs file with the CascadingAuthenticationState component, the result will look something like this:

< CascadingAuthenticationState>
  <Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
      <RouteView RouteData="@routeData" 
             DefaultLayout="@typeof(MainLayout)"/>   
    </Found>
    …more markup…
</CascadingAuthenticationState>

Declarative Authorization for Components

Now that you've got the user's authorization information available throughout your application, you can use it without having to write any code. There are limitations with a declarative approach because it's essentially coarse-grained: It allows or forbids users access to whole components or to part of a component's UI. You can also use a procedural approach (i.e. "write some code") to give you a more fine-grained approach that lets you integrate authorization into your business logic. In this column, however, I'm going to stick with the declarative approach which may be all that you need.

If, for example, you want to prevent unauthorized users from accessing specific components, the easiest way to do that is declaratively: You just have to set up your routing component to refuse to send users to components they're not authorized for. You do that by, back in the App.cs file, replacing the RouteView component inside the Router's Found element with an AuthorizeRouteView component.

Unlike the RouteView component, the AuthorizeRouteView looks at who's allowed to use a component and won't let users access components they're not authorized for. Here's the markup inside an App.cs file that does that:

<Found Context="routeData">
  <AuthorizeRouteView RouteData="@routeData" 
            DefaultLayout="@typeof(MainLayout)">
    <NotAuthorized>
            <h1>You are not allowed to view this page</h1>
    </NotAuthorized> 
 </AuthorizeRouteView >
</Found>

As you can see, the AuthorizeRouteView component supports a NotAuthorized element that allows you to specify a message to be displayed when you turn people away.

Of course, this assumes that you've established who is and isn't authorized to use a component. To do that you add an Authorize attribute to a component, just as you would with an ASP.NET Controller. Because you're in a component, however, the syntax is slightly different: You use Blazor's @attribute directive to add the attribute. Other than that, though, the attribute works the same way in Blazor as it does in ASP.NET.

This code, for example, added to a component, would only allow users in the Admin and SalesManager roles to access the component:

@attribute [Authorize(Roles = "Admin, SalesManager")]

Authorizing Parts of a Component
You can be more selective: You don't have to completely lock users out of a component. Like the AuthorizeRouteView component, there's also an AuthorizeView component that you can use in a component's UI to selectively display parts of the component's UI, based on the user's roles. Like the Authorize attribute, the AuthorizeView element has a Roles attribute that you can use to specify who's allowed to receive a part of the component's UI (and, by exclusion, who's not allowed to).

Within the AuthorizeView, you can use up to three elements:

  • An Authorized element that contains the part of the UI authorized users can access
  • A NotAuthorized element that allows you to control what part of the UI is delivered to the user when they're not authorized
  • An Authorizing element that displays a message if the user's information isn't available yet

This example delivers a button to users in the Admin role while just giving everyone else a message (unless the authorization process isn't complete in which case the user gets a "please wait" message):

<AuthorizeView Roles="Admin">
  <Authorized>
    <button @onclick="UpdateCustomer">Update</button>
  </Authorized>
  <NotAuthorized>
    <p>You are not allowed to update customers.</p>
  </NotAuthorized>  
  <Authorizing>
    <p>Please wait while we authorize you…</p>
  </NotAuthorizing>  
</AuthorizeView>

I suspect that this declarative approach will handle much (or even all) of your authorization needs. However, when that's not enough, you'll need to use the procedural model that Blazor provides. I'll cover that in my next column along with claims and policy-based authorization.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube