I’m trying to get 2fa to work on a backend project.
I have a function that created and store the secret:
import { Injectable } from '@nestjs/common';
import { authenticator } from 'otplib';
import { ClientService } from 'src/client/client.service';
@Injectable()
export class TwoFactorAuthService {
constructor(private readonly prisma: ClientService)
public async generateTwoFactorAuthSecret(loggedUserEmail: string) {
const user = await this.prisma.users.findFirst({
where: { email: loggedUserEmail },
});
const secret = authenticator.generateSecret();
const otpAuthUrl = authenticator.keyuri(user.email, 'MyApp', secret);
await this.prisma.users.update({
where: {id: user.id},
data: {2faSecret: secret}
});
return {otpAuthUrl}
}
}
Then with that otpAuthUrl I have the qrcode to read using google authenticator, but the thing is when I use the code provided by the auth APP it doesn’t match.
Here’s the function to verify the code:
async verifyTwoFaCode(code: string, user: Users) {
//code = 6 number token from google auth APP
return authenticator.verify({
token: code,
secret: user.2faSecret,
});
}
The ‘authenticator.verify’ function returns false.
There’s a function that actually gives me the correct code:
const correctCode = authenticator.generate(user.2faSecret); //6 number code
return authenticator.verify({
token: correctCode,
secret: user.2faSecret,
});
If I do this it returns true, which tells me that the code provided by google auth APP is incorrect. How can I get this working properly??