Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate User Two Factor Security Code from Microsoft.AspNetCore.Identity
using System.Threading.Tasks;
using BrunoMartinsPro.Data.Models;
namespace BrunoMartinsPro.Utils.MicrosoftAspNetCoreIdentity
{
public interface IMicrosoftAspNetCoreIdentityUtils
{
Task<string> GenerateUserTwoFactorSecurityCode(ApplicationUser user, string securityType);
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using BrunoMartinsPro.Data.Models;
namespace BrunoMartinsPro.Utils.MicrosoftAspNetCoreIdentity
{
public class MicrosoftAspNetCoreIdentityUtils : IMicrosoftAspNetCoreIdentityUtils
{
private readonly UserManager<ApplicationUser> _userManager;
/// <summary>
/// Register DI
/// </summary>
/// <param name="userManager"></param>
public MicrosoftAspNetCoreIdentityUtils(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
/// <summary>
/// UpdateSecurityStampAsync signs out all sessions and creates a new security stamp, this in turn generates a new code
/// </summary>
/// <param name="user"></param>
/// <param name="securityType"></param>
/// <returns></returns>
public async Task<string> GenerateUserTwoFactorSecurityCode(ApplicationUser user, string securityType)
{
//Sign out all sessions, generate a new security stamp to generate phone code
await _userManager.UpdateSecurityStampAsync(user);
//Get generated phone code
var codePhoneConfirmation = await _userManager.GenerateTwoFactorTokenAsync(user, securityType);
//Return generated phone code
return codePhoneConfirmation;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment