{"id":28717,"date":"2024-04-17T06:01:01","date_gmt":"2024-04-17T05:01:01","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/implementando-autenticacion-de-dos-factores-en-php-una-guia-integral\/"},"modified":"2024-06-03T18:39:18","modified_gmt":"2024-06-03T17:39:18","slug":"implementando-autenticacion-de-dos-factores-en-php-una-guia-integral","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/","title":{"rendered":"Implementing Two-Factor Authentication in PHP: A Comprehensive Guide"},"content":{"rendered":"<p>Web application security is a topic that never goes out of style and with growing cyber threats, it is essential to adopt robust data protection measures. Among the most effective strategies is implementing two-factor authentication (2FA), which adds an additional layer of security by verifying not only what the user knows (their password), but also what the user has (e.g. a Mobile phone). In this text, we will explore how you can implement 2FA in your PHP applications, ensuring greater protection against unauthorized access.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#La_importancia_de_la_Autenticacion_de_Dos_Factores\" >The importance of Two-Factor Authentication<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Comenzando_con_2FA_en_PHP\" >Getting started with 2FA in PHP<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Requisitos_Previos\" >Previous requirements<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Configuracion_de_la_Base_de_Datos\" >Database Configuration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Integracion_de_Google_Authenticator\" >Google Authenticator integration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Generando_QR_para_la_Configuracion\" >Generating QR for Configuration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Validando_el_Codigo_de_2FA\" >Validating the 2FA Code<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/implementing-two-factor-authentication-in-php-a-comprehensive-guide\/#Mejores_Practicas_y_Consideraciones_de_Seguridad\" >Best Practices and Security Considerations<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"La_importancia_de_la_Autenticacion_de_Dos_Factores\"><\/span>The importance of Two-Factor Authentication<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Before we dive into the code and settings, it&#039;s crucial to understand why two-factor authentication is so important. In essence, 2FA acts as a double check that ensures that the person trying to access an account is really who they say they are. If the login credentials are compromised, the attacker will still need the second factor, which is usually physically in the possession of the legitimate user, to gain entry.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Comenzando_con_2FA_en_PHP\"><\/span>Getting started with 2FA in PHP<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Requisitos_Previos\"><\/span>Previous requirements<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Before implementing 2FA, make sure your PHP server is configured correctly and that your application already has a basic authentication system (username and password). For the practical example in this article, we will use &quot;PHP&quot;, &quot;MySQL&quot; for data management and &quot;Google Authenticator&quot; as the app to generate the authentication token.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Configuracion_de_la_Base_de_Datos\"><\/span>Database Configuration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>First, you need to prepare your database to store 2FA-related information. This generally includes a secret associated with each user that will be used to generate the single-use tokens.<\/p>\n<pre><code class=\"&quot;language-sql&quot;\">ALTER TABLE `users` ADD `secret_2fa` VARCHAR(255) NULL AFTER `password`;<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Integracion_de_Google_Authenticator\"><\/span>Google Authenticator integration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Google Authenticator generates time-limited codes based on the TOTP (Time-Based One-Time Password) standard. To implement this functionality in PHP, we can use the PHP library <code>sonata-project\/google-authenticator<\/code>.<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">composer require sonata-project\/google-authenticator<\/code><\/pre>\n<p>After installing the library, you can generate a new &quot;secret&quot; for each user when they activate 2FA and store it in the database.<\/p>\n<pre><code class=\"&quot;language-php&quot;\">use SonataGoogleAuthenticatorGoogleAuthenticator; $g = new GoogleAuthenticator(); 1TP4YourUser_id = getUserId(); \/\/ Make sure you implement this function $secret = $g-&gt;generateSecret(); saveSecretInDatabase(1TP4YourUser_id, $secret);<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Generando_QR_para_la_Configuracion\"><\/span>Generating QR for Configuration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To make it easier to set up 2FA in apps like Google Authenticator, it&#039;s helpful to generate a QR code that users can scan. We will use the &quot;Bacon\/BaconQrCode&quot; library to generate this QR code.<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">composer require bacon\/bacon-qr-code<\/code><\/pre>\n<p>Generate and display QR code:<\/p>\n<pre><code class=\"&quot;language-php&quot;\">use BaconQrCodeWriter; use BaconQrCodeRendererImagePng; $renderer = new Png(); $writer = new Writer($renderer); $url = $g-&amp;gt;getURL(&amp;#039;NelkoDev&amp;#039;, &amp;#039;nelkodev.com&amp;#039;, $secret); echo &amp;#039;&lt;img src=&quot;&#039; . $writer-&gt;writeString($url) . &#039;&quot; \/&gt;&#039;;<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Validando_el_Codigo_de_2FA\"><\/span>Validating the 2FA Code<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Every time the user logs in, after validating their username and password, you must verify the 2FA code:<\/p>\n<pre><code class=\"&quot;language-php&quot;\">$2FACode = getUserCode(); \/\/ Implement this capture if ($g-&gt;checkCode($secret, $codigo2FA)) { \/\/ The code is correct, allow access } else { \/\/ Incorrect code, deny access }<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Mejores_Practicas_y_Consideraciones_de_Seguridad\"><\/span>Best Practices and Security Considerations<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When implementing 2FA, consider the following best practices to ensure the solution is both secure and user-friendly:<\/p>\n<ul>\n<li><strong>Inform your users<\/strong>: Make sure users understand what 2FA is and why it is important.<\/li>\n<li><strong>Account recovery<\/strong>: Implement a secure method so that users can regain access to their accounts if they lose the device used for 2FA.<\/li>\n<li><strong>Audit and records<\/strong>: Keep records of access attempts and review them regularly.<\/li>\n<\/ul>\n<p>For more details and advice on specific implementations and security in web applications, I invite you to visit my blog at <a href=\"https:\/\/nelkodev.com\/en\/\">nelkodev.com<\/a>. If you have questions or need assistance with your implementation, please feel free to contact me via <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">my contact page<\/a>.<\/p>\n<p>Implementing two-factor authentication is an essential step towards a more secure application. Although it may seem complex at first, the additional effort is minimal compared to the increased security it provides.<\/p>","protected":false},"excerpt":{"rendered":"<p>Web application security is a topic that never goes out of style and with increasing cyber threats, it is essential to adopt robust data protection measures. Among the most effective strategies is the implementation of two-factor authentication (2FA), which adds an additional layer of security by verifying not only what is happening but also what is [\u2026]<\/p>","protected":false},"author":1,"featured_media":28718,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,2206,1907],"tags":[467,205,232,1905,358,929,1906,15,1008,18,37],"class_list":["post-28717","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-php","category-pruebas-de-seguridad","tag-autenticacion","tag-blog","tag-dos","tag-factores","tag-guia","tag-implementando","tag-integral","tag-php","tag-pruebas","tag-seguridad","tag-una"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28717","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28717"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28717\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28718"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}