Reputation: 14610
Initially I was using:
var user = await _userManager.FindByEmailAsync(email);
and now I'm using:
var normalizedEmail = _userManager.NormalizeEmail(loginDto.Email);
var user = await _userManager.Users
.Include(p => p.TokensPoints)
.Include(p => p.UserRoles)
.ThenInclude(r => r.Role)
.SingleOrDefaultAsync(x => x.NormalizedEmail == normalizedEmail);
In terms of security for logging into a user account like this:
var result = await _signInManager.CheckPasswordSignInAsync(user, password, false);
Is there any difference between the two calls to fetch the user? Pro's vs Con's
Upvotes: 0
Views: 67
Reputation: 1702
The UserManager.FindByEmailAsync
method is part of the UserManager class. Its implementation depends on the IUserEmailStore interface. It can find users by email, but it is limited to querying simple information of users. It does not involve querying related tables, and the query speed is fast.
Source code example: https://github.com/dotnet/aspnetcore/blob/main/src/Identity/Extensions.Core/src/UserManager.cs#L1286
SingleOrDefaultAsync
is a LINQ extension method for asynchronous query. It is used to return the only element that meets the specified conditions from a sequence. If the sequence is empty, it returns the default value; if there are multiple elements in the sequence, an exception is thrown. https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.singleordefaultasync?view=efcore-8.0
This method allows you to query users through LINQ, include related navigation properties, and load data from related tables. SingleOrDefaultAsync is relatively more flexible and allows loading related data, but you need to be careful to validate the email parameter to prevent SQL injection attacks.
The CheckPasswordSignInAsync
method is part of the SignInManager class and is used to verify the user's password and attempt to log in. . From the source code, we can see https://github.com/dotnet/aspnetcore/blob/main/src/Identity/Core/src/SignInManager.cs#L374 that it not only checks the password, but also handles the lock logic after a failed login.
Upvotes: -1