在我的 LoginController 中,我已將 UserManager 和 SignInManager 注入到建構式中,并通過以下方式成功驗證了用戶:
var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);
result.Succeeded 為真。都好。我在瀏覽器中獲得了一個身份驗證 cookie。
在我的 _layout.cshtml 視圖中,我想使用 SignInManager 檢查我的用戶是否已登錄。我將正確的部分注入到 cshtml 檔案中,如下所示:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> signInManager
@inject UserManager<ApplicationUser> userManager
然后我使用代碼檢查 User 屬性是否已登錄。
@if (signInManager.IsSignedIn(User))
問題:看起來用戶宣告主體為空或未使用任何資料初始化。即使我成功進行了用戶身份驗證,signInManager.IsSignedIn 也將始終回傳 false。
我認為 SignInManager 應該創建我需要的所有默認宣告和主體。還有其他原因導致主體在 cshtml 視圖中不可用嗎?
編輯:添加了 startup.cs 代碼
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DocumentsContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddInfrastructure();
// For Identity
services.AddIdentity<ApplicationUser, IdentityRole>(
options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<DocumentsContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options => {
options.Cookie.Name = "Wdd.Identity.User";
options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
options.SlidingExpiration = true;
options.LoginPath = "/Login/Login";
options.LogoutPath = "/Account/Logout";
});
// Adding Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 3;
});
services.Configure<MailSettings>(Configuration.GetSection("MailSettings"));
services.Configure<AppConfiguration>(Configuration.GetSection("appConfiguration"));
InitCommon();
}
// 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("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
uj5u.com熱心網友回復:
您的專案將 cookie 身份驗證與身份混合在一起。
只需從 Startup.cs 中洗掉以下代碼:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465588.html
上一篇:從其他API方法在串列中添加值
