受欢迎的博客标签

Cookie Authentication with Asp .Net Core Server-side Blazor 3.x

Published

 

 

Blazor Server authentication

ASP.NET Core 6.x Blazor authentication and authorization

https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0

 

ASP.NET Core 3.x Blazor authentication and authorization

https://github.com/aspnet/AspNetCore.Docs/blob/master/aspnetcore/security/blazor/index.md

Authenticate users connecting to a SignalR hub

https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.0

 

step 1: add <CascadingAuthenticationState>

G:\x\src\Presentation\Admin\App.razor

.Net 5.x

old

<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

new

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

or

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData"
                                DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <h1>Sorry</h1>
                    <p>You're not authorized to reach this page.</p>
                    <p>You may need to log in as a different user.</p>
                </NotAuthorized>
                <Authorizing>
                    <h1>Authentication in progress</h1>
                    <p>Only visible while authentication is in progress.</p>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <h1>Sorry</h1>
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

 

.Net 3.x

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

 

step 2:

G:\x\src\Presentation\Admin\Shared\LoginComponent.razor

@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider





<AuthorizeView>
    <Authorized>
        <b>Hello, @context.User.Identity.Name!</b>
        <a class="ml-md-auto btn btn-primary"
           href="/logout?returnUrl=/"
           target="_top">Logout</a>
    </Authorized>
    <NotAuthorized>
        <input type="text"
               placeholder="User Name"
               @bind="@Username" />
        &nbsp;&nbsp;
        <input type="password"
               placeholder="Password"
               @bind="@Password" />
        <a class="ml-md-auto btn btn-primary"
           href="/login?paramUsername=@Username&paramPassword=@Password"
           target="_top">Login</a>
    </NotAuthorized>
</AuthorizeView>
@code {
    string Username = "";
    string Password = "";
}

 

 

When you create a non-server-side Blazor application you can use a method such as JWT Authentication with Dotnet Core 2.1 and Blazor app. However, server-side Blazor provides options for deeper integration between the ‘client side’ and ‘server side’ code because the ‘client side’ code is processed server-side. With server-side Blazor, we end up using less code, and things are a lot less complex because we can trustthat the end-user was not able to alter or hack the ‘client side’ code.

If the ‘client side’ code says a user is who they say they are, we can trust them. Otherwise, we have to always make a ‘round trip’ to the server, before permitting operations or returning sensitive data. The ‘round trip’ is still being made (because the ‘client site’ code is being generated ‘server side’), but, our code structure is now cleaner and more streamlined.

Application Authentication

image

Most business web applications require their users to log into the application.

image

The users enter their username and passwords, that are checked against a membership database.

image

Once authenticated, the application recognizes the user and now has the ability to deliver content securely.

To demonstrate how authentication works on a server-side Blazor application, we will strip authentication down to its most basic elements. We will simply set a cookie then read that cookie in the application.

Once the authentication process of a server-side Blazor application is understood, we can then implement an authentication and membership management system that meets our needs (for example, one that allows users to create and manage their user accounts).

NOTE: This sample code does not check to see if a person is using a legitimate username and password! You would need to add the proper code to check. This code is just a demonstration of how the process of authorizing a user works.

Create The Application

 

Open Visual Studio 2017.

image

Select File then New then Project.

image

Select ASP.NET Core Web Application.

Name the project BlazorCookieAuth.

image

Select Server-side Blazor.

Add Nuget Packages

image

In the Solution Explorerright-click on the client project (BlazorCookieAuth.App) and select Manage NuGet Packages.

image

Add references to the following libraries:

  • Microsoft.AspNetCore.Authorization
  • Microsoft.AspNetCore.Http
  • Microsoft.AspNetCore.Identity

Add Cookie Authentication

image

In the server project (BlazorCookieAuth.Server), open the Startup.cs file.

Add the following using statements to the top of the file:

 

// ******
// BLAZOR COOKIE Auth Code (begin)
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
// BLAZOR COOKIE Auth Code (end)
// ******

 

Alter the remaining code to the following, adding the sections marked BLAZOR COOKIE Auth Code:

 

   public class Startup
    {
        // This method gets called by the runtime. Use this method to 
        // add services to the container.
        // For more information on how to configure your application, 
        // visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // ******
            // BLAZOR COOKIE Auth Code (begin)
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
 
            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie();
            // BLAZOR COOKIE Auth Code (end)
            // ******
 
            // Adds the Server-Side Blazor services, and those registered 
            // by the app project's startup.
            services.AddServerSideBlazor<App.Startup>();
 
            // ******
            // BLAZOR COOKIE Auth Code (begin)
            // From: https://github.com/aspnet/Blazor/issues/1554
            // HttpContextAccessor
            services.AddHttpContextAccessor();
            services.AddScoped<HttpContextAccessor>();
 
            services.AddHttpClient();
            services.AddScoped<HttpClient>();
            // BLAZOR COOKIE Auth Code (end)
            // ******
 
            services.AddResponseCompression(options =>
            {
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
                {
                    MediaTypeNames.Application.Octet,
                    WasmMediaTypeNames.Application.Wasm,
                });
            });
        }
 
        // This method gets called by the runtime. 
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseResponseCompression();
 
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
 
            // ******
            // BLAZOR COOKIE Auth Code (begin)
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
 
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            // BLAZOR COOKIE Auth Code (end)
            // ******
 
            // Use component registrations and static files from the app project.
            app.UseServerSideBlazor<App.Startup>();
        }
    }

 

First the code adds support for cookies. Cookies are created by the application, and passed to the user’s web browser when the user logs in. 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.

This code also adds:

  • HttpContextAccessor
  • HttpClient

as services that will be accessed in client-side code using dependency Injection.

See this link for a full explanation of how HttpContextAccessor allows us to determine who the logged in user is.

The code also adds routing so that application navigation, from the client project Blazor code, to the server project login and logout pages, will work.

 

Add Server Project Login/Logout Pages

image

Logging in (and out) is performed in the server project.

Add a folder called Pages and add the following Razor pages and code:

 

_ViewImports.cshtml

 

@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

 

Login.cshtml

 

@page
@model BlazorCookieAuth.Server.Pages.LoginModel
@{
    ViewData["Title"] = "Log in";
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
    <title>BlazorCookieAuth</title>
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>
        <div class="sidebar">
            <div class="top-row pl-4 navbar navbar-dark">
                <a class="navbar-brand" href="">BlazorCookieAuth</a>
            </div>
        </div>
 
        <div class="main">
            <div class="top-row px-4">
                <h2>@ViewData["Title"]</h2>
            </div>
 
            <div class="content px-4">
 
                <form id="account" method="post">
                    <div class="form-group">
                        <label asp-for="Input.Email"></label>
                        <input asp-for="Input.Email" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label asp-for="Input.Password"></label>
                        <input asp-for="Input.Password" class="form-control" />
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">Log in</button>
                    </div>
                </form>
 
            </div>
        </div>
    </app>
</body>
</html>

 

Login.cshtml.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
 
namespace BlazorCookieAuth.Server.Pages
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {
        public string ReturnUrl { get; set; }
 
        [BindProperty]
        public InputModel Input { get; set; }
 
        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }
 
            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }
        }
 
        public async Task OnGetAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
 
            // Clear the existing external cookie
            try
            {
                await HttpContext
                    .SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch { }
 
            ReturnUrl = returnUrl;
        }
 
        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
 
            // *** !!! This is where you would validate the user !!! ***
            // In this example we just log the user in
 
            // (Always log the user in for this demo)
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, Input.Email),
                    new Claim(ClaimTypes.Role, "Administrator"),
                };
 
            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);
 
            var authProperties = new AuthenticationProperties
            {
                IsPersistent = true,
                RedirectUri = this.Request.Host.Value
            };
 
            try
            {
                await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
 
                return LocalRedirect(returnUrl);
            }
            catch 
            {
                return Page();
            }
        }
    }
}

 

Logout.cshtml

 

@page
@model BlazorCookieAuth.Server.Pages.LogoutModel
@{
    ViewData["Title"] = "Logout";
}
 
<h2>Logout</h2>

 

Logout.cshtml.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
 
namespace BlazorCookieAuth.Server.Pages
{
    public class LogoutModel : PageModel
    {
        public string ReturnUrl { get; private set; }
 
        public async Task<IActionResult> OnGetAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
 
            // Clear the existing external cookie
            try
            {
                await HttpContext
                    .SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }
 
            return LocalRedirect(returnUrl);
        }
    }
}

 

Add Client Project Code

image

In the client project, add a page called Login.cshtml to the Pages folder using the following code:

 

@using System.Security.Claims
@using Microsoft.AspNetCore.Http
 
@using BlazorCookieAuth.App.Shared
 
@page "/login"
@inject IHttpContextAccessor _httpContextAccessor
@inject HttpClient Http
 
    @if (User.Identity.Name != null)
    {
        <b>You are logged in as: @User.Identity.Name</b> 
        <a class="ml-md-auto btn btn-primary" 
           href="/logout?returnUrl=/" 
           target="_top">Logout</a>
    }
    else
    {
        <a class="ml-md-auto btn btn-primary" 
           href="/login?returnUrl=/" 
           target="_top">Login</a>
    }
 
    @functions {
        private ClaimsPrincipal User;
 
        protected override void OnInit()
        {
            base.OnInit();
 
            try
            {
                // Set the user to determine if they are logged in
                User = _httpContextAccessor.HttpContext.User;
            }
            catch { }
        }
    }

 

This code creates a login component (because the @page tag is set to ‘/login’), that calls the IHttpContextAccessor (that was registered in the server project code using dependency injection), to determine if the user is logged in and that they have a “Name”.

If the user is logged in, we display their name and a Logout button (that navigates the user to the logout page in the server project).

If they are not logged in, we display a Login button (that navigates the user to the login page in the server project).

 

image

Finally, we alter the MainLayout.cshtml page (in the Shared folder) to the following:

 

@inherits BlazorLayoutComponent
 
<div class="sidebar">
    <NavMenu />
</div>
 
<div class="main">
    <div class="top-row px-4">
        <!-- BLAZOR COOKIE Auth Code (begin) -->
        <Login />
        <!-- BLAZOR COOKIE Auth Code (end) -->
    </div>
 
    <div class="content px-4">
        @Body
    </div>
</div>

 

This adds the login component to the top of every page in the Blazor application.

image

We can now hit F5 to run the application.

image

We can click the Login button…

image

Log in

image

We can then look in the Google Chrome Web Browser DevTools and see the cookie has been created.

image

When we click Logout

image

The cookie is removed.

 

Special Thanks

This article would not be possible without sample code (using the full .Net Core Membership provider) provided by SQL-MisterMagoo.

 

Links

Blazor.net

BlazorTest (SQL-MisterMagoo's site)

Authentication for serverside Blazor (How to use IHttpContextAccessor)

Blazor Security/Authorization

Use cookie authentication without ASP.NET Core Identity

JWT Authentication with Dotnet Core 2.1 and Blazor app

Download

The project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

You must have Visual Studio 2017 (or higher) installed to run the code.