登录代码似乎有效,因为PasswordSignInAsync
返回Succeed
,但当我使用User.GetUserName()
获取下一个请求的用户信息时,它总是归还给我null
。此外,User.IsSignedIn()
也会返回false
。
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
// this code executed and the redirection works fine
Logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
Logger.LogWarning(2, "RequiresTwoFactor");
}
if (result.IsLockedOut)
{
Logger.LogWarning(3, "User account locked out.");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
return View(model);
}
在下一个请求中,我无法获得任何信息。
Logger.LogWarning(User.Identity.Name ?? "User.Identity.Name is null"); // null
Logger.LogWarning(User.GetUserName() ?? "User.GetUserName() is null"); // null
Logger.LogWarning(User.IsSignedIn() ? "User is signed in" : "User is not signed in"); // not signed in
我的Startup.cs
app.UseIdentity();
services.AddIdentity<CustomAccount, CustomRole>(options =>
{
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(24);
})
.AddEntityFrameworkStores<ApplicationDbContext, long>()
.AddDefaultTokenProviders();
注意:我也在同一个应用中使用app.UseJwtBearerAuthentication
,这可能是个问题吗?
答案 0 :(得分:1)
对任何与此问题斗争的人。这是我的工作代码
加载证书
注意:我正在将证书导入Azure并使用指纹值将其加载到我的应用程序中
public X509Certificate2 LoadCertificate()
{
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore
.Certificates
.Find(X509FindType.FindByThumbprint,
"", // Generated by Azure
false);
if (certCollection.Count > 0)
{
var cert = certCollection[0];
return cert;
}
certStore.Dispose();
return null;
}
连接身份服务器
var cert = LoadCertificate();
if (cert == null)
{
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddAspNetIdentity<ApplicationUser>()
.AddConfigurationStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)))
.AddOperationalStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)));
}
else
{
services.AddIdentityServer()
.AddSigningCredential(cert)
.AddAspNetIdentity<ApplicationUser>()
.AddConfigurationStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)))
.AddOperationalStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)));
}
希望它有所帮助。