Authentication in Blazor is that bit more complicated than MVC or Razor…
Here goes:
Starting with App.razor there is a <Found>
and <NotFound>
tag helper. Inside the Found there is an <AuthorizeRouteView>
which allows you authorize pages and views. However by default an unauthorized user will just get a ‘Not authorized’ message instead of redirecting to the login page. To achieve this we need to open the <AuthorizeRouteView>
and put a <NotAuthorized>
child inside. In the <NotAuthorized>
we can reference a <RedirectToLogin>
class base component. This will redirect the user to the login page.
public class RedirectToLogin : ComponentBase {
[Inject]
protected NavigationManager NavigationManager { get; set; }
protected override void OnInitialized() {
NavigationManager.NavigateTo("/Login");
}
}
Each individual page still needs an @attribute [Authorize]
attribute though. [According to this question you may be able to set the Auth attribute on the _host page globally. Not sure if this will work or not.]
According to the docs you can add this to the Startup.cs file to decide where the redirect to the login page will be redirected to:
services.ConfigureApplicationCookie(options => {
options.LoginPath = "/Login";
options.AccessDeniedPath = "/AccessDenied";
});
I can’t see how this would work though, as there is nothing that actually tries to redirect. Adding an [Authorize]
attribute only shows the ‘Not authorized’ message instead of redirecting to the login page.
Either way, all the above still leaves one loophole to overcome. As we started with, this is all in the <Found>
tag in the App.razor file. If a user were to go to a url the doesn’t exist, we will fall through to the <NotFound>
tag. By default this is set to use the default MainLayout like this: <LayoutView Layout="@typeof(MainLayout)">
if you have a NavMenu like the one that comes in the ‘Out of the box template’ then this will be shown as well as a top bar etc. If you are trying to restrict users to authorized ones only, by requesting a not found url, they will be able to see your NavMenu and see what pages you have on your site.
The simplest way to answer this would be to add a <NotAuthorized>
attribute on the NavMenu which would show a link to the Login page.
As noted around the web, hiding elements is not fool proof, as they are still loaded on the client’s side and therefore may be able to get a hold of them. Authorizing on the server side is therefore still required to protect sensitive info. This will still be ok if it’s just links that will be protected in the NavMenu.