I like Blazor, and I like Razor and ASP stuff. I've been coding stuff in it for a while but I refuse to learn about their built in authorization APIs. I come from the world of PHP where cookie/session management was always really handled manually, so I always feel more comfortable handling all this myself.
So here's how I do my own access control without using their whole AuthorizeRouteView
stuff, here's an example App.razor
.
@using System.Reflection; <Router AppAssembly="@typeof(Program).Assembly"> <Found Context="routeData"> @{ // // If the page has an [AdminOnly], only let them see it if they're an admin // if (routeData.PageType.GetCustomAttributes<AdminOnlyAttribute>().Any() && !SessionInfo.IsAdmin ) { <LayoutView Layout="@typeof(MainLayout)"> <h1>404 - not found</h1> <p>Sorry, there's nothing at this address</p> </LayoutView> return; } if ( SessionInfo.IsBanned ) { <LayoutView Layout="@typeof(MainLayout)"> <h1>Ya Banned</h1> <p>Sorry, you're banned from this site. You must have done something really bad. Or was it your cousin?</p> </LayoutView> return; } } <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <h1>404 - not found</h1> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router>
So in the above example SessionInfo
is my custom service for managing user session. What you can see is that routeData contains a PageType. That's the Type of the component it's going to load.
So you can use that type to check for this. Like in this instance we're checking to see if it has an [AdminOnly] attribute. If it has and the current session isn't an admin, then it throws up a fuck off screen.
FYI AdminOnly is a custom attribute I added, but you can see that you can put any kind of logic here. Like below I see if the user is banned, and if they are then I show another fuck off screen.
Add a Comment