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.
    [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();
             . . .
             . . .
          });
       } 
    }

  2. 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("/");
            }
        }
    }

  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 ]

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

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

  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.