简体   繁体   English

确认电子邮件时 ASP.NET Core 令牌无效但令牌似乎有效

[英]ASP.NET Core invalid token when confirming email but token seems valid

I have ASP.NET Core web api project and I need to confirm email.我有 ASP.NET Core web api 项目,我需要确认电子邮件。 Everything is working fine and generated token and token received in ConfirmEmail() method are equal.一切正常,生成的令牌和在 ConfirmEmail() 方法中收到的令牌是相等的。 Token seems valid but result gives invalid token:令牌似乎有效,但结果给出无效令牌:

    var result = await userManager.ConfirmEmailAsync(user, code);

Generating token:生成令牌:

        var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
        var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
        var email = user.Email;
        await emailSender.SendEmailConfirmationAsync(email, callbackUrl);

EmailConfirmationLink() and SendEmailConfirmationAsync() methods: EmailConfirmationLink() 和 SendEmailConfirmationAsync() 方法:

    public static string EmailConfirmationLink(this IUrlHelper urlHelper, string userId, string code, string scheme)
    {
        var result = urlHelper.Action(
            action: "ConfirmEmail",
            controller: "ApplicationUsers",
            values: new { userId, code },
            protocol: scheme);

        return result;
    }

    public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, string email, string link)
    {
        return emailSender.SendEmailAsync(email, "Confirm your email",
            $"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(link)}'>Confirm email</a>");
    }

ConfirmEmail() method: ConfirmEmail() 方法:

    public async Task<IActionResult> ConfirmEmail(string userId, string code)
    {
            if (userId == null || code == null)
            {
                // ....
            }
            var user = await userManager.FindByIdAsync(userId);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{userId}'.");
            }               
            var result = await userManager.ConfirmEmailAsync(user, code);

I was also having this issue and i tried the answers above and till got no luck.我也遇到了这个问题,我尝试了上面的答案,直到没有运气。 Setting the isHtml parameter to true in the SendAsync method fixed my problem.在 SendAsync 方法中将 isHtml 参数设置为 true 解决了我的问题。

_emailService.SendAsync(vm.Email, "Click the link below to validate.", $"<a href=\"{link}\">Validate email</a>",true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM