为了确保 ASP.Net Identity 登录功能在传输敏感信息时安全可靠,我们需要强制要求使用 Https 协议进行重定向。下面是一种简单的
app.Use(async (context, next) => { if (context.Request.IsHttps || context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps) { await next(); } else { var withHttps = context.Request.Scheme; withHttps = "https://" + withHttps.Substring("http://".Length); var newUrl = withHttps + context.Request.Path + context.Request.QueryString; context.Response.Redirect(newUrl); } });
该代码段首先检查请求是否已经使用了 Https 协议,或者通过“X-Forwarded-Proto”请求头信息来检查协议。如果是,则调用 next 方法来执行应用程序中的下一个中间件。
如果请求不使用 Https 协议,则使用 Request.Scheme 获取原始协议(可能是“http”),并将其替换为“https”。然后从 Request.Path 和 Request.QueryString 构建重定向 URL,并使用 Response.Redirect 方法将请求重定向到新位置。
[AllowAnonymous] public async Task OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
// 省略其他代码
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });