Skip to content

Repository files navigation

Blazor Cookie Authentification Example

Prototype (Blazor Server) with cookie authentication. This prototype is only meant to show the functionality of cookie authentication and is a pure demo application. This code should never be used in a productive environment without any modifications. In productive environments the UserService can be passed a database context and the users will be matched in the database.



Features

  • Login Control displayed on every page
  • Login & Logout Functionality
  • Claim Management
  • After inactivity of 30 sec, user will be logged out automatically

Demo

  • Weather forecast is protected if not authorized
  • Counter page is based on the claim "Admin" (does not exist! Dummy to show the functionality of the roles)
  • Login control shows username if successfully logged in
  • Sliding Expiration and logout after inactivity of 30 Seconds.

Screenshots

Unauthorized View on FetchData:

Unauthorized

After successful login:

Authorized

View encrypted Cookie:

Authorized

Core Concepts

Program.cs

builder.Services.AddScoped<UserService>();builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>{options.ExpireTimeSpan=TimeSpan.FromSeconds(30);options.SlidingExpiration=true;options.AccessDeniedPath="/Forbidden";options.LoginPath="/login";});builder.Services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();varcookiePolicyOptions=newCookiePolicyOptions{MinimumSameSitePolicy=SameSiteMode.Strict,};app.UseCookiePolicy(cookiePolicyOptions);app.UseAuthorization();app.UseAuthentication();

Login Control

//use authorizedView and unauthorized View//Encode UserName & Password for query parameter

Login.cshtml

Code Behind is used for setting cookiePolicyOptions

publicasyncTask<IActionResult>OnGetAsync(stringparamUsername,stringparamPassword){stringreturnUrl=Url.Content("~/");try{// Clear the existing external cookieawaitHttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);}catch{}//TODO check paramUserName & paramPassword in DBvarclaims=newList<Claim>{newClaim(ClaimTypes.Name,paramUsername),newClaim(ClaimTypes.Role,"Administrator"),};varclaimsIdentity=newClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);varauthProperties=newAuthenticationProperties{IsPersistent=true,RedirectUri=this.Request.Host.Value};try{awaitHttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,newClaimsPrincipal(claimsIdentity),authProperties);}catch(Exceptionex){stringerror=ex.Message;}returnLocalRedirect(returnUrl);}

Weather Forecast

Use Authentification for View

//FetchData.razor
@page "/fetchdata"
@using CookieAuthenticationExample.Data@inject WeatherForecastService ForecastService
@attribute [Authorize]//This is important!<PageTitle>Weather forecast</PageTitle><h1>Weather forecast</h1>

Counter (Role Authentification)

//Counter.razor
@page "/counter"@attribute[Authorize(Roles="Admin")]// This is important - only visible if claim role contains admin<PageTitle>Counter</PageTitle><h1>Counter</h1>

About

ASP Net Core Prototype (Blazor Server) cookie authentication without identity

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages