Home > Net >  Select ClaimsIdentity directly via Entity Framework and LINQ
Select ClaimsIdentity directly via Entity Framework and LINQ

Time:05-06

I have a user table with following columns:

  • Id : Guid
  • Name: string
  • IsAdmin: bool

Now I want to create a select using EF Core with a ClaimsIdentity result:

public ClaimsIdentity? GetIdentity(string email, string password)
{
   return _context.Users
       .Where(user => user.Email.ToLower().Equals(email.ToLower()))
       .Where(user => user.Password.Equals(password))
       .Select(user => new ClaimsIdentity(
           new Claim("id", user.Id.ToString()),
           new Claim(ClaimTypes.Role, UserRole.ADMIN.ToString())
       ))
       .SingleOrDefault();

But currently I don't know if the dynamic claims-list is possible respectively how I can archive that. The claim "Admin" should only be in the claims-list if the user is administrator (IsAdmin = true).

Or do I need a temporary class/DTO (e.g. UserIdentity) to select the data? But in that case, can I then have a dynamic list of roles?

CodePudding user response:

You can do something like this for your use case

public ClaimsIdentity? GetIdentity(string email, string password)
             {
            return _context.Users
                .Where(user => user.Email.ToLower().Equals(email.ToLower()))
                .Where(user => user.Password.Equals(password))
                .Select(user =>
                {
                    var identity = new ClaimsIdentity(
                    new Claim("id", user.Id.ToString())
                    );
                    if (UserRole.ADMIN == true)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, UserRole.ADMIN.ToString()))
                    }
                    return identity;
                })
                .SingleOrDefault();
            }
  • Related