1 year ago
#383268
Gamalina
Razor Pages & Role Based Authorzation. Got trouble with applying roles to Shared Layout
I am working on my school project, which I have done. And want to try to add something more. Right now I have the problem with role-based authorzation. I have set up in the controllers to autherize only the one that should be able to get in. However I want to have in _Layout so if you are logged in and has the role "Admin" You would be able to see a link to the Admin page. And if you are a normal user, you can't.
Here is some of my code, I can provide a lot more if need be. Thanks for your time
_Layout Page:
@if (User.IsInRole("Admin"))
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="RoleTest/Admin">Admin Page</a>
</li>
}
@if (User.IsInRole("Admin") || User.IsInRole("NormalPW"))
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="RoleTest/UserWithPower">UserWithPowerPage</a>
</li>
}
@if (User.IsInRole("Admin") || User.IsInRole("NormalPW") || User.IsInRole("NormalNoPW"))
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="RoleTest/UserWithPower">UserWithoutPowerPage</a>
</li>
}
I have tried this too:
@if (LoginModel.LoggedInUser.UserRole == "Admin")
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="RoleTest/Admin">Admin Page</a>
</li>
}
But I get a "Possible 'System.NullReferenceException'.
This is my Login controller:
public async Task<IActionResult> OnPost()
{
List<User> users = _userService.GetAll();
foreach (User u in users)
{
if (UserName == u.UserName && Password == u.Password)
{
LoggedInUser = u;
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("/UserStories/Index");
}
}
Message = "Invalid attempt";
return Page();
}
c#
asp.net
authorization
razor-pages
claims-based-identity
0 Answers
Your Answer