【问题标题】:Email confirmation on identity using two projects (one to send the token and one to confirm)使用两个项目的电子邮件确认身份(一个用于发送令牌,一个用于确认)
【发布时间】:2021-02-04 23:47:10
【问题描述】:

我在 ASP.NET core 3.1 应用程序中使用身份电子邮件确认时遇到问题。

我有一个接收注册用户请求的 Web API 项目。这样,我生成一个用于确认的令牌并将该令牌发送到用户的电子邮件。但是,电子邮件中为他执行确认而配置的 URL 来自 Web 项目,当我确认用户时,应用程序会显示错误消息,指出即使对两个应用程序使用相同的数据库,令牌也是无效的 - 在此外,我还为这些应用程序使用了一个共享身份项目。

发送的token是正确的,因为API发送的和Web收到的比较是同一个token,但是调用方法确认email时,返回的是token的消息无效。

生成令牌以确认(API 项目)

var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = $"https://localhost:5001/Identity/Account/ConfirmEmail?userId={user.Id}&code={code}";
var confirmationUrl = HtmlEncoder.Default.Encode(callbackUrl);

令牌确认(网络项目)

public async Task<IActionResult> OnGetAsync(string userId, string code)
{
    if (userId == null || code == null)
    {
        return RedirectToPage("/Index");
    }

    var user = await _userManager.FindByIdAsync(userId);
    if (user == null)
    {
        return NotFound();
    }

    code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
    var result = await _userManager.ConfirmEmailAsync(user, code);
    StatusMessage = result.Succeeded ? "Email confirmed" : "Error to confirm email.";
    return Page();
}

【问题讨论】:

    标签: asp.net-core asp.net-identity identity


    【解决方案1】:

    据我所知,用户管理器 ConfirmEmailAsync 将根据其数据保护提供商解密令牌。

    通常,不同的项目会使用不同的数据保护提供商。如果你的两个应用程序都是 asp.net 核心应用程序。

    我建议您可以尝试使用以下代码连接到同一个外部商店并使用相同的应用程序名称。外部存储可以是网络位置、映射驱动器、A​​zure Key Vault 等。

    如果您处于开发模式,则可以将它们设置为相同的路径。

    在startup.cs配置服务方法中添加如下代码:

     //Make sure the app name and path is same.
    services.AddDataProtection()
        .SetApplicationName("shared app name")
        .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"));
    

    更多细节,你可以参考这个article

    【讨论】:

    • 这个答案涵盖了为什么这不起作用,但我建议不要使用文件系统将它们添加到像 redis 这样的分布式缓存中。我认为您希望它们作为单独项目的原因是为了获得更大的灵活性。我会四处走动并尝试设置它,看看IDistributedCache for .Net Core,如果缓存不够,则将其存储到数据库中(但我假设您需要高速来进行这种验证场景)跨度>
    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 2018-03-19
    • 2015-02-16
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2016-10-04
    相关资源
    最近更新 更多