Trying to find out where roles are assigned to a particular user in an ASP.Net core app. I'm new to .net core so bare with me. I can debug and see the username and password but cannot figure out where the roles are set for this particular user? If there's something else I need to add here please advise.
I use the login provide and get "No roles assigned." below for the user. I have in the Login.cshtml.cs page:
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
var user = _signInManager.UserManager.Users.Where(a => a.Email == Input.Email).FirstOrDefault();
if (user == null || !user.IsActive)
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
else
{
var roles = await _userManager.GetRolesAsync(user);
if (!roles.Any())
{
ModelState.AddModelError(string.Empty, "No roles assigned.");
return Page();
}
if ((returnUrl ?? "").Length < 1)
{
returnUrl = await GetRoleHomepage(user);
}
}
return RedirectToPage(returnUrl);
}
Honestly, I'm used to website's, the old school pages because I'm coming from local government which is far behind private. Now I'm private and now stressed. Looking at the AccountController.cs I see:
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly SignInManager<AspNetUsers> _signInManager;
private readonly ILogger _logger;
public AccountController(SignInManager<AspNetUsers> signInManager, ILogger<AccountController> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToPage("/Index");
}
}
Thanks for the input: The only part I see with IdentityRole is in a class with this but it's empty:
using Microsoft.AspNetCore.Identity;
namespace Portal.HPAG.Data
{
public partial class AspNetRoles : IdentityRole
{
}
}
And then I found a AspNetRoles class:
using System;
using System.Collections.Generic;
namespace Portal.HPAG.Data
{
public partial class AspNetRoles
{
public AspNetRoles()
{
AspNetUserRoles = new HashSet<AspNetUserRoles>();
PartStatusTypeRoles = new HashSet<PartStatusTypeRoles>();
RoleLevels = new HashSet<RoleLevels>();
Stage = new HashSet<Stage>();
}
public string Id { get; set; }
public bool IsManager { get; set; }
public virtual ICollection<AspNetUserRoles> AspNetUserRoles { get; set; }
public virtual ICollection<PartStatusTypeRoles> PartStatusTypeRoles { get; set; }
public virtual ICollection<RoleLevels> RoleLevels { get; set; }
public virtual ICollection<Stage> Stage { get; set; }
}
}
Still digging through.
In addition to
AddToRoleAsync(TUser user, string role)andIsInRoleAsync, you should be able to iterating through roles in anIEnumerable<IdentityRole>variable.You should be able to set a new variable for
_roleManagerusing: