Live Chat Icon For mobile
Live Chat Icon

How do I do cookie authentication in Blazor?

Platform: Blazor| Category: General

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.

  1. Configure the cookie authentication services in the Startup.cs file.

    public class Startup
       . . .
       . . .
       public void ConfigureServices(IServiceCollection services)
          . . .
          . . .
       public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          . . .
          . . .
          app.UseEndpoints(endpoints =>
             . . .
             . . .

  2. Now, add a controller page to set the cookie to the browser and redirect the URL.

    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
        public class CookieController : ControllerBase
            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("/");

  3. 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 ]

        <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
            . . .
            . . .
            . . .

  4. Use form action to call the cookie controller to set the cookie and have it read by AuthorizeView user name.

    @page "/"
            <h1>Hello @context.User.Claims.First().Value</h1>
    <form action="cookie" method="post">
        <input type="text" name="name" />
        <input type="submit" />

  5. 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

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.