Skip to content

Instantly share code, notes, and snippets.

@brunomartinspro
Last active June 11, 2018 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunomartinspro/18e310d98448fee974db240775fff735 to your computer and use it in GitHub Desktop.
Save brunomartinspro/18e310d98448fee974db240775fff735 to your computer and use it in GitHub Desktop.
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