HTTP Basic Authentication in ASP.NET Core Razor Pages

पिछ्ला सम्बन्धित लेख HTTP Basic Authentication फ्लो

ASP.NET Core Razor Pages एप्लीकेशन बनाए जिसका नाम BasicAuthDemo है।

प्रोजेक्ट file इस प्रकार है:
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

HTTP Basic Authentication को हैंडल करने के लिए निम्न BasicAuthenticationHandler क्लास file बनाए।  ध्यान दीजिए की सरलता के लिए यूजरनाम और पासवर्ड हार्ड कोडेड है। वास्तव में इसे किसी डेटाबेस में रखना चाहिए।  

using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;

namespace BasicAuthDemo
{
    public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public BasicAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder)
        {
        }
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
                return Task.FromResult(AuthenticateResult.Fail("Missing Authorization Header"));

            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]!);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter!);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':');

                var username = credentials[0];
                var password = credentials[1];

                // Dummy validation (replace with DB check)
                if (username != "admin" || password != "1234")
                    return Task.FromResult(AuthenticateResult.Fail("Invalid Username or Password"));

                var claims = new[]
                {
                new Claim(ClaimTypes.Name, username)
                };

                var identity = new ClaimsIdentity(claims, Scheme.Name);
                var principal = new ClaimsPrincipal(identity);
                var ticket = new AuthenticationTicket(principal, Scheme.Name);

                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
            catch
            {
                return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
            }
        }
        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.Headers["WWW-Authenticate"] = "Basic realm=\"MyApp\"";
            return base.HandleChallengeAsync(properties);
        }
    }
}
BasicAuthenticationHandler को सर्विस के रूप में रजिस्टर करें।  
using BasicAuthDemo;
using Microsoft.AspNetCore.Authentication;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddAuthentication("BasicAuthentication")
    .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>(
        "BasicAuthentication", null);

builder.Services.AddAuthorization();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();
अब एक रिसोर्स बनाए जिसको एक्सेस करने के लिए ऑथेंटिकेशन चाहिए।  
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;

[Authorize]
public class IndexModel : PageModel
{
    public string Message { get; set; } = string.Empty;

    public void OnGet()
    {
        Message = $"Hello {User.Identity?.Name}, you are authenticated!";
    }
}
अब इस रिसोर्स के डाटा को प्रदर्शित कीजिए।  
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
   @Model.Message
</div>

अब एप्लीकेशन को रन कर परीक्षण कीजिए।  


टिप्पणियाँ

इस ब्लॉग से लोकप्रिय पोस्ट

Differences between in-process and out-of-process hosting models

Web Fundamental Concepts in Hindi for Beginners - FAQs with their Answers Part-1

Introduction to ASP.NET Core and Web Frameworks