SignInManager.SignInAsync(...) 不会在 Core Blazor ASP.NET 登录



我正在学习 ASP.Net 核心 Blazor 和SignInManager.SignInAsync以及SignInManager.PasswordSignInAsync不登录。我试过几次,但一直都失败了。我可以看到数据在 SQLServer 数据库表中。我看不到密码,但用户帐户在那里。我花了几天时间,但无法弄清楚

这是我的代码

登录页面组件

@page "/loginPage"
@using Microsoft.AspNetCore.Identity;
@using Microsoft.AspNetCore.Authentication;
@using GroupMembersInfo.Data;
@inject UserManager<IdentityUser> UserManager
@inject SignInManager<IdentityUser> SignInManager
@inject NavigationManager NavigationManager
<h3>Log In</h3>
<div class="row">
<div class="col-md-12">
<EditForm Model="@LoginUserModel" OnValidSubmit="@LogIn">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-group">
<label>User Id: </label>
<input @bind-value="LoginUserModel.Email" class="form-control" />
</div>
<div class="form-group">
<label>Password: </label>
<input @bind-value="LoginUserModel.Password" class="form-control" />
</div>
<div class="form-group">
<button type="submit">Login</button>
</div>
</EditForm>
</div>
</div>
@code {
public LoginUserModel LoginUserModel { get; set; } = new LoginUserModel();
public async Task LogIn()
{
var user = new IdentityUser
{
UserName = LoginUserModel.Email,
Email = LoginUserModel.Email
};
user.PasswordHash = SignInManager.UserManager.PasswordHasher.HashPassword(user, LoginUserModel.Password);
AuthenticationProperties properties = new AuthenticationProperties();
properties.IsPersistent = true;
await SignInManager.SignInAsync(user, properties).ContinueWith(p =>
{
var User = System.Security.Claims.ClaimsPrincipal.Current;
NavigationManager.NavigateTo("/");
});
//var result = await SignInManager.PasswordSignInAsync(user, LoginUserModel.Password, isPersistent: false, lockoutOnFailure: false);
//if (result.Succeeded)
//{
//    var User = System.Security.Claims.ClaimsPrincipal.Current;
//    NavigationManager.NavigateTo("/");
//}
}
}

启动.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using GroupMembersInfo.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
namespace GroupMembersInfo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("GMIDbConnection")));
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 2;
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
}).AddEntityFrameworkStores<AppDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
services.ConfigureApplicationCookie(options =>
{
options.SlidingExpiration = true;
options.Events.OnRedirectToLogin = cxt =>
{
cxt.Response.StatusCode = 401;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = cxt =>
{
cxt.Response.StatusCode = 403;
return Task.CompletedTask;
};
options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}

为什么不简单地使用给定的电子邮件和密码登录用户?

public async Task LogIn()
{
var result = await SignInManager.PasswordSignInAsync(LoginUserModel.Email, LoginUserModel.Password, isPersistent: false, lockoutOnFailure: false);
if (result.Succeeded)
{
NavigationManager.NavigateTo("/");
}
}

最新更新