我正在从事一个金融项目,该项目需要高度安全的用户登录。在这个项目中,我在创建项目时没有使用默认身份验证,我手动实现了它。现在,当用户登录他的面板,所有功能运行没有错误,SignInManager签署他正常,但当我想重定向到他的仪表板与[Authorize]
注释再次他重定向到登录页面。有什么问题吗?它是关于手动实现身份?
下面是我的登录代码:
public async Task<IActionResult> Login(LoginViewModel model)
{
try
{
string targetUrl = "";
if (ModelState.IsValid)
{
var user = await userManager.FindByEmailAsync(model.Email);
if (user == null)
{
_logger.Log(LogLevel.Warning, $"User ({model.Email}) tried to login with went wrong info");
return Json(new { result = "error", target = "login", message = "Wrong Email or Password. Please fill the form with valid information" });
}
var loginAttempt = await signInManager.CheckPasswordSignInAsync(user, model.Password, true);
if (loginAttempt.Succeeded)
{
if (user.TwoFactorEnabled)
{
TempData["loginInfo"] = JsonConvert.SerializeObject(user);
TempData.Keep("loginInfo");
targetUrl = "/Account/TwoStepVerification";
}
else
{
await signInManager.SignInAsync(user, false);
var login = new UserLogin
{
IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
TimeStamp = DateTime.Now.Ticks,
UserId = user.Id
};
DbContext.UserLogins.Add(login);
await DbContext.SaveChangesAsync();
targetUrl = model.ReturnUrl ?? "/Account/Dashboard";
}
return Json(new { result = "success", target = "login", url = targetUrl, message = "You have successfully logged in. Wait some seconds..." });
}
return Json(new { result = "error", target = "login", message = "Wrong Email or Password." });
}
return Json(new { result = "error", target = "register", message = "Something went wrong. Bad input" });
}
catch (Exception exc)
{
_logger.Log(LogLevel.Critical, $"Failed Login : {exc.Message}");
return Json(new { result = "error", target = "register", message = "Something went wrong. Please try again after some minutes" });
}
}
这里有两步验证:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> TwoStepVerification(string code)
{
TempData.Keep("loginInfo");
if (code == null)
{
return Json(new { result = "error", target = "2faverified", message = "Please 2fa code" });
}
var user = JsonConvert.DeserializeObject<ApplicationUser>(TempData["loginInfo"].ToString());
GoogleAuthenticatorHelper google2FA = new(user.Id, user.Email);
if (google2FA.IsUserInputValid(code))
{
await signInManager.SignInAsync(user, false);
var login = new UserLogin
{
IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
TimeStamp = DateTime.Now.Ticks,
UserId = user.Id
};
DbContext.UserLogins.Add(login);
await DbContext.SaveChangesAsync();
return Json(new { result = "success", url = "/Account/Dashboard", target = "2faverified", message = "You have successfully validate 2fa. Please wait..." });
}
return Json(new { result = "error", target = "2faverified", message = "Validation failed." });
}
这里是Startup.cs中的ConfigureService
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = false;
}).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.LoginPath = new PathString("/Account/Login");
options.AccessDeniedPath = new PathString("/Account/AccessDenied");
options.SlidingExpiration = true;
});
services.Configure<DataProtectionTokenProviderOptions>(options =>
{
options.TokenLifespan = TimeSpan.FromDays(1);
});
services.AddControllersWithViews();
}
对不起,我忘了在Startup.cs
的Configure
函数中添加app.UseAuthentication();
代码