Skip to content

Instantly share code, notes, and snippets.

@fourgeotf
Last active February 10, 2022 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fourgeotf/b3ff4c23e25f9fb71934204762cb4999 to your computer and use it in GitHub Desktop.
Save fourgeotf/b3ff4c23e25f9fb71934204762cb4999 to your computer and use it in GitHub Desktop.
[BLAZOR Custom Authentication] #blazor #cs #identity #authentication #autorization #custom
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<CascadingAuthenticationState>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<h1>404 Error</h1>
<p role="alert">Désolé, il n'y a rien à cette adresse.</p>
</LayoutView>
</CascadingAuthenticationState>
</NotFound>
</Router>
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
namespace BatMan.Server
{
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "fourgeotf@ciminfo.fr")
}, "apiauth_type");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
}
@page "/"
<PageTitle>Index</PageTitle>
<AuthorizeView>
<Authorized>
<p>Bienvenue, @context.User.Identity.Name</p>
</Authorized>
<NotAuthorized>
<p>Vous n'êtes pas authentifié !</p>
</NotAuthorized>
</AuthorizeView>
...
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
...
app.UseRouting();
app.UseCors();
// Ajout des lignes pour Authentication et Autorization
app.UseAuthentication();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment