Laravel Google Authentication Kurulumu
Laravel Projemize Google Authentication ekleyerek projemizde 2 adımlı doğrulamayı aktifleştiriyoruz. Bu sayede projemize 1 güvenlik adımı daha ekleyerek projemizi daha güvenli hale getiriyoruz.
Projeye geçmeden önce GitHub'tan kodları inceleyebilir ve başlamadan önce bilgi sahibi olabilirsiniz.
ADIM 1 : Gerekli Paketleri Yüklüyoruz.
composer require pragmarx/google2fa-laravel
Projemiz 7.x ve üzeri olduğu için publish komutunu çalıştırmamıza gerek yok. Laravel bizim için bunları otomatik olarak gerçekleştirecek.
ADIM 2 : Model ve Controller Paketlerimizi Yüklüyoruz.
php artisan make:model GirisAuthentication -m -c
Database\Migration yolunu takip ederek migration işlememizi gerçekleştiriyoruz.
ADIM 3 : Migration Yazıyoruz.
public function up(){Schema::create('giris_authentications', function (Blueprint $table){$table->id(); $table->integer('user_id'); $table->boolean('google2fa_enable')->default(false); $table->string('google2fa_secret')->nullable(); $table->timestamps(); }); }
.env dosyamızı hazırladığımızı varsayarak tablomuzu oluşturuyoruz.
php artisan migrate:refresh
ADIM 4 : Model İlişkilerimizi Ayarlıyoruz.
User.php
public function loginSecurity(){return $this->hasOne('App\Models\GirisAuthentication '); }
LoginSecurity.php
protected $fillable = [ 'user_id' ]; public function user(){return $this->belongsTo('App\Models\User'); }
ADIM 5 : Controller Yazıyoruz.
<?php namespace App\Http\Controllers; use App\Models\GirisAuthentication ; use Auth; use Hash; use Illuminate\Http\Request; class GirisAuthenticationController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show 2FA Setting form */ public function show2faForm(Request $request){ $user = Auth::user(); $google2fa_url = ""; $secret_key = ""; if($user->loginSecurity()->exists()){ $google2fa = (new \PragmaRX\Google2FAQRCode\Google2FA()); $google2fa_url = $google2fa->getQRCodeInline( 'MyNotePaper Demo', $user->email, $user->loginSecurity->google2fa_secret ); $secret_key = $user->loginSecurity->google2fa_secret; } $data = array( 'user' => $user, 'secret' => $secret_key, 'google2fa_url' => $google2fa_url ); return view('auth.2fa_settings')->with('data', $data); } /** * Generate 2FA secret key */ public function generate2faSecret(Request $request){ $user = Auth::user(); // Initialise the 2FA class $google2fa = (new \PragmaRX\Google2FAQRCode\Google2FA()); // Add the secret key to the registration data $login_security = LoginSecurity::firstOrNew(array('user_id' => $user->id)); $login_security->user_id = $user->id; $login_security->google2fa_enable = 0; $login_security->google2fa_secret = $google2fa->generateSecretKey(); $login_security->save(); return redirect('/2fa')->with('success',"Secret key is generated."); } /** * Enable 2FA */ public function enable2fa(Request $request){ $user = Auth::user(); $google2fa = (new \PragmaRX\Google2FAQRCode\Google2FA()); $secret = $request->input('secret'); $valid = $google2fa->verifyKey($user->loginSecurity->google2fa_secret, $secret); if($valid){ $user->loginSecurity->google2fa_enable = 1; $user->loginSecurity->save(); return redirect('2fa')->with('success',"2FA is enabled successfully."); }else{ return redirect('2fa')->with('error',"Invalid verification Code, Please try again."); } } /** * Disable 2FA */ public function disable2fa(Request $request){ if (!(Hash::check($request->get('current-password'),Auth::user()->password))){ // The passwords matches return redirect()->back()->with("error","Your password does not matches with your account password. Please try again."); } $validatedData = $request->validate([ 'current-password' => 'required', ]); $user = Auth::user(); $user->loginSecurity->google2fa_enable = 0; $user->loginSecurity->save(); return redirect('/2fa')->with('success',"2FA is now disabled."); }}
ADIM 6 : Middleware Oluşturuyoruz.
2FA ara katmanımızı oluşturarak yasaklı girişleri engelliyoruz.
Google2FAAuthenticator.php <?php namespace App\Support; use PragmaRX\Google2FALaravel\Support\Authenticator; class Google2FAAuthenticator extends Authenticator { protected function canPassWithoutCheckingOTP(){if($this->getUser()->loginSecurity == null) return true; return !$this->getUser()->loginSecurity->google2fa_enable || !$this->isEnabled() || $this->noUserIsAuthenticated() || $this->twoFactorAuthStillValid(); }protected function getGoogle2FASecretKey(){$secret = $this->getUser()->loginSecurity->{$this->config('otp_secret_column')}; if (is_null($secret) || empty($secret)){throw new InvalidSecretKey('Secret key cannot be empty.'); }return $secret; }}