Authentication with Middleware in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Create new folder named Middlewares. In this folder, create new middleware as below:

In Middlewares folder, create new class named AdminMiddleware.cs as below:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace LearnASPNETCoreRazorPagesWithRealApps.Middlewares
{
    public class AdminMiddleware
    {
        private readonly RequestDelegate _next;

        public AdminMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            var path = httpContext.Request.Path;
            if (path.HasValue && path.Value.ToLower().StartsWith("/admin".ToLower()) && !path.Value.ToLower().StartsWith("/admin/login".ToLower()))
            {
                if (httpContext.Session.GetString("username") == null)
                {
                    httpContext.Response.Redirect("/admin/login");
                }
            }
            return _next(httpContext);
        }
    }

    public static class AdminMiddlewareExtensions
    {
        public static IApplicationBuilder UseAdminMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AdminMiddleware>();
        }
    }
}




Open Startup.cs file and add new configurations as below:

using LearnASPNETCoreRazorPagesWithRealApps.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();

            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession();

            app.UseAdminMiddleware();

            app.UseStaticFiles();

            app.UseMvc();
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Create new folder named Pages. In Pages folder, create new Razor Page named Index as below:

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Home Page</h3>

</body>
</html>

In project, create new folder named Areas. In Areas folder, create new folder named Admin. In Admin folder, create new folder named Pages. In Pages folder, create new Razor Pages as below:




In Pages folder, create new Razor Page named Login as below:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Areas.Admin.Pages
{
    public class LoginModel : PageModel
    {
        public string Msg;

        public void OnGet()
        {
        }

        public IActionResult OnPost(string username, string password)
        {
            if (username.Equals("admin") && password.Equals("123"))
            {
                HttpContext.Session.SetString("username", username);
                return RedirectToPage("Index");
            }
            else
            {
                Msg = "Invalid";
                return Page();
            }
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Areas.Admin.Pages.LoginModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Login</title>
</head>
<body>

    <h3>Login Admin</h3>
    <form method="post" asp-page="login">
        @Model.Msg
        <br />
        Username <input type="text" name="username" />
        <br />
        Password <input type="password" name="password" />
        <br />
        <input type="submit" value="Login" />
    </form>

</body>
</html>




In Pages folder, create new Razor Page named Index as below:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Areas.Admin.Pages
{
    public class IndexModel : PageModel
    {
        public string Username { get; set; }

        public void OnGet()
        {
            Username = HttpContext.Session.GetString("username");
        }

        public IActionResult OnGetLogout()
        {
            HttpContext.Session.Remove("username");
            return RedirectToPage("Login");
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Areas.Admin.Pages.IndexModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Admin Panel</h3>
    Welcome @Model.Username
    <br>
    <a asp-page="index" asp-page-handler="logout">Logout</a>

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

Access Index razor page in Admin area with following url: http://localhost:1115/admin/index without session

Test with invalid account is username: abc and password: 123

Test with valid account is username: admin and password: 123