I am developing a blazor web assembly app, I am authenticating users using custom RouteView.
I simply check if a component has AuthorizeAttribute and then call my AccountService to check if a user is logged in or not.
public class AuthRouteView : RouteView
{
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IAccountService AccountService { get; set; }
protected override void Render(RenderTreeBuilder builder)
{
var authorize = Attribute.GetCustomAttribute(RouteData.PageType, typeof(AuthorizeAttribute)) != null;
var allowAnonymous = Attribute.GetCustomAttribute(RouteData.PageType, typeof(AllowAnonymousAttribute)) != null;
var loggedIn = AccountService.isLoggedIn();
if (authorize && !loggedIn && !allowAnonymous)
{
var returnUrl = WebUtility.UrlEncode(new Uri(NavigationManager.Uri).PathAndQuery);
NavigationManager.NavigateTo($"login?returnUrl={returnUrl}");
}
else
{
base.Render(builder);
}
}
}
It's all working fine, Now what I want to do is check for a role for some components, I was thinking of writing a custom Authorize attribute, moved all the logic to it from AuthRouteView, and then passing a role to it and that attribute will then check if the user has a role, but the attribute is not getting invoked.
In my AuthRouteView, I am unable to get the parameter I passed to the attribute so I'll check that here.
here is my custom attribute.
public class Authorize : Attribute, IAuthorizeData
{
private string role;
public Authorize(string role = "")
{
this.role = role;
}
}
I have checked in Attribute and IAuthorizeData they both don't contain any protected method for me to override.
I inherited it from IAuthorizeData because the built-in Authorize attribute is also inherited from it.
I am confused about two things here?
Am I following the right way (using AuthRouteView) to Authenticate or Authorize the User. (Authorization is where I am stuck right now). because I don't find any example for custom authentication and authorization.
Can we write custom attributes that get invoked before the component initialize?