admin管理员组

文章数量:1123467

I have implemented identity in ASP.NET Core, with features like registration and login working properly, including returning a JWT. Now, I want to migrate the system to MongoDB with using MongoDB.EntityFrameworkCore package. During testing, I can successfully register a new user, and the user appears in the collection. However, when I attempt to log in, I encounter the following exception.

All I did

builder.Services.AddDbContext<AppDbContext>(ops => ops.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

to

builder.Services.AddDbContext<AppDbContext>(options =>

    options.UseMongoDB(connectionUri, databaseName)
);

in the AppDbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<User>().ToCollection("users");
}

What can cause this? The registration works as expected but when login throws this at signInManager.PasswordSignInAsync

var routeGroup = endpoints.MapGroup("");
 routeGroup.MapPost("/login", async Task<Results<Ok<AccessTokenResponse>, EmptyHttpResult, ProblemHttpResult>>
     ([FromBody] LoginRequest login, [FromQuery] bool? useCookies, [FromQuery] bool? useSessionCookies, [FromServices] IServiceProvider sp) =>
 {
     var signInManager = sp.GetRequiredService<SignInManager<TUser>>();

     var useCookieScheme = (useCookies == true) || (useSessionCookies == true);
     var isPersistent = (useCookies == true) && (useSessionCookies != true);
     signInManager.AuthenticationScheme = useCookieScheme ? IdentityConstants.ApplicationScheme : IdentityConstants.BearerScheme;

     // THIS FAILS WITH
     // MongoDB.Driver.Linq.ExpressionNotSupportedException: 'Expression not supported: i.ToClaim().'
     var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);

     if (result.RequiresTwoFactor)
     {
         if (!string.IsNullOrEmpty(login.TwoFactorCode))
         {
             result = await signInManager.TwoFactorAuthenticatorSignInAsync(login.TwoFactorCode, isPersistent, rememberClient: isPersistent);
         }
         else if (!string.IsNullOrEmpty(login.TwoFactorRecoveryCode))
         {
             result = await signInManager.TwoFactorRecoveryCodeSignInAsync(login.TwoFactorRecoveryCode);
         }
     }

     if (!result.Succeeded)
     {
         return TypedResults.Problem(result.ToString(), statusCode: StatusCodes.Status401Unauthorized);
     }

     // The signInManager already produced the needed response in the form of a cookie or bearer token.
     return TypedResults.Empty;
 });

本文标签: