@page "/login" @using System.ComponentModel.DataAnnotations @using System.Security.Claims @using Microsoft.AspNetCore.Authentication @using Microsoft.AspNetCore.Authentication.Cookies @using AuthenticationService = JustShortIt.Service.AuthenticationService @inject AuthenticationService Authentication @inject IHttpContextAccessor HttpContextAccessor @inject NavigationManager Navigation Login - Just Short It

Login

@code { [SupplyParameterFromForm] public LoginModel Model { get; set; } = default!; public string? Message { get; set; } protected override void OnInitialized() { // ReSharper disable once NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract Model ??= new LoginModel(); } public sealed class LoginModel { [Required(AllowEmptyStrings = false, ErrorMessage = "User name is required.")] public string? Username { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Password is required.")] public string? Password { get; set; } } private async Task Submit() { if (Model.Username is null || Model.Password is null) return; var context = HttpContextAccessor.HttpContext; if (context is null) throw new ArgumentNullException("context"); if (Authentication.IsUser(Model.Username, Model.Password)) { var claims = new List { new(ClaimTypes.Name, Model.Username), new(ClaimTypes.Role, "Administrator") }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var properties = new AuthenticationProperties{ AllowRefresh = true, IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1), IssuedUtc = DateTimeOffset.UtcNow, RedirectUri = "/" }; await context.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties); Navigation.NavigateTo("/urls", true); } else { Message = "Invalid user name or password."; } } }