This library adds a simple way of being able to sign in, sign out and remember the signed in user (e.g. via cookies) directly from Blazor without the need of redirecting the user to Razor pages.
Existing Blazor components such as AuthorizeView will continue to work as expected.
⚠️ This library is meant only for server-sided Blazor.
1. Install BytexDigital.Blazor.Server.Authentication or BytexDigital.Blazor.Server.Authentication.Identity
Make sure to register the services after other calls to add Authentication services.
services.AddHttpContextAccessor();services
.AddAuthenticationService()
.AddCookiePrincipalStorage()
.AddIdentityPrincipalProvider<ApplicationUser>();services
.AddAuthenticationService()
.AddCookiePrincipalStorage()
.AddPrincipalProvider<ImplementationOfIPrincipalProvider>();<script src="/_content/BytexDigital.Blazor.Server.Authentication/bundle.js"></script><BytexDigital.Blazor.Server.Authentication.CascadingAuthenticationProvider>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<NotFound></NotFound>
</LayoutView>
</NotFound>
</Router>
</BytexDigital.Blazor.Server.Authentication.CascadingAuthenticationProvider>Use IServerAuthenticationService.SignInAsAsync and IServerAuthenticationService.SignOutAsync to change the signed in user.
Reloading the page is not necessary. You can use IServerAuthenticationService.GetSignedInIdOrDefault and IServerAuthenticationService.IsSignedIn to get information about the current authentication status.
The IPrincipalProvider is used to convert a user id to a ClaimsPrincipal object. The included IdentityPrincipalProvider will convert the user id to a principal using a UserStore<TUser>.