在 ASP.NET Core Identity(独立)中,您如何实施 2FA? [英] In ASP.NET Core Identity (standalone), how do you enforce 2FA?
问题描述
我在 Razor Pages 项目中使用 ASP.NET Core Identity.如果经过身份验证的用户未满足特定政策(例如未启用 2FA),您如何重定向到特定页面(例如启用 2FA 页面)?
I'm using ASP.NET Core Identity on a Razor Pages project. If a specific policy is not met (e.g. 2FA is not enabled) for an authenticated user, how do you redirect to a specific page (e.g. Enable 2FA page)?
我想避免必须检查每个 OnGet 中的声明,例如:
I'd like to avoid having to check against a claim in every OnGet, like:
public IActionResult OnGet()
{
var claimTwoFactorEnabled = User.Claims.FirstOrDefault(t => t.Type == "TwoFactorEnabled");
if (claimTwoFactorEnabled != null && "true".Equals(claimTwoFactorEnabled.Value))
{
// You logged in with MFA, do the admin stuff
}
else
{
return Redirect("/Identity/Account/Manage/TwoFactorAuthentication");
}
return Page();
}
我确实找到了这个答案,但它似乎需要 OpenIdConnect.我使用的是独立的 Identity.
I did find this answer but it seems to require OpenIdConnect. I'm using standalone Identity.
推荐答案
I started with AdditionalUserClaimsPrincipalFactory
from https://damienbod.com/2020/01/03/requiring-mfa-for-admin-pages-in-an-asp-net-core-identity-application/:
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IdentityStandaloneMfa
{
public class AdditionalUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser, IdentityRole>
{
public AdditionalUserClaimsPrincipalFactory(
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, roleManager, optionsAccessor)
{
}
public async override Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
{
var principal = await base.CreateAsync(user);
var identity = (ClaimsIdentity)principal.Identity;
var claims = new List<Claim>();
if (user.TwoFactorEnabled)
{
claims.Add(new Claim("TwoFactorEnabled", "true"));
}
else
{
claims.Add(new Claim("TwoFactorEnabled", "false")); ;
}
identity.AddClaims(claims);
return principal;
}
}
}
另外,在 Startup 的 ConfigureServices 中,添加:
Plus, in ConfigureServices in Startup, added:
services.AddAuthorization(options =>
{
options.AddPolicy("TwoFactorEnabled",
x => x.RequireClaim("TwoFactorEnabled", "true")
);
// you can also combine with a role based policy
options.AddPolicy("RequireAdminRole",
policy => policy.RequireRole("Admin", "SuperAdmin").RequireClaim("TwoFactorEnabled", "true"));
});
然后不是将 if
逻辑添加到每个 OnGet
方法中,而是添加[Authorize(Policy = "TwoFactorEnabled")]
在代码隐藏文件的顶部,例如:
Then instead of adding the if
logic to each OnGet
method, I'm adding
[Authorize(Policy = "TwoFactorEnabled")]
at the top of the code behind file, like:
[Authorize(Policy = "TwoFactorEnabled")]
public class DetailModel : PageModel
{
这篇关于在 ASP.NET Core Identity(独立)中,您如何实施 2FA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!