Search code examples
urlurlencode.net-core-3.1

Invalid activation token - problem with controller?


I have a really weird problem. Everything worked in previous version of .net core, but now in .net core 3.1 it does not.

So the thing is, after a user registers an account, I send him activation e-mail with activation code created like this:

var activationCode = await userMan.GenerateEmailConfirmationTokenAsync(su);

Next I generate a http url which is formed like that:

http://localhost/api/users/activate?userId=1234&code=abc+860/def==

Now, note that userId is a valid GUID and my activation code is just example, because I really get a long one code. But what's important in this code - it has plus sings(+), slashes and ends with double equal sign.

Now I get the email with valid user guid and still VALID activation code. But, when I click this link and my UsersController starts, something bad happens. This is my activation method in UserController (part of code)

[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    [HttpGet("activate")]
    [AllowAnonymous]
    public async Task<IActionResult> ActivateAccount([FromQuery] Guid userId, [FromQuery] string code)
    {
        if (userId == Guid.Empty || string.IsNullOrWhiteSpace(code))
            return BadRequest();
    }
}

And the weird thing is that the code parameter is invalid here. The value is just without plus signs. Instead it has spaces. What's wrong?


Solution

  • You need to URL Encode parameters. Some symbols can get stripped without that. You can read more here about symbols and the procedure.

    Correct URL for you will be:

    http://localhost/api/users/activate?userId=1234&code=abc%2B860%2Fdef%3D%3D
    

    And to generate correct URL, you can use HttpUtility.UrlEncode before giving a URL to someone. Read the link as there are details that could be helpful. That is some common approach to encode URLs.

    And here is some nice article, listing all or majority of approaches to do so, discussing on how to peak one.