gpt4 book ai didi

c# - User.Identity.Name 在 PasswordSignInAsync MVC .Net Core 3.0 之后始终为 null 并声明计数为 0

转载 作者:行者123 更新时间:2023-12-03 16:22:32 25 4
gpt4 key购买 nike

我有一个无法使用 ASP.NET MVC Core 3.0 解决的问题。登录后,结果成功并成功返回到我想要登录的页面,当我检查cookies或session时,我可以看到API成功添加了它们。但是当我尝试获取 User.Identity.Name 时,它​​始终为 null,并且 isAuthenticated 始终等于 false。这就像 app.UseAuthentication() 不读取 cookie 或 session 。

我的启动.cs

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.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AnisubsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AnisubsDBConnection")));

services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AnisubsDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
services.AddControllersWithViews();


services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = "353222242210621";
facebookOptions.AppSecret = "XXXX";
facebookOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = "1093176997632-ug4j2h7m9f1nl9rg8nucecpf9np0isro.apps.googleusercontent.com";
googleOptions.ClientSecret = "XXXX";
googleOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
})
.AddTwitter(twitterOptions =>
{
twitterOptions.ConsumerKey = "lZ2ugpLuKpDOlmdSuyw1hVJLU";
twitterOptions.ConsumerSecret = "XXXX";
twitterOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
})
.AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = "22f501ab-70c9-4054-8f33-2b35af3a64ba";
microsoftOptions.ClientSecret = "XXXX";
microsoftOptions.CallbackPath = new Microsoft.AspNetCore.Http.PathString("/Login/Callback");
})
.AddCookie();
}

// 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.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}

登录 Controller .cs
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel loginViewModel)
{
if (ModelState.IsValid)
{
var user = await userManager.FindByEmailAsync(loginViewModel.Email);
if (user != null)
{
var result = await signInManager.PasswordSignInAsync(user.UserName, loginViewModel.Password, loginViewModel.RememberMe, false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}
return View(loginViewModel);
}

重定向到主页后的 session
enter image description here

Razor 页面共享 _navbarlayout.cshtml(_layout.cshtml 内的部分 View )
@using Microsoft.AspNetCore.Identity

@inject SignInManager<IdentityUser> signInManager;


<nav class="navbar fixed-top">


<a class="navbar-logo" href="Dashboard.Default.html">
<span class="logo d-none d-xs-block"></span>
<span class="logo-mobile d-block d-xs-none"></span>
</a>

<div class="navbar-right">
<div class="header-icons d-inline-block align-middle">
<div class="user d-inline-block">
<button class="btn btn-empty p-0" type="button" data-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">
@if (signInManager.IsSignedIn(User))
{
<span class="name">@User.Identity.Name</span>
}
else
{
<span class="name">Not Registered</span>
}

<span>
<img alt="Profile Picture" src="img/profile-pic-l.jpg" />
</span>
</button>

<div class="dropdown-menu dropdown-menu-right mt-3">
@if (signInManager.IsSignedIn(User))
{
<a class="dropdown-item" href="#">Account</a>
<a class="dropdown-item" href="#">Features</a>
<a class="dropdown-item" href="#">History</a>
<a class="dropdown-item" href="#">Support</a>
<a class="dropdown-item" asp-action="logout" asp-controller="account">Sign out</a>
}
else
{
<a class="dropdown-item" asp-action="login" asp-controller="account">Login</a>
<a class="dropdown-item" asp-action="register" asp-controller="account">Register</a>
}
</div>
</div>
</div>
</nav>

从上面的 Razor 代码中,signInManager.IsSignedIn(User) 始终为 false,User.identity 声称始终计数为零。

更改了如下启动中间件的顺序,问题仍然相同
app.UseStaticFiles();
app.UseHttpsRedirection();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

下面是一个 GIF 图片,显示当 quickwatch 用户
enter image description here

最佳答案

ASP.NET Core Identity 创建一个 cookie(在屏幕截图中显示为 .AspNetCore.Identity.Application ),它在成功调用 PasswordSignInAsync 后设置。 .调用 AddIdentityStartup.ConfigureServices设置它:它注册一个名为 Identity.Application 的身份验证方案并将其设置为应用程序的默认身份验证方案。

现在,考虑到这一点,从问题中获取以下代码:

services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})


如上所述,此调用 AddAuthentication将默认身份验证方案覆盖为 CookieAuthenticationDefaults.AuthenticationScheme .这最终是 PasswordSignInAsync使用 Identity.Application 正确登录用户方案,但应用程序正在使用 Cookies尝试加载当前用户时的方案。自然,这意味着用户永远不会被加载。

在解决方案方面,只需从 AddAuthentication 中删除回调即可。 :
services.AddAuthentication()
.AddFacebook(facebookOptions =>
{
// ...
})
.AddGoogle(googleOptions =>
{
// ...
})
.AddTwitter(twitterOptions =>
{
// ...
})
.AddMicrosoftAccount(microsoftOptions =>
{
// ...
});

我还删除了对 AddCookie 的调用,这是多余的。这添加了 Cookies身份验证方案,但您的应用程序正在使用 Identity.Application ,如前所述。

关于c# - User.Identity.Name 在 PasswordSignInAsync MVC .Net Core 3.0 之后始终为 null 并声明计数为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59335028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com