c# - 即使在 asp.net core 2.2 中使用 PasswordSignInAsync 成功登录后,User.Identity.IsAuthenticated 也总是返回 false
问题描述
每当我点击登录时,用户都会使用 signinManager.PasswordSignInAsync 登录,并且 result.Succeeded 为真。问题是,如果我第二次调用登录,用户不会坚持。User.Identity.IsAuthenticated 下次应该为真,但始终为假
[HttpGet("[action]")]
public async Task<IActionResult> Login()
{
try
{
if (User.Identity.IsAuthenticated)
{
Console.WriteLine("You are alredy Logged In...................");
var claims = User.Claims;
return Ok("Authenticated");
}
else
{
var result = await signinManager.PasswordSignInAsync("myEmail.com", "Password", true, true);
if (result.Succeeded)
{
Console.WriteLine("Logged in successfully....");
}
return Ok("Logged in successfully ");
}
}
catch (System.Exception e)
{
Console.WriteLine("........................................" +e.Message);
return Ok(e.Message);
throw;
}
}
StartUp.Cs 中的 ConfigureServices 看起来像
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContextBase>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<DbContextBase>()
.AddDefaultTokenProviders();
services.AddMvc();
}
Startup.cs 中的配置方法如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
登录方法在第二次点击时必须返回“Authenticated”。
解决方案
您忘记配置实际的身份验证方法,例如 cookie。
在你的ConfigureServices
:
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
推荐阅读
- mysql - node.js 中基于角色的登录身份验证
- r - 当尝试保存输出时,为什么 R 中的系统调用会失败?
- gitlab-ci - 如何手动触发 gitlab 管道测试?
- azure - 预配 Azure 资源时出错 (Ubuntu)
- css - 定位图像和文本响应式
- angular - 贝宝集成中的 ExpressionChangedAfterItHasBeenCheckedError
- sass - 如何从 SASS 中的字符串中修剪空格?
- c++ - 如何将具有 const noexcept 的虚函数从 c++11 转换为 c++17?
- python - 无法删除某些列表元素
- java - 通过单元测试中的字段“userService”表示不满足的依赖关系