Cookies are created by the application and passed to the user’s web browser when the user submits the request. The web browser passes the cookie back to the application to indicate that the user is authenticated. When the user logs out, the cookie is removed.
Follow these steps to set a cookie and read that cookie with authentication in Blazor.
Configure the cookie authentication services in the Startup.cs file.
[Startup.cs]public class Startup
{
. . .
. . .
public void ConfigureServices(IServiceCollection services)
{
. . .
. . .
services.AddAuthentication("Cookies").AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
. . .
. . .
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
. . .
. . .
});
}
}Now, add a controller page to set the cookie to the browser and redirect the URL.
[CookieController.cs]using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace blazorcookie
{
[Route("/[controller]")]
[ApiController]
public class CookieController : ControllerBase
{
[HttpPost]
public async Task<ActionResult> Login([FromForm] string name)
{
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, name)
}, "auth");
ClaimsPrincipal claims = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(claims);
return Redirect("/");
}
}
}To use the authorized view, configure the CascadingAuthenticationState component in the App.razor file. This will let you check the authentication state inside the Blazor application.
[ App.razor ]<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
. . .
. . .
. . .
</Router>
</CascadingAuthenticationState>Use form action to call the cookie controller to set the cookie and have it read by AuthorizeView user name.
[Index.razor]@page "/"
<AuthorizeView>
<Authorized>
<h1>Hello @context.User.Claims.First().Value</h1>
</Authorized>
</AuthorizeView>
<form action="cookie" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>Run the application and submit the form request. You will find an authentication cookie with the scheme “Cookies,” which was specified in the ConfigureServices() method of the Startup class.
Refer to this blog post for more details and download the sample on GitHub.
Share with