-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccountController.cs
More file actions
79 lines (70 loc) · 2.46 KB
/
Copy pathAccountController.cs
File metadata and controls
79 lines (70 loc) · 2.46 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
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
/*
* A simple accountcontroller used for testing authorization
* using RBAC. Accounts and roles are provided in the configuration
* file.
*/
namespace SimpleRBAC.Controllers
{
public class AccountController : Controller
{
private readonly IConfiguration _configuration;
public AccountController( IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult AccessDenied()
{
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction(nameof(Login));
}
[AllowAnonymous]
public IActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(string Username, string Password)
{
var authorizedUserEntry = _configuration.GetSection("AuthorizedUsers").GetSection(Username);
if (authorizedUserEntry.Exists())
{
if (authorizedUserEntry["Password"] != Password)
{
ViewData["ErrorDscr"] = "Incorrect password";
}
else
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, Username));
var roles = authorizedUserEntry.GetSection("Roles").Get<string[]>();
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity));
return RedirectToAction("Index", "Home");
}
}
else
{
ViewData["ErrorDscr"] = "User not found";
}
return View();
}
}
}