У меня есть проект идентификации ядра. net, в котором у меня проблемы с аутентификацией.
Login.cs html .cs
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
if (ModelState.IsValid)
{
// Modified base identity to allow login by email or username
var user = await _userManager.FindByNameAsync(Input.Username);
if (user == null)
{
user = await _userManager.FindByEmailAsync(Input.Username);
}
var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
return LocalRedirect(returnUrl);
}
if (result.IsNotAllowed)
{
return RedirectToPage("./ConfirmEmail");
}
if (result.IsLockedOut)
{
return RedirectToPage("./Lockout");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
return Page();
}
Со страницы Login
эта строка кода: var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);
возвращает result.Succeeded
, но из представления страницы этот код всегда возвращает false
:
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
}
Когда я перебираю код для метода IsSignedIn
из приведенного ниже кода, происходит сбой, поскольку principal.Identities.AuthenticationType
всегда null
.
SignInManager.cs
public override bool IsSignedIn(ClaimsPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
return principal?.Identities != null &&
principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme);
}
Сначала я подумал, что это проблема конфигурации в Startup.cs
, но я не Вы уверены, что или где установлен AuthenticationType
?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDbConnection>((sp) => new SqlConnection(Configuration.GetConnectionString("Database")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath ="/Account/AccessDenied";
options.Cookie.Name = "MyApp";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.LoginPath = "/Account/Login";
// ReturnUrlParameter requires
//using Microsoft.AspNetCore.Authentication.Cookies;
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
options.SlidingExpiration = true;
});
services.AddMemoryCache();
services.AddMvc(options => { options.EnableEndpointRouting = false; });
services.AddRazorPages();
services.AddSession();
services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
services.AddTransient<IRoleStore<ApplicationRole>, CustomRoleStore>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddSerilog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}