具有令牌认证的Web API中的两要素认证

时间:2019-04-05 15:11:49

标签: jwt asp.net-web-api2 two-factor-authentication

我正在构建授权API,并且想使用令牌身份验证和两因素身份验证。我可以发送带有安全代码的SMS,但是我不确定如何处理GrantResourceOwnerCredentials中的逻辑。我最初设置了令牌身份验证,然后添加了两因素逻辑。问题是直到用户验证代码后,我才希望将其设置为已验证用户。如何修改GrantResourceOwnerCredentials(和AccountController VerifyCode操作?)来做到这一点?还是我完全不合时宜?

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new [] {"*"});

        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = context.OwinContext.Get<ApplicationDbContext>().Users
            .FirstOrDefault(u => u.UserName == context.UserName);
        if (!userManager.CheckPassword(user, context.Password))
        {
            context.SetError("invalid_grant", "The user name or password is incorrect");
            context.Rejected();
            return Task.FromResult<object>(null);
        }

        var twoFactorEnabled = userManager.GetTwoFactorEnabled(user.Id);
        if (twoFactorEnabled)
        {
            var code = userManager.GenerateTwoFactorToken(user.Id, "PhoneCode");
            var notificationResult = userManager.NotifyTwoFactorToken(user.Id, "PhoneCode", code);
            if (!notificationResult.Succeeded)
            {
                context.SetError("invalid_grant", "Two factor notification failed");
                context.Rejected();
                return Task.FromResult<object>(null);
            }
        }

        var ticket = new AuthenticationTicket(SetClaimsIdentity(context, user), new AuthenticationProperties());
        context.Validated(ticket);

        return Task.FromResult<object>(null);
    }

0 个答案:

没有答案