[英].Net Core 5 Razor pages Cookie Authentication redirects to the login page after successful login
在将此问题标记为重复之前,请大家理解我的问题。 我创建了一个带有“个人身份验证”的 Asp.net 核心 web 应用程序(Razor 页面)。 然后我添加了身份脚手架并运行了应用程序,它要求“应用迁移”我做到了。 然后我注册了一个用户并使用该用户登录。 一切都那么顺利。
成功登录后,应用程序登陆索引页面。
但是当我用[Authorize]属性标记我的“ Index.cshtml.cs ”页面并在我的 startup.cs 文件中添加 cookie 设置时,问题就发生了。 成功登录后,应用程序开始重定向回登录页面。
预期的行为是它应该重定向到主页,即 Index.cshtml。
我检查了这个 SO 问题和其他问题,但没有任何东西对我有用。
我不明白我哪里出错了。
这是我的startup.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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0);
options.SlidingExpiration = true;
options.Cookie = new CookieBuilder
{
SameSite = SameSiteMode.Strict,
SecurePolicy = CookieSecurePolicy.Always,
IsEssential = true,
HttpOnly = true
};
options.Cookie.Name = "Authentication";
});
services.AddAuthorization();
}
// 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();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/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.MapRazorPages();
});
}
}
登录.cshtml.cs
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
public LoginModel(SignInManager<IdentityUser> signInManager,
ILogger<LoginModel> logger,
UserManager<IdentityUser> userManager)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl ??= Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
有人可以帮我吗?
不知道确切原因,但更改默认身份验证方案对我有用。
在您的 startup.cs 文件中,更改
由此:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0);
options.SlidingExpiration = true;
options.Cookie = new CookieBuilder
{
SameSite = SameSiteMode.Strict,
SecurePolicy = CookieSecurePolicy.Always,
IsEssential = true,
HttpOnly = true
};
options.Cookie.Name = "Authentication";
});
对此:
services.AddAuthentication(IdentityConstants.ApplicationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0);
options.SlidingExpiration = true;
options.Cookie = new CookieBuilder
{
SameSite = SameSiteMode.Strict,
SecurePolicy = CookieSecurePolicy.Always,
IsEssential = true,
HttpOnly = true
};
options.Cookie.Name = "MyCookie";
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.