-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathLoginController.cs
More file actions
82 lines (69 loc) · 2.83 KB
/
LoginController.cs
File metadata and controls
82 lines (69 loc) · 2.83 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Duende.IdentityServer;
using Duende.IdentityServer.Services;
using Hosts.Shared.InMemory;
using IdentityManager2;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Hosts.IdentityServerAuthentication
{
[Route("login")]
public class LoginController : Controller
{
private readonly ICollection<InMemoryUser> users;
private readonly IIdentityServerInteractionService interactionService;
public LoginController(ICollection<InMemoryUser> users, IIdentityServerInteractionService interactionService)
{
this.users = users ?? throw new ArgumentNullException(nameof(users));
this.interactionService = interactionService ?? throw new ArgumentNullException(nameof(interactionService));
}
[HttpGet("login")]
public IActionResult Login(string returnUrl)
{
return View(new LoginModel {ReturnUrl = returnUrl});
}
[HttpPost("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));
}
var identityServerUser = new IdentityServerUser(user.Subject) {AdditionalClaims = claims};
await HttpContext.SignInAsync(identityServerUser);
if (Url.IsLocalUrl(model.ReturnUrl)) return LocalRedirect(model.ReturnUrl);
return LocalRedirect("~/");
}
ModelState.AddModelError("", "Invalid username or password");
return View(model);
}
[HttpGet("logout")]
public async Task<IActionResult> Logout(string logoutId)
{
await HttpContext.SignOutAsync();
var logoutContext = await interactionService.GetLogoutContextAsync(logoutId);
if (logoutContext.PostLogoutRedirectUri != null) return Redirect(logoutContext.PostLogoutRedirectUri);
return Redirect("/idm");
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
public string ReturnUrl { get; set; }
}
}