saving the Identity token in the Aspnetusertokens table

Marnelle M'BENGUET 20 Reputation points
2023-11-07T11:19:50.1566667+00:00
Hi I created an Asp.net core 6 project and I added the Identity framework for authentication and authorization, I would like to add token management and while doing research I realized that Identity also manages the management of tokens because it generates them at each authentication thanks to the command ".AddDefaultTokenProviders();" in startup.cs but I would like to save these tokens in the database precisely in the Aspnetusertokens table of Identity, so I added a TokenController controller which will help me do it, here is what I have in this controller 

"using Projet.Data;
Microsoft Identity Manager
Microsoft Identity Manager
A family of Microsoft products that manage a user's digital identity using identity synchronization, certificate management, and user provisioning.
624 questions
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
Microsoft Authenticator
Microsoft Authenticator
A Microsoft app for iOS and Android devices that enables authentication with two-factor verification, phone sign-in, and code generation.
5,588 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,216 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,323 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 57,401 Reputation points
    2024-04-19T17:49:47.45+00:00

    the tokens expire. you only need the last created.

    in general they are intended for one time use. generate the token and save. send email, with token on url. the user must click the link before the token expires. if expired they must ask for new email link. only the lastest email link should work.

    this is different from caching access and refresh tokens which you might want if using external oauth server.

    1 person found this answer helpful.

  2. Marnelle M'BENGUET 20 Reputation points
    2023-11-07T11:23:36.1266667+00:00
    using Project.Data;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc;
    using Project.Entities;
    
    namespace Project.Controllers
    {
        public class TokenController : Controller
        {
            private readonly UserManager<IdentityUser> _userManager;
            private readonly ARTFContext _context;
            public TokenController(UserManager<IdentityUser> userManager, ARTFContext context)
            {
                _userManager = userManager;
                _context = context;
            }
            [HttpPost]
            public async Task<IActionResult> GeneratePasswordResetToken(string userId)
            {
                var user = await _userManager.FindByIdAsync(userId);
    
                if (user != null)
                {
                    var token = await _userManager.GeneratePasswordResetTokenAsync(user);
    
                    // Enregistrer le token dans la base de données (table AspNetUserTokens)
                    var userToken = new IdentityUserToken<string>
                    {
                        UserId = user.Id,
                        LoginProvider = "Default",
                        Name = "PasswordResetToken",
                        Value = token
                    };
    
                    _context.UserTokens.Add(userToken);
                    await _context.SaveChangesAsync();
    
                    // Vous pouvez également envoyer le token par e-mail si nécessaire
    
                    return Ok("Token de réinitialisation de mot de passe généré et enregistré avec succès");
                }
                return NotFound(); // Gérer le cas où l'utilisateur n'existe pas
            }
    
            [HttpPost]
            public async Task<IActionResult> GenerateEmailConfirmationToken(string userId)
            {
                var user = await _userManager.FindByIdAsync(userId);
    
                if (user != null)
                {
                    var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
    
                    // Enregistrer le token dans la base de données (table AspNetUserTokens)
                    var userToken = new IdentityUserToken<string>
                    {
                        UserId = user.Id,
                        LoginProvider = "Default",
                        Name = "EmailConfirmationToken",
                        Value = token
                    };
    
                    _context.UserTokens.Add(userToken);
                    await _context.SaveChangesAsync();
    
                    // Vous pouvez également envoyer le token par e-mail si nécessaire
    
                    return Ok("Token de confirmation d'e-mail généré et enregistré avec succès");
                }
    
                return NotFound(); // Gérer le cas où l'utilisateur n'existe pas
            }
        }
    }
    
    
    0 comments No comments

  3. Marnelle M'BENGUET 20 Reputation points
    2023-11-07T11:28:03.9766667+00:00

    but I have no record in the database yet the token is indeed generated because in my browser at the header level I have a token corresponding to my authentication information which is generated, someone can help me understand where the problem is coming from?

    THANKS

    sorry for presenting my problem to you in several sections like that I did it so that it doesn't seem too long otherwise it's the same question


  4. AgaveJoe 1,495 Reputation points
    2023-11-16T16:44:42.5466667+00:00

    Example of saving data to the AspNetUserTokens table.

    public async Task<IActionResult> Index()
    {
        IdentityUser? user = await _userManager.FindByEmailAsync("email@gmail.com");
    
        if (await _userManager.GetAuthenticationTokenAsync(user, "MyLoginProvider", "MyToken") == null)
        {
            IdentityResult result = await _userManager.SetAuthenticationTokenAsync(user, "MyLoginProvider", "MyToken", "123456ASDFGG");
        }
                
        string? token = await _userManager.GetAuthenticationTokenAsync(user, "MyLoginProvider", "MyToken");
    
    
        return Ok(new { token = token });
    }