使用身份在 .net 核心应用程序中强制使用 2FA
Enforce use of 2FA in .net core application using identity
我已经使用 here 中的指南在我的 .net 核心 mvc 应用程序中设置了 2 因素身份验证
这一切工作正常,但它依赖于用户进入他们的帐户并设置 2FA。有什么办法可以强制用户这样做,以便所有用户都必须使用 2FA?
一种方法是在登录期间检查用户是否通过以下方式设置了 2FA:
var user = await _userManager.FindByEmailAsync(Input.Email);
var twoFactorEnabled = user.TwoFactorEnabled;
如果为 false,则可以重定向用户以配置 2FA 页面(./Manage/TwoFactorAuthentication
),在用户设置 2FA 并启用 2FA 后,TwoFactorEnabled
in AspNetUsers
table 将是 True
然后在登录过程中,如果当前用户的 TwoFactorEnabled
值为真,身份将自动将用户重定向到 ./LoginWith2fa
页面以进行 2FA 登录。
我来晚了。但是实现它的方法是制作一个自定义控制器并覆盖 OnActionExecuting 方法。
public class CustomController : Controller
{
public readonly DataContext _db;
public CustomController(DataContext context)
{
_db = context;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (User.Identity.IsAuthenticated)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
UserModel user = _db.UserModel.Find(userId);
if (user.TwoFactorEnabled==false && ControllerContext.ActionDescriptor.ActionName != "TwoFactor")
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "TwoFactor" }));
return;
}
}
base.OnActionExecuting(filterContext);
}
}
我已经使用 here 中的指南在我的 .net 核心 mvc 应用程序中设置了 2 因素身份验证 这一切工作正常,但它依赖于用户进入他们的帐户并设置 2FA。有什么办法可以强制用户这样做,以便所有用户都必须使用 2FA?
一种方法是在登录期间检查用户是否通过以下方式设置了 2FA:
var user = await _userManager.FindByEmailAsync(Input.Email);
var twoFactorEnabled = user.TwoFactorEnabled;
如果为 false,则可以重定向用户以配置 2FA 页面(./Manage/TwoFactorAuthentication
),在用户设置 2FA 并启用 2FA 后,TwoFactorEnabled
in AspNetUsers
table 将是 True
然后在登录过程中,如果当前用户的 TwoFactorEnabled
值为真,身份将自动将用户重定向到 ./LoginWith2fa
页面以进行 2FA 登录。
我来晚了。但是实现它的方法是制作一个自定义控制器并覆盖 OnActionExecuting 方法。
public class CustomController : Controller
{
public readonly DataContext _db;
public CustomController(DataContext context)
{
_db = context;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (User.Identity.IsAuthenticated)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
UserModel user = _db.UserModel.Find(userId);
if (user.TwoFactorEnabled==false && ControllerContext.ActionDescriptor.ActionName != "TwoFactor")
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "TwoFactor" }));
return;
}
}
base.OnActionExecuting(filterContext);
}
}