Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using AuthenticationSample.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
namespace AuthenticationSample.Pages
public class IndexModel : PageModel
private readonly IConfiguration configuration;
public IndexModel(IConfiguration configuration)
this.configuration = configuration;
public string UserName { get; set; }
[BindProperty, DataType(DataType.Password)]
public string Password { get; set; }
public string Message { get; set; }
public async Task<IActionResult> OnPost()
var user = configuration.GetSection("SiteUser").Get<SiteUser>();
if (UserName == user.UserName)
var passwordHasher = new PasswordHasher<string>();
if (passwordHasher.VerifyHashedPassword(null, user.Password, Password) == PasswordVerificationResult.Success)
var claims = new List<Claim>
new Claim(ClaimTypes.Name, UserName)
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
return RedirectToPage("/admin/index");
Message = "Invalid attempt";
return Page();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment