I have two roles in my project fetched from Azure AD: User and Admin. I also have different views for each role and two different layouts for each role. The standard startup controller is the Home controller which is also the controller to the main page for user, but I want the startup controller to change if the logged in user is admin. What are best practice to achieve this and what is the best method to maintain scalability in the project. I am just a junior developr so try giving an answer that is easy to understand. Also I am using ASP.NET Core 7.
I have tried setting the startup controller to "Dashboard" which is the main page for admin, and then setting authorization to that controller so only an admin role can access it. Then my idea was to create a redirect to the homecontroller index if the user don’t have acces (is not an admin).
Program.cs
app.MapControllerRoute(
name: "default",
pattern: "{controller=Dashboard}/{action=Index}/{id?}");
DashboardController.cs
[Authorize(Roles = "Admin")]
2
Answers
If you know how to make this redirect to Home/Index that you said, I think it might be a good solution.
Another possible solution is to use a custom Action Filter. “Authorize” is an Action Filter already included in the framework, but you can write your own.
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs
So, you can create something like
[MyCustomActionFilter(Roles = “Admin”)]
. This filter would be called on every call to the DashboardController.cs, and you can write the code that you want inside it, like so:You can call the filter on every call made to the DashboardController.cs, or specify which actions inside the controller would trigger the filter:
You can use dynamic route value transformation for "root" address:
Or use custom redirect middleware which will redirect request based on some conditions (like empty route and role).