-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathLoginController.cs
More file actions
65 lines (55 loc) · 2.06 KB
/
LoginController.cs
File metadata and controls
65 lines (55 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Hosts.Shared.InMemory;
using IdentityManager2;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
namespace Hosts.CookieAuthentication
{
[Route("login")]
public class LoginController : Controller
{
private readonly ICollection<InMemoryUser> users;
public LoginController(ICollection<InMemoryUser> users)
{
this.users = users ?? throw new ArgumentNullException(nameof(users));
}
[HttpGet(Name = "CookieAuthentication-login")]
public IActionResult Login(string returnUrl)
{
return View(new LoginModel {ReturnUrl = returnUrl});
}
[HttpPost("CookieAuthentication-login")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model)
{
var user = users.FirstOrDefault(x => x.Username == model.Username && x.Password == model.Password);
if (user != null)
{
var claims = new List<Claim>
{
new Claim("sub", user.Subject),
new Claim("name", user.Username)
};
foreach (var role in user.Claims.Where(x => x.Type == IdentityManagerConstants.ClaimTypes.Role))
{
claims.Add(new Claim(IdentityManagerConstants.ClaimTypes.Role, role.Value));
}
await HttpContext.SignInAsync("cookie", new ClaimsPrincipal(new ClaimsIdentity(claims, "cookie")));
if (Url.IsLocalUrl(model.ReturnUrl)) return LocalRedirect(model.ReturnUrl);
return LocalRedirect("~/");
}
ModelState.AddModelError("", "Invalid username or password");
return View(model);
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
public string ReturnUrl { get; set; }
}
}