Created
May 7, 2019 11:05
-
-
Save mikebrind/d06009612a9981eb70cfe63c92336b3f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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