Role-Based Authorization in Blazor File Manager: An Overview
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (179).NET Core  (28).NET MAUI  (214)Angular  (112)ASP.NET  (51)ASP.NET Core  (83)ASP.NET MVC  (90)Azure  (41)Black Friday Deal  (1)Blazor  (227)BoldSign  (15)DocIO  (24)Essential JS 2  (109)Essential Studio  (200)File Formats  (69)Flutter  (133)JavaScript  (226)Microsoft  (120)PDF  (82)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (946)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (45)Webinar  (52)Windows Forms  (61)WinUI  (71)WPF  (163)Xamarin  (160)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (9)Business intelligence  (55)Button  (4)C#  (158)Chart  (140)Chart of the week  (54)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (70)Development  (661)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (14)Excel  (43)Extensions  (23)File Manager  (7)Gantt  (19)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (512)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (4)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (14)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (113)UI  (393)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (618)What's new  (334)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Role-Based Authorization in Blazor File Manager: An Overview

Role-Based Authorization in Blazor File Manager: An Overview

Our previous blog showed us how to easily create a Blazor server application 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 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.

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.

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.

Role

Subject

File operations

Admin

Admin can perform all the supported operations of the File Manager.

  • NewFolder
  • Upload
  • Cut
  • Copy
  • Paste
  • Delete
  • Download
  • Rename
  • SortBy
  • Refresh
  • Selection
  • View
  • Details

Employee

Employees can perform file and folder management operations.

  • Cut
  • Copy
  • Paste
  • Delete
  • Download
  • Rename
  • SortBy
  • Refresh
  • Selection
  • View
  • Details

Guest

Guest users can view and download the files and folders.

  • Download
  • SortBy
  • Refresh
  • Selection
  • View
  • Details

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

User roles

User roles

User Role ID

User Role ID

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.razor 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.

@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.

<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 repository.

[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

Employee

Employee

Guest

Guest

GitHub reference

Check out the code example for Role-based authorization in Blazor File Manager on GitHub.

Conclusion

Thanks for reading! This blog showed you how to enable role-based authorization in the Syncfusion Blazor File Manager 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. If you’re a new customer, then try our Blazor components by downloading a free 30-day trial.

For questions, you can contact us through our feedback portal, support forums, or support portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Comments (1)

Hi
How can I authorize FileManagerController for Administrator role?
If I put [Auhtorize] for controller I get an error.

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed