I would like to add two factor authentication to a login screen. My understanding of the process is the following:

  1. Generate a QR Code
  2. Scan this Code with Google Authenticator app
  3. Use a library to check if the Google authenticator code matches the code the user has entered.

I would like to use PHP for the authentication. I am a little bit unsure what might be the best code for generating the QR code. As it should be unique, I thought about the hashed password from the user database. Because if the attacker has access to the server, there might be no way to protect the qr code generation. Or is there a way to protect the key?

A random string would not work because it would change each time and the user would need to scan the code each time again.

What is a proper way to create relatively secure two factor authentication and what is the common key to generate the qr code? Where should the key for the qr code be stored? And what is a recommended library for it using PHP?

1 Answer 1


The secret is a shared secret, generated by you, and shared with the user. Both parties has to store the secret.

OTP is not meant to stop an attacker that has access to the server. It's meant to stop attackers who can access the password (think: password leaks) and limit impact of phishing.

You should generate a secret value server side, and store this in your database. It should not be derived from the password, as that makes it non-secret to an attacker who knows the password - and also would mean that the user has to update their 2FA app whenever they want to change password.

  • Great explanation. Could you tell me what is the best way to handle the loss of the secret on the client side? E.g. deleting the Google Authenticator app. The use case is to secret the admin area. I can definitely generate a new key manually, but what would be the proper way to do it automatically? My idea would be to use an e-mail address to reset it. Feb 10 at 8:42
  • You should use a method that you deem secure enough. If it's trivial to reset the 2FA, it's not worth anything.
    – vidarlo
    Feb 10 at 9:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .