OTP in dotnet identity
From Logic Wiki
Contents
Data
TwoFactorenabled and TwoFactorDefined fields of the user should be false in AspNetUser Table
Creating Authenticator App Entry
Code
public async Task<string> GetAuthenticator(string username)
{
var user = await userManager.FindByEmailAsync(username);
var unformattedKey = await userManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(unformattedKey))
{
await userManager.ResetAuthenticatorKeyAsync(user);
unformattedKey = await userManager.GetAuthenticatorKeyAsync(user);
}
var AuthenticatorUri = GenerateQrCodeUri(user.UserName, unformattedKey);
return AuthenticatorUri;
}
private string GenerateQrCodeUri(string email, string unformattedKey)
{
var authenticatorTitle = settingManager.GetSetting("AuthenticatorTitle");
var AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
return string.Format(
AuthenticatorUriFormat,
_urlEncoder.Encode(authenticatorTitle),
_urlEncoder.Encode(email),
unformattedKey);
}
it gives you the link
otpauth://totp/Logicmade:ali.iybar@gmail.com?secret=CKNZWXGDHTQUZYU37S6XYYTOQJAUX6ZE&issuer=Logicmade&digits=6
The link in details
Logicmade: it is an open text. Name of your site
ali.iybar@gmail.com : it's the user email in identity user
secret : it's the code we get from userManager.GetAuthenticatorKeyAsync
Logicmade (issuer) : issuer :)
digits : it's how many digits you need to authenticate
Creating a QR Code
use any QR code generator and put the link in it.
Add link to Authenticator app
Open the authenticator app and click + to add a new one. Select QR code and read the QR code you created above
Validating
just stub the code below to Sign in wherever needed.
var user = await userManager.FindByEmailAsync(userSignIn.Email);
....
var otpResult = await userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, userSignIn.OTP);
if (!otpResult)
{
throw new Exception("OTP mismatch");
}
userSignIn.OTP : this is the 6 digit code created in the app