asp.net-core-mvcasp.net-core-webapi.net-8.0asp.net-core-identity

ASP.NET Core Identity: "Invalid token" when generating and confirming email in different applications


I am working on a project using ASP.NET Core Identity that involves two separate applications: an API and an MVC app.

My scenario is as follows: I generate an email confirmation token using UserManager.GenerateEmailConfirmationTokenAsync in the API.

Then, I attempt to confirm the email in the MVC app by calling _userManager.ChangeEmailAsync. However, this results in an "Invalid token" error.

If the token is both generated and confirmed within the same application, whether in the API or the MVC app, everything works correctly. The issue occurs only when the token is generated in one application and used in another.

Both applications share the same ASP.NET Core Identity configuration, including the token generation algorithm and keys, and the library versions are synchronized.

Why is the token created in one application considered invalid in another, and how can this scenario be resolved? Any advice or solutions would be greatly appreciated.


Solution

  • This is excepted, the generated token is based on the user SecurityStamp and the hostserver IP address and other thing.

    You could check below source codes:

    How it validates the token:

    https://github.com/dotnet/aspnetcore/blob/main/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs#L59

    How it get the SecurityStamp:

    https://github.com/dotnet/aspnetcore/blob/091e35e3ae113e79b8d973ebdcd96404ba4f9758/src/Identity/Extensions.Core/src/UserManager.cs#L819

    This ScurityStamp noramlly is stored inside the database per user, you need make sure you have the same database fistly.

    Then according to this source codes, you could find when generate and validate the token, it will also check the host IP address. I suggest you could make sure both two application are inside the same host and use same security configuration like data protection keys.