Last active
October 10, 2023 09:02
-
-
Save iambacon/648aa62f0c275e20d61585d7aa26d81e to your computer and use it in GitHub Desktop.
Blazor - redirect to login when unauthorized https://www.iambacon.co.uk/blog/blazor-authentication-and-authorisation-redirect-to-login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<CascadingAuthenticationState> | |
<Router AppAssembly="typeof(App).Assembly"> | |
<Found Context="routeData"> | |
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)"> | |
<Authorizing> | |
</Authorizing> | |
<NotAuthorized> | |
<RedirectToLogin /> | |
</NotAuthorized> | |
</AuthorizeRouteView> | |
</Found> | |
<NotFound> | |
<LayoutView Layout="typeof(MainLayout)"> | |
<h1>Page not found</h1> | |
<p>Sorry, but there's nothing here!</p> | |
</LayoutView> | |
</NotFound> | |
</Router> | |
</CascadingAuthenticationState> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Components; | |
namespace RenewPlus.Web.Shared.Components.Shared | |
{ | |
public class RedirectToLogin : ComponentBase | |
{ | |
[Inject] | |
protected NavigationManager NavigationManager { get; set; } | |
protected override void OnInitialized() | |
{ | |
NavigationManager.NavigateTo("login"); | |
} | |
} | |
} |
If you got Navigation error on NavigationManager.NavigateTo
you can use OnAfterRender
instead of OnInitialized
See [https://stackoverflow.com/a/58077203](this StackOverflow answer)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! I needed this