Search code examples
asp.net-corerazorasp.net-identity

How do I show signed in users information?


I'm trying to understand how this works without adding Roles, but maybe it won't. I'm following along with Microsofts tutorial about protecting user data with Authorize but I am still having trouble understanding this without roles.

In my database, I have the AspNet identity tables and a few custom tables. Is there a way to show the signed-in users' data to them from the custom table? I have look on here but I'm probably not searching for the right thing.

I have tried getting the user email from context and checking userManager for that email if it's found then pushing it to a list but that just returns null.

public async Task OnGetAsync()
        {
            var employee = from e in Context.EmpInfo
                select e;
           
            var currentUserId = UserManager.GetUserId(User);

            employee = employee.Where(e =>e.OwnerId == currentUserId);
            
            EmpInfo = await employee.ToListAsync();
        }

Solution

  • Is there a way to show the signed-in users' data to them from the custom table?

    they were setting OwnerId to the admin role ID

    In AspNetUsers table as below, Id of user is a primary key. To implement one-to-one relationships between AspNetUsers and Employee, you can store corresponding AspNetUsers.Id in OwnerId of specific employee, then you can get detailed employee information based on retrieved User's Id.

    enter image description here

    I guess I would need to compare email against email?

    If you persist email information in both AspNetUsers and Employee tables, getting corresponding employee information by comparing email as you mentioned could be an alternative approach.

    //find user and get user's email
    var user = await _userManager.GetUserAsync(User);
    var user_email = user?.Email.ToString();
    
    //...
    //query employee table with retrieved user_email 
    //code logic here...
    

    Besides, please note that if you do not configure RequireUniqueEmail in your ASP.NET Core Identity system, users might be with duplicate emails.