.net 身份自定义身份验证

.net identity custom authentication

我有一个网络API,它被网络应用程序和移动应用程序使用。目前它使用用户名和密码登录的标准方法。为了简单起见,我们需要通过短信向用户发送一个六位数的代码;此代码与 phone 号码相结合将授予他们访问 API 的权限。

我的问题: 是否可以生成一个六位数的号码并让用户使用此代码和他们的 phone 号码的组合登录?

我正在研究将它添加到请求 headers 中然后在身份验证提供程序中处理它的可能性,但我不确定是否有我应该遵循的最佳实践。安全当然非常重要。

我可以只检查提供程序中的 headers,然后让代码相应地执行操作。我已经搜索了其他示例,但没有找到任何内容,因此这更多是一个指导和最佳方法的问题。该代码将有一天的有效期,并在散列后存储在数据库中。

再次强调,如有任何建议,我们将不胜感激。

您将需要 Set up SMS for Two-factor authentication 使用 ASP.NET 身份并创建一个 class 实现接口 IIdentityMessageService

public class SmsService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Send SMS implementation using SMS provider 
    }
}

然后Enable two-factor authentication让用户强制输入生成六位数字以完成登录过程。

所以我的解决方案是使用自定义授权类型。在您的 OAuthProvider 中,您可以覆盖函数 GrantCustomExtension。你可以在下面看到我是如何处理的。

public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
    {
        ApplicationUser currentUser = null;
        try
        {
            //custom grant_type
            if (context.GrantType != "sms")
            {
                context.SetError("invalid_grant", "unsupported grant_type");
                return;
            }

            var accessCode = context.Parameters.Get("access_code");
            var phoneNumber = context.Parameters.Get("phone_number");

            if (string.IsNullOrEmpty(accessCode))
            {
                context.SetError("invalid_grant", "Pin Code is required");
                return;
            }

            if (string.IsNullOrEmpty(phoneNumber))
            {
                context.SetError("invalid_grant", "Phone number is required");
                return;
            }

            // Do your authentication logic here.
        }
        catch (Exception ex)
        {
            context.SetError("invalid_grant", "Something went wrong. Please contact tech support.");
        }
    }

我是在这个问题的帮助下走到这一步的。

您可以使用此方法实现您自己的授权类型和授权逻辑。对于我自己,我有一个四位数的代码散列并存储在数据库中。当用户使用授权类型 sms 登录时,我将访问代码与数据库中的值进行比较,然后采取相应的行动。至于短信方面和发送令牌,我使用 AWS 简单通知服务。由于代码和短信是通过单击按钮发送的,因此实施起来很简单。希望这有帮助。