Role-Based Authorization in Blazor File Manager: An Overview
Tags: blazor, filemanager, webdev, productivity
Published: 2023-06-20 03:33:25

---
title: Role-Based Authorization in Blazor File Manager: An Overview
published: true
date: 2023-06-19 10:55:09 UTC
tags: blazor, filemanager, webdev, productivity
canonical_url: https://www.syncfusion.com/blogs/post/role-based-authorization-blazor-file-manager.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdwcbc1seo2b4f22lq89.png
---
Our previous blog showed us how to [easily create a Blazor server application with authentication](https://www.syncfusion.com/blogs/post/easy-steps-create-a-blazor-server-app-with-authentication.aspx "Blog: Easy Steps to Create a Blazor Server App with Authentication"). This blog will show how to configure the Blazor File Manager component with role-based authorization.

- **Authentication** is done before authorization. It is the process of validating that users are whom they claim to be. It determines whether the person is a registered user or not.
- **Authorization** is done after authentication. It is the process of permitting a user to access a resource.

The Syncfusion [Blazor File Manager](https://www.syncfusion.com/blazor-components/blazor-file-manager "Blazor File Manager") is a graphical user interface component for managing the file system. It allows users to perform common file operations like accessing, editing, and sorting files and folders. This component also provides easy navigation of folders for selection of a file or folder from the file system.

Let’s get started!

## Create a Blazor server app with authentication and authorization

First, refer to the [Getting Started with authentication and authorization in a Blazor server app documentation](https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-7.0 "Authentication and authorization in a Blazor server app documentation").

## Getting started with the Syncfusion Blazor File Manager component

After creating a Blazor server app, refer to the [Getting Started with the Blazor File Manager component documentation](https://blazor.syncfusion.com/documentation/file-manager/getting-started "Getting Started with Blazor File Manager Component").

## Configure the Blazor File Manager’s supported operations

We can control the Blazor File Manager’s supported operations through user roles. We will define the following roles and their corresponding file operations.
<table style="width: 100%;">
<tbody>
<tr>
<td style="width: 32.2034%;" width="208">
<p><strong>Role</strong></p>
</td>
<td style="width: 33.63%;" width="208">
<p><strong>Subject</strong></p>
</td>
<td style="width: 32.9167%;" width="208">
<p><strong>File operations</strong></p>
</td>
</tr>
<tr>
<td style="width: 32.2034%;" width="208">
<p>Admin</p>
</td>
<td style="width: 33.63%;" width="208">
<p>Admin can perform all the supported operations of the File Manager.</p>
</td>
<td style="width: 32.9167%;" width="208">
<ul>
<li>NewFolder</li>
<li>Upload</li>
<li>Cut</li>
<li>Copy</li>
<li>Paste</li>
<li>Delete</li>
<li>Download</li>
<li>Rename</li>
<li>SortBy</li>
<li>Refresh</li>
<li>Selection</li>
<li>View</li>
<li>Details</li>
</ul>
</td>
</tr>
<tr>
<td style="width: 32.2034%;" width="208">
<p>Employee</p>
</td>
<td style="width: 33.63%;" width="208">
<p>Employees can perform file and folder management operations.</p>
</td>
<td style="width: 32.9167%;" width="208">
<ul>
<li>Cut</li>
<li>Copy</li>
<li>Paste</li>
<li>Delete</li>
<li>Download</li>
<li>Rename</li>
<li>SortBy</li>
<li>Refresh</li>
<li>Selection</li>
<li>View</li>
<li>Details</li>
</ul>
</td>
</tr>
<tr>
<td style="width: 32.2034%;" width="208">
<p>Guest</p>
</td>
<td style="width: 33.63%;" width="208">
<p>Guest users can view and download the files and folders.</p>
</td>
<td style="width: 32.9167%;" width="208">
<ul>
<li>Download</li>
<li>SortBy</li>
<li>Refresh</li>
<li>Selection</li>
<li>View</li>
<li>Details</li>
</ul>
</td>
</tr>
</tbody>
</table>
Refer to the following images. They depict the details of the users that we’ll use in this blog to enable role-based authorization.

**Usernames**

![Usernames](https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Usernames-1.png)

**User roles**

![User roles](https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/User-roles.png)

**User Role ID**

![User Role ID](https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/User-Role-ID.png)

## Configure the Blazor File Manager toolbar

Let’s configure the file operations in the File Manager component’s toolbar based on the roles of the users in the **Index.**** r ****azor** file:

1.First, access the currently logged-in user’s identity using the **AuthenticationState ** class.
2.Then, validate the authenticated user using the **Identity.IsAuthenticated** property.
3.Define the toolbar items in the Blazor File Manager with file operations based on the user role by checking the condition using the **IsInRole ** method.

Refer to the following code example.

```csharp
@code {
 [CascadingParameter]
 private Task<AuthenticationState> authenticationStateTask { get; set; }
 string[] toolbarItems = { };
 protected async override Task OnInitializedAsync()
 {
     var authState = await authenticationStateTask;
     var user = authState.User;

     if (user.Identity.IsAuthenticated)
     {
         if (user.IsInRole(“Admin”))
         {
            toolbarItems = new string[] { “NewFolder”, “Upload”, “Cut”, “Copy”, “Paste”, “Delete”, “Download”, “Rename”, “SortBy”, “Refresh”, “Selection”, “View”, “Details” };
         }
         else if (user.IsInRole(“Employee”))
         {
             toolbarItems = new string[] { “Cut”, “Copy”, “Paste”, “Download”, “Rename”, “SortBy”, “Refresh”, “Selection”, “View”, “Details” };
        }
        else
        {
            toolbarItems = new string[] { “Download”, “SortBy”, “Refresh”, “Selection”, “View”, “Details” };
        }
     }

  }
}

```

## Configure the File Manager to handle users

To handle the **authorized** and **not authorized** users, define the **<Authorized>** and **<NotAuthorized>** components within the **<AuthorizeView>** component in the **Index.razor** file:

1.Access the authenticated user’s identity using the **@context** object within the **<Authorized>** component.
2.Then, validate the user role using the **IsInRole** method.
3.Define the **Url** , **DownloadUrl** , **GetImageUrl** , and **UploadUrl** properties using the **FileManagerAjaxSettings** based on the roles.
4.Pass the corresponding role as a query parameter to the File Manager service to handle the file operations based on the user roles.

Refer to the following code example.

```xml
<AuthorizeView>
  <Authorized>
    <h1>Hello, @context.User.Identity.Name!</h1>
        
    @if (context.User.IsInRole(“Admin”))
    {
      <SfFileManager Tvalue=”FileManagerDirectoryContent”>
          <FileManagerAjaxSettings Url=”/api/FileManager/FileOperations?Role=Admin”
                                     DownloadUrl=”/api/FileManager/Download”
                                     GetImageUrl=”/api/FileManager/GetImage”
                                     UploadUrl=”/api/FileManager/Upload”>
          </FileManagerAjaxSettings>
          <FileManagerToolbarSettings Items=”@toolbarItems”></FileManagerToolbarSettings>
      </SfFileManager>
   }
   else if (context.User.IsInRole(“Employee”))
   {
      <SfFileManager Tvalue=”FileManagerDirectoryContent”>
          <FileManagerAjaxSettings Url=”/api/FileManager/FileOperations?Role=Employee”
                                     DownloadUrl=”/api/FileManager/Download”
                                     GetImageUrl=”/api/FileManager/GetImage”
                                     UploadUrl=”/api/FileManager/Upload”>
          </FileManagerAjaxSettings>
          <FileManagerToolbarSettings Items=”@toolbarItems”></FileManagerToolbarSettings>
     </SfFileManager>
   }
   else
   {
      <SfFileManager Tvalue=”FileManagerDirectoryContent”>
          <FileManagerAjaxSettings Url=”/api/FileManager/FileOperations?User=AuthorizedUser”
                                     DownloadUrl=”/api/FileManager/Download”
                                     GetImageUrl=”/api/FileManager/GetImage”>
         </FileManagerAjaxSettings>
         <FileManagerToolbarSettings Items=”@toolbarItems”></FileManagerToolbarSettings>
     </SfFileManager>
   }
   </Authorized>
   <NotAuthorized>
     <h1>Authentication Failure!</h1>
     <p>You’re not signed in.</p>
   </NotAuthorized>
</AuthorizeView>
```

### Configure the Blazor File Manager service

Finally, configure the File Manager service:

1.Receive the file operation details and corresponding roles as parameters through the **FileManagerDirectoryContent** and **Role** parameter.
2.Then, define the file operations based on the user roles.

The main action code follows, but you can also find all its dependent classes and methods by checking out this [GitHub](https://github.com/SyncfusionExamples/blazor-filemanager-authorization "Blazor FileManager Authorization GitHub demo") repository.

```csharp
[Route(“api/[controller]”)]
public class FileManagerController : Controller
{
    public PhysicalFileProvider operation;
    public string basePath;
    string root = “wwwroot\\Files”;

    public FileManagerController(Microsoft.AspNetCore.Hosting.IwebHostEnvironment hostingEnvironment)
    {
       this.basePath = hostingEnvironment.ContentRootPath;
       this.operation = new PhysicalFileProvider();
       this.operation.RootFolder(this.basePath + this.root); // It denotes in which files and folders are available.
   }

   // Processing the File Manager operations.
   [Route(“FileOperations”)]
   public object? FileOperations([FromBody] FileManagerDirectoryContent args, string Role)
   {
      if (Role == “Admin”)
      {
         if (args.Action == “create”)
             // Path – Current path where the folder is to be created; Name – Name of the new folder.
             return this.operation.ToCamelCase(this.operation.Create(args.Path, args.Name));
         else if (args.Action == “delete”)
              // Path – Current path where the folder is to be deleted; Names – Name of the files to be deleted.
             return this.operation.ToCamelCase(this.operation.Delete(args.Path, args.Names));
      }

      if (Role == “Admin” || Role == “Employee”)
      {
          if (args.Action == “copy”)
              // Path – Path from where the file was copied; TargetPath – Path where the file/folder is to be copied; RenameFiles – Files with same name in the copied location that are confirmed for renaming; TargetData – Data of the copied file.
             return this.operation.ToCamelCase(this.operation.Copy(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));
          else if (args.Action == “move”)
              // Path – Path from where the file was cut; TargetPath – Path where the file/folder is to be moved; RenameFiles – Files with same name in the moved location that is are confirmed for renaming; TargetData – Data of the moved file.
              return this.operation.ToCamelCase(this.operation.Move(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));
          else if (args.Action == “rename”)
              // Path – Current path of the renamed file; Name – Old file name; NewName – New file name.
              return this.operation.ToCamelCase(this.operation.Rename(args.Path, args.Name, args.NewName));
      }

      if (args.Action == “read”)
          // Path – Current path; ShowHiddenItems – Boolean value to show/hide hidden items.
          Return this.operation.ToCamelCase(this.operation.GetFiles(args.Path, args.ShowHiddenItems));
      else if (args.Action == “search”)
           // Path – Current path where the search is performed; SearchString – String typed in the searchbox; CaseSensitive – Boolean value which specifies whether the search must be case sensitive.
           return this.operation.ToCamelCase(this.operation.Search(args.Path, args.SearchString, args.ShowHiddenItems, args.CaseSensitive));
      else if (args.Action == “details”)
            // Path – Current path where details of file/folder is are requested; Name – Names of the requested folders.
            return this.operation.ToCamelCase(this.operation.Details(args.Path, args.Names));

      return null;
}
```

After executing these code examples, users can perform the file management operations added as items in the toolbar based on their roles in the Blazor File Manager component. Refer to the following output images.

**Admin**

![Admin](https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Admin.png)

**Employee**

![Employee](https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Employee.png)

**Guest**

![Guest](https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Guest.png)

## GitHub reference

Check out the code example for [Role-based authorization in Blazor File Manager on GitHub](https://github.com/SyncfusionExamples/blazor-filemanager-authorization "Role-based authorization in Blazor File Manager GitHub demo").

## Conclusion

Thanks for reading! This blog showed you how to enable role-based authorization in the Syncfusion [Blazor File Manager](https://www.syncfusion.com/blazor-components/blazor-file-manager "Blazor File Manager Component") component. This will help you prevent users from performing certain file management operations based on their roles in Blazor applications. Try out the steps in this blog and leave your feedback in the comments section below!

For current Syncfusion customers, the newest version of Essential Studio is available from the [license and downloads page](https://www.syncfusion.com/account/downloads "Essential Studio license and downloads page"). If you’re a new customer, then try our Blazor components by downloading a [free 30-day trial](https://www.syncfusion.com/account/manage-trials/downloads "Free evaluation of the Essential Studio products").

For questions, you can contact us through our [feedback portal](https://www.syncfusion.com/feedback/blazor-components "Syncfusion Feedback Portal"), [support forums](https://www.syncfusion.com/forums/blazor-components "Syncfusion Support Forum"), or [support portal](https://support.syncfusion.com "Syncfusion Support Portal"). We are always happy to assist you!

## Related blogs

- [Easily Use a Dynamic Blob Container in the Blazor File Manager](https://www.syncfusion.com/blogs/post/easily-use-a-dynamic-blob-container-in-the-blazor-file-manager.aspx "Blog: Easily Use a Dynamic Blob Container in the Blazor File Manager")
- [Simple Steps to Upload Files to Azure Blob Storage in Blazor App](https://www.syncfusion.com/blogs/post/simple-steps-to-upload-files-to-azure-blob-storage-in-blazor-app.aspx "Blog: Simple Steps to Upload Files to Azure Blob Storage in Blazor App")
- [Column Pinning: The Efficient Way to Organize Columns in the Blazor DataGrid](https://www.syncfusion.com/blogs/post/column-pinning-blazor-datagrid.aspx "Blog: Column Pinning: The Efficient Way to Organize Columns in the Blazor DataGrid")
- [Simple Steps to Integrate OpenAI (ChatGPT) with Syncfusion’s Blazor Rich Text Editor](https://www.syncfusion.com/blogs/post/integrate-chatgpt-blazor-rich-text-editor.aspx "Blog: Simple Steps to Integrate OpenAI (ChatGPT) with Syncfusion’s Blazor Rich Text Editor")