在將這個問題標記為重復之前,請大家理解我的問題。我創建了一個帶有“個人身份驗證”的 Asp.net 核心 Web 應用程式(Razor 頁面)。然后我添加了身份腳手架并運行應用程式,它要求“應用遷移”我做到了。然后我注冊了一個用戶并使用該用戶登錄。一切都那么順利。
登錄成功后,應用登陸Index頁面。
但是當我用[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();
}
}
有人可以幫我嗎?
uj5u.com熱心網友回復:
不知道確切原因,但更改默認身份驗證方案對我有用。
在您的 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";
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387477.html
標籤:C# .net-5 asp.net 核心身份 asp.net-core-razor-pages
下一篇:創建可調整大小的Qml對話框
