Skip to content

Instantly share code, notes, and snippets.

@mikebrind
Created May 7, 2019 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikebrind/d06009612a9981eb70cfe63c92336b3f to your computer and use it in GitHub Desktop.
Save mikebrind/d06009612a9981eb70cfe63c92336b3f to your computer and use it in GitHub Desktop.
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;
}
[BindProperty]
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