laravel集成谷歌验证

Laravel is a wonderful PHP framework that makes building applications with PHP a lot of fun.

Laravel是一个很棒PHP框架,它使使用PHP构建应用程序变得非常有趣。

One of the nice features of Laravel is how easy it is to set up user authentication. It includes everything from registering to authentication and even password retrieval.

Laravel的一项不错的功能是设置用户身份验证非常容易。 它包括从注册到身份验证甚至是密码检索的所有内容。

However, with the state of the things at the moment, the regular email and password login method is becoming less and less secure. Brute force attacks, phishing scams, data breaches, and SQL injection attacks have become so common that usernames and passwords can be easily cracked, captured, and leaked. Also, the use of weak passwords, same passwords across multiple accounts, and unsecure wifi networks, put many people in jeopardy of getting hacked.

但是,鉴于目前的状况,常规的电子邮件和密码登录方法变得越来越安全。 蛮力攻击,网络钓鱼诈骗,数据泄露和SQL注入攻击已变得非常普遍,用户名和密码很容易被破解,捕获和泄漏。 此外,使用弱密码,跨多个帐户使用相同密码以及不安全的wifi网络,使许多人面临被黑客攻击的危险。

Two factor authentication (2FA) strengthens access security by requiring two methods (also referred to as factors) to verify your identity. Two factor authentication protects against phishing, social engineering and password brute force attacks and secures your logins from attackers exploiting weak or stolen credentials.

两要素认证(2FA)通过要求两种方法(也称为要素)来验证您的身份,从而增强了访问安全性。 两因素身份验证可防止网络钓鱼,社会工程学和密码暴力破解攻击,并利用脆弱或被盗的凭据保护您的登录名不受攻击者的攻击。

In this tutorial, we are going to learn how to add two factor authentication to our Laravel application. We'll be using Google Authenticator and implementing the Time-based One-time Password (TOTP) algorithm specified in RFC 6238.

在本教程中,我们将学习如何在我们的Laravel应用程序中添加两因素身份验证。 我们将使用Google Authenticator并实现RFC 6238中指定的基于时间的一次性密码(TOTP)算法。

To use the two factor authentication, your user will have to install a Google Authenticator compatible app. Here are some that are currently available:

要使用两因素身份验证,您的用户将必须安装与Google Authenticator兼容的应用。 以下是一些当前可用的:

  • Authy for iOS, Android, Chrome, OS X适用于iOS,Android,Chrome,OS X的Authy
  • FreeOTP for iOS, Android and Pebble适用于iOS,Android和Pebble的FreeOTP
  • Google Authenticator for iOS适用于iOS的Google身份验证器
  • Google Authenticator for Android适用于Android的Google身份验证器
  • Google Authenticator (port) on Windows StoreWindows Store上的Google Authenticator(端口)
  • Microsoft Authenticator for Windows PhoneWindows Phone的Microsoft身份验证器
  • LastPass Authenticator for iOS, Android, OS X, Windows适用于iOS,Android,OS X,Windows的LastPass Authenticator
  • 1Password for iOS, Android, OS X, Windows1适用于iOS,Android,OS X,Windows的密码

配置 ( Setting up )

安装Laravel (Installing Laravel)

To start, we will create a fresh Laravel installation. Let's install it in a folder called laravel-2fa

首先,我们将创建一个全新的Laravel安装。 让我们将其安装在名为laravel-2fa的文件夹中

composer create-project --prefer-dist laravel/laravel laravel-2fa# set proper folder permissions
sudo chmod -R 777 laravel-2fa/storage laravel-2fa/bootstrap/cache

For more detailed installation instructions, visit the documentation.

有关更详细的安装说明,请访问文档 。

We can then start our server with the command:

然后,我们可以使用以下命令启动服务器:

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

php artisan serve --port=8000

Now our website will be available on http://localhost:8000. It should look like this.

现在我们的网站将在http://localhost:8000上可用。 它应该看起来像这样。

连接到数据库 (Connecting to a database)

In order to manage the user data, we need to connect to a database. We will use MySQL for this tutorial, but it works the same for any other database system.

为了管理用户数据,我们需要连接到数据库。 在本教程中,我们将使用MySQL,但对于其他任何数据库系统,它的作用相同。

In the .env file, edit the following lines according to your database setup.

.env文件中,根据数据库设置编辑以下几行。

# .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

You should also update the following lines.

您还应该更新以下几行。

# .env
APP_NAME=Laravel 2FA Demo
APP_URL=http://localhost:8000

This is to give our application a name different from the default (Laravel) and also to update our base URL. You can choose any other URL depending on your setup, but take note and use the right base URL while following this tutorial.

这是为了给我们的应用程序一个不同于默认名称的名称(Laravel),并更新我们的基本URL。 您可以根据自己的设置选择其他任何URL,但是在学习本教程时,请注意并使用正确的基本URL。

设置Laravel身份验证 ( Setting up Laravel authentication )

Laravel ships with several pre-built authentication controllers and provides a quick way to scaffold all of the routes and views you need for authentication using one simple command:

Laravel随附了几个预先构建的身份验证控制器,并提供了一种使用一种简单的命令来搭建身份验证所需的所有路由和视图的快速方法:

php artisan make:auth# create the database tables needed with
php artisan migrate

If we visit our site, we will now see this. Notice LOGIN and REGISTER at the top of the screen.

如果我们访问我们的网站,我们现在将看到此信息。 注意屏幕顶部的“ LOGIN和“ REGISTER ”。

.

We can then visit http://localhost:8000/register to register a new user.

然后,我们可以访问http://localhost:8000/register注册一个新用户。

在注册过程中添加两个因素认证 ( Adding two factor authentication during registration )

What we aim to achieve is this:

我们旨在实现的目标是:

  1. When a new user tries to register we will generate a user secret for the authenticator.当新用户尝试注册时,我们将为身份验证器生成用户密码。
  2. On the next request, we will use that secret to show the QR code for the user to set up their Google Authenticator.在下一个请求时,我们将使用该密码显示QR码,以供用户设置其Google身份验证器。
  3. When the user clicks "OK" we will then register the user with their Google Authenticator secret.当用户单击“确定”时,我们将使用其Google Authenticator密码注册用户。

This way the QR code page is accessible ONLY once. This is for maximum security. If the user wants to set up the two factor authentication again, they will have to repeat the flow and invalidate the old one.

这样,QR码页面只能访问一次。 这是为了最大程度的安全。 如果用户想再次设置两因素身份验证,则他们将不得不重复该流程并使旧的身份验证无效。

To achieve this, we will put a step for setting up the Google Authenticator before registering the user in the database.

为此,我们将采取步骤设置Google身份验证器,然后再在数据库中注册用户。

To make changes to the registration flow, we have to define the register method of the RegisterController (you can find it at app/Http/Controllers/Auth/RegisterController).

要更改注册流程,我们必须定义RegisterController的register方法(您可以在app/Http/Controllers/Auth/RegisterController找到它)。

生成并显示秘密 (Generating and displaying the secret)

First, we need to install two packages.

首先,我们需要安装两个软件包。

composer require pragmarx/google2fa-laravel
composer require bacon/bacon-qr-code

If you are using Laravel 5.4 and below, you need to add PragmaRX\Google2FALaravel\ServiceProvider::class, to your providers array, and 'Google2FA' => PragmaRX\Google2FALaravel\Facade::class, to your aliases array in app/config/app.php (Laravel 4.x) or config/app.php (Laravel 5.x).

如果您使用的是Laravel 5.4及更低版本,则需要将PragmaRX\Google2FALaravel\ServiceProvider::class,添加到您的provider数组中,并将'Google2FA' => PragmaRX\Google2FALaravel\Facade::class,app/config/app.php 'Google2FA' => PragmaRX\Google2FALaravel\Facade::class,数组中app/config/app.php 4.x)或config/app.php (Laravel 5.x)。

Next, we have to publish the config file using:

接下来,我们必须使用以下方法发布配置文件:

php artisan vendor:publish --provider=PragmaRX\\Google2FALaravel\\ServiceProvider

Next, we include request class at the top of our RegisterController. This is so we can use the Request class without using of the full namespace.

接下来,我们在RegisterController的顶部包含请求类。 这样我们就可以使用Request类而不使用完整的名称空间。

// app/Http/Controllers/Auth/RegisterController.phpuse Illuminate\Http\Request;

Then we define the register method of our RegisterController as this.

然后,我们以此定义RegisterControllerregister方法。

// app/Http/Controllers/Auth/RegisterController.phppublic function register(Request $request){//Validate the incoming request using the already included validator method$this->validator($request->all())->validate();// Initialise the 2FA class$google2fa = app('pragmarx.google2fa');// Save the registration data in an array$registration_data = $request->all();// Add the secret key to the registration data$registration_data["google2fa_secret"] = $google2fa->generateSecretKey();// Save the registration data to the user session for just the next request$request->session()->flash('registration_data', $registration_data);// Generate the QR image. This is the image the user will scan with their app// to set up two factor authentication$QR_Image = $google2fa->getQRCodeInline(config('app.name'),$registration_data['email'],$registration_data['google2fa_secret']);// Pass the QR barcode image to our viewreturn view('google2fa.register', ['QR_Image' => $QR_Image, 'secret' => $registration_data['google2fa_secret']]);}

We also need to create the view for displaying the QR code. Our method defines the view as google2fa.register, so in resources/views we will create a google2fa folder and a file inside it called register.blade.php.

我们还需要创建用于显示QR码的视图。 我们的方法将视图定义为google2fa.register ,因此在resources/views我们将创建google2fa文件夹,并在其中创建一个名为register.blade.php的文件。

So the full file path will be resources/views/google2fa/register.blade.php.

因此,完整的文件路径将是resources/views/google2fa/register.blade.php

Here are the contents of the file.

这是文件的内容。

// resources/views/google2fa/register.blade.php@extends('layouts.app')@section('content')
<div class="container"><div class="row"><div class="col-md-8 col-md-offset-2"><div class="panel panel-default"><div class="panel-heading">Set up Google Authenticator</div><div class="panel-body" style="text-align: center;"><p>Set up your two factor authentication by scanning the barcode below. Alternatively, you can use the code {{ $secret }}</p><div><img src="{{ $QR_Image }}"></div><p>You must set up your Google Authenticator app before continuing. You will be unable to login otherwise</p><div><a href="/complete-registration"><button class="btn-primary">Complete Registration</button></a></div></div></div></div></div>
</div>
@endsection

Now immediately after registration, the user is taken to a page with the relevant QR code and the SECRET incase they cannot scan the code themselves.

现在,注册后立即将用户带到带有相关QR码和SECRET的页面,以防他们自己无法扫描该码。

The page should look like this.

该页面应如下所示。

注册用户 (Registering the user)

Unfortunately, we get an error when the user tries to proceed beyond this point, this is because we have not set up the route and controller action to handle the proper registration.

不幸的是,当用户尝试继续执行此操作时,我们会收到错误消息,这是因为我们尚未设置路由和控制器操作来处理正确的注册。

However, before we do that, we need to make space for the Google two factor authentication secret in the users table. For that, we create a migration.

但是,在此之前,我们需要在users表中为Google两因素身份验证秘密空间。 为此,我们创建了一个迁移。

php artisan make:migration add_google2fa_column_to_users --table=users

The migration file should look like this.

迁移文件应如下所示。

// database/migrations/201X_XX_XX_XXXXXX_add_google2fa_column_to_users.php<?phpuse Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;class AddGoogle2faColumnToUsers extends Migration
{/*** Run the migrations.** @return void*/public function up(){Schema::table('users', function (Blueprint $table) {// add a text column in the users table for the google2fa_secret$table->text('google2fa_secret');});}/*** Reverse the migrations.** @return void*/public function down(){Schema::table('users', function (Blueprint $table) {// drop the column if the migration is rolledback$table->dropColumn('google2fa_secret');});}
}

The migration file tells our application to add a googel2fa_secret column to our users table when we run it and to delete that column if we rollback the migration. Now we run our migrations again.

迁移文件告诉我们的应用程序在运行时向我们的用户表中添加googel2fa_secret列,并在回滚迁移时删除该列。 现在,我们再次运行迁移。

php artisan migrate

In this next step of the registration, we will need to make use of the register method that we overrode, so in our RegisterController, we change this:

在注册的下一步中,我们将需要使用我们覆盖的register方法,因此在RegisterController ,我们对此进行了更改:

// app/Http/Controllers/Auth/RegisterController.phpuse RegistersUsers;

to this:

对此:

// app/Http/Controllers/Auth/RegisterController.phpuse RegistersUsers {// change the name of the name of the trait's method in this class// so it does not clash with our own register methodregister as registration;}

Next, we create the complete-registration route.

接下来,我们创建complete-registration路线。

In routes/web.php add the following line:

routes/web.php添加以下行:

// routes/web.php Route::get('/complete-registration', 'Auth\RegisterController@completeRegistration');

So, now we define the completeRegistration method in out RegisterController.

因此,现在我们在RegisterController定义completeRegistration方法。

// app/Http/Controllers/Auth/RegisterController.phppublic function completeRegistration(Request $request){        // add the session data back to the request input$request->merge(session('registration_data'));// Call the default laravel authenticationreturn $this->registration($request);}

Unfortunately, the default Laravel authentication saves just the name, email and password.

不幸的是,默认的Laravel身份验证仅保存名称,电子邮件和密码。

To include our google2fa_secret we modify our create method:

为了包括我们的google2fa_secret我们修改了create方法:

// app/Http/Controllers/Auth/RegisterController.phpprotected function create(array $data){return User::create(['name' => $data['name'],'email' => $data['email'],'password' => bcrypt($data['password']),'google2fa_secret' => $data['google2fa_secret'],]);}

We have to also modify our User model's fillable property to include the google2fa_secret and also hide it whenever we cast it to an array or JSON.

我们也必须修改我们的User模型的fillable属性包括google2fa_secret ,也隐藏它时,我们将其转换为一个数组或JSON。

Read about the fillable property here.

在此处阅读有关fillable属性的信息 。

Read about hiding attributes from casting here.

在这里阅读有关隐藏属性的信息 。

So we modify the following lines in the app/User.php.

因此,我们在app/User.php修改了以下几行。

// app/User.php/*** The attributes that are mass assignable.** @var array*/protected $fillable = ['name', 'email', 'password', 'google2fa_secret',];/*** The attributes that should be hidden for arrays.** @var array*/protected $hidden = ['password', 'remember_token', 'google2fa_secret',];

We can proceed with this, but for extra security, let us encrypt the google2fa_secret so that our users are not compromised even if our database gets compromised.

我们可以继续进行此操作,但是为了提高安全性,让我们对google2fa_secret进行加密,以便即使我们的数据库遭到入侵也不会损害我们的用户。

In our User model, we will add these extra methods.

在我们的User模型中,我们将添加这些额外的方法。

// app/User.php/*** Ecrypt the user's google_2fa secret.** @param  string  $value* @return string*/public function setGoogle2faSecretAttribute($value){$this->attributes['google2fa_secret'] = encrypt($value);}/*** Decrypt the user's google_2fa secret.** @param  string  $value* @return string*/public function getGoogle2faSecretAttribute($value){return decrypt($value);}

To understand how the above methods work, read about Laravel accessors and mutators here.

要了解上述方法如何工作,请在此处阅读有关Laravel访问器和变异器的信息 。

Finally, users can now register seamlessly! A logged in user should see this:

最后,用户现在可以无缝注册! 登录的用户应该看到以下内容:

登录期间添加两因素身份验证 ( Adding two factor authentication during logging in )

Everything we have done so far will be useless if we do not use it during the login flow. Since we are still using the default login flow, users only need their email and password.

如果我们在登录流程中不使用它,那么到目前为止,我们所做的一切都是无用的。 由于我们仍在使用默认登录流程,因此用户只需要其电子邮件和密码。

Our aim is for users to first input their Google Authenticator code before they are allowed full access to the site.

我们的目标是让用户先输入他们的Google Authenticator代码,然后才能完全访问该网站。

The best way to implement this is to use a middleware. Thankfully, the pragmarx/google2fa-laravel package ships with a middleware for this.

实现此目的的最佳方法是使用中间件。 幸运的是, pragmarx/google2fa-laravel软件包随附了一个中间件。

To use it, first, we add this to the routeMiddleware array in app/Http/Kernel.php.

要使用它,首先,将其添加到app/Http/Kernel.phprouteMiddleware数组中。

// app/Http/Kernel.phpprotected $routeMiddleware = [...'2fa' => \PragmaRX\Google2FALaravel\Middleware::class,];

With this, we can use 2fa to refer to our middleware whenever we need to. Either in our route files or inside our controller classes.

这样,我们可以在需要时使用2fa引用我们的中间件。 在我们的路由文件中或在我们的控制器类中。

Next, we define the view where the user enters the OTP after logging in. By default, it is configured to use the view at resources/views/google2fa/index.blade.php. So we will create the view and add the following.

接下来,我们定义用户登录后进入OTP的视图。默认情况下,将其配置为在resources/views/google2fa/index.blade.php上使用该视图。 因此,我们将创建视图并添加以下内容。

// resources/views/google2fa/index.blade.php @extends('layouts.app')@section('content')
<div class="container"><div class="row"><div class="col-md-8 col-md-offset-2"><div class="panel panel-default"><div class="panel-heading">Register</div><div class="panel-body"><form class="form-horizontal" method="POST" action="{{ route('2fa') }}">{{ csrf_field() }}<div class="form-group"><label for="one_time_password" class="col-md-4 control-label">One Time Password</label><div class="col-md-6"><input id="one_time_password" type="number" class="form-control" name="one_time_password" required autofocus></div></div><div class="form-group"><div class="col-md-6 col-md-offset-4"><button type="submit" class="btn btn-primary">Login</button></div></div></form></div></div></div></div>
</div>
@endsection

Next, we need a route to handle the submissions of the OTP. The middleware already checks for the OTP, so we just need a route to sit behind the middleware and redirect the user back to the original URL.

接下来,我们需要一种方法来处理OTP的提交。 中间件已经在检查OTP,因此我们只需要一条路由就可以坐在中间件后面,并将用户重定向回原始URL。

We can do that by adding this to routes/web.php:

我们可以通过将其添加到routes/web.php来做到这routes/web.php

// routes/web.phpRoute::post('/2fa', function () {return redirect(URL()->previous());
})->name('2fa')->middleware('2fa');

We created a route that responds to post requests to http://localhost:8000/2fa and redirects to the previous URL. Since we put the route behind the 2fa middleware, it will validate the OTP if it is contained in the request object.

我们创建了一条路由,该路由响应对http://localhost:8000/2fa发布请求,并重定向到先前的URL。 由于我们将路由放在2fa中间件后面,因此它将验证OTP是否包含在请求对象中。

Now, we can use the middleware to restrict any aspect of the application that requires it.

现在,我们可以使用中间件来限制需要它的应用程序的任何方面。

Read all about using middlewares here.

在此处阅读有关使用中间件的所有信息。

For example, in our HomeController, we can change this:

例如,在我们的HomeController ,我们可以更改此设置:

// app/Http/Controllers/HomeController.php/*** Create a new controller instance.** @return void*/public function __construct(){$this->middleware('auth');}

to this

对此

// app/Http/Controllers/HomeController.php/*** Create a new controller instance.** @return void*/public function __construct(){$this->middleware(['auth', '2fa']);}

So that after logging in, when the user is redirected to /home they have to first enter the one-time password from the google authenticator.

因此,登录后,当用户重定向到/home他们必须首先输入来自Google身份验证器的一次性密码。

They will be presented with a form like this:

它们将以如下形式呈现:

Once they enter the OTP, they will then be fully logged in.

一旦他们进入OTP,他们将完全登录。

That's it! We've successfully added two factor authentication with the Google Authenticator to our Laravel Application.

而已! 我们已经使用Google Authenticator成功地将两因素身份验证添加到了Laravel应用程序中。

奖励:边缘情况 ( BONUS: Edge cases )

用户重新认证 (Reauthentication by the User)

So you user feels like someone has access to his secret and will be able to generate the OTP, so he wants to get a new one.

因此,您的用户感觉好像有人可以访问他的秘密,并且能够生成OTP,因此他想获得一个新的。

You don't want him calling you at 3 am or blaming you if something goes wrong, so you need to give them a link to re-authenticate.

您不希望他在凌晨3点打电话给您或在出现问题时指责您,因此您需要给他们一个链接以进行重新认证。

To do this, let us define the route.

为此,让我们定义路线。

In routes/web.php we'll add:

routes/web.php我们将添加:

// routes/web.phpRoute::get('/re-authenticate', 'HomeController@reauthenticate');

Next, in HomeController we'll add the reauthenticate method;

接下来,在HomeController我们将添加reauthenticate方法;

// app/Http/Controllers/HomeController.phppublic function reauthenticate(Request $request){// get the logged in user$user = \Auth::user();// initialise the 2FA class$google2fa = app('pragmarx.google2fa');// generate a new secret key for the user$user->google2fa_secret = $google2fa->generateSecretKey();// save the user$user->save();// generate the QR image$QR_Image = $google2fa->getQRCodeInline(config('app.name'),$user->email,$user->google2fa_secret);// Pass the QR barcode image to our view.return view('google2fa.register', ['QR_Image' => $QR_Image, 'secret' => $user->google2fa_secret,'reauthenticating' => true]);}

If you notice, we are using the same view as last time. So let us add some conditionals in the view to hide the registration messages.

如果您注意到,我们使用的视图与上次相同。 因此,让我们在视图中添加一些条件来隐藏注册消息。

Edit resources/views/google2fa/register.blade.php:

编辑resources/views/google2fa/register.blade.php

//resources/views/google2fa/register.blade.php@extends('layouts.app')@section('content')
<div class="container"><div class="row"><div class="col-md-8 col-md-offset-2"><div class="panel panel-default"><div class="panel-heading">Set up Google Authenticator</div><div class="panel-body" style="text-align: center;"><p>Set up your two factor authentication by scanning the barcode below. Alternatively, you can use the code {{ $secret }}</p><div><img src="{{ $QR_Image }}"></div>@if (!@$reauthenticating) {{-- add this line --}}<p>You must set up your Google Authenticator app before continuing. You will be unable to login otherwise</p><div><a href="/complete-registration"><button class="btn-primary">Complete Registration</button></a></div>@endif {{-- and this line --}}</div></div></div></div>
</div>
@endsection

您由SysAdmin重新认证 (Reauthentication by you the SysAdmin)

So this time your user cannot login. His phone may have been stolen, or he deleted the credentials unknowingly or some other thing.

因此,这次您的用户无法登录。 他的电话可能被盗了,或者他在不知不觉中删除了凭据或其他东西。

Bottom line is, you have to generate a new secret for him.

最重要的是,您必须为他产生一个新的秘密。

I've found the best way to do this is to create an artisan command that will update the user secret and print it on the command line. We can then send the secret to the user to input in his app.

我发现执行此操作的最佳方法是创建一个工匠命令,该命令将更新用户密码并将其打印在命令行上。 然后,我们可以将机密发送给用户以在其应用程序中输入。

To create the command we run this:

要创建命令,我们运行以下命令:

php artisan make:command ReAuthenticate

Now we can go edit our command file at app/Console/Commands/ReAuthenticate.php.

现在,我们可以在app/Console/Commands/ReAuthenticate.php编辑命令文件。

// app/Console/Commands/ReAuthenticate.php<?phpnamespace App\Console\Commands;use App\User;
use Illuminate\Console\Command;class ReAuthenticate extends Command
{/*** The name and signature of the console command.** @var string*/protected $signature = '2fa:reauthenticate {--email= : The email of the user to reauthenticate} {--force : run without asking for confirmation}';/*** The console command description.** @var string*/protected $description = 'Regenerate the secret key for a user\'s two factor authentication';/*** Create a new command instance.** @return void*/public function __construct(){parent::__construct();}/*** Execute the console command.** @return mixed*/public function handle(){// retrieve the email from the option$email = $this->option('email');// if no email was passed to the option, prompt the user to enter the emailif (!$email) $email = $this->ask('what is the user\'s email?');// retrieve the user with the specified email$user = User::where('email', $email)->first();if (!$user) {// show an error and exist if the user does not exist$this->error('No user with that email.');return;}// Print a warning $this->info('A new secret will be generated for '.$user->email);$this->info('This action will invalidate the previous secret key.');// ask for confirmation if not forcedif (!$this->option('force') && !$this->confirm('Do you wish to continue?')) return;// initialise the 2FA class$google2fa = app('pragmarx.google2fa');// generate a new secret key for the user$user->google2fa_secret = $google2fa->generateSecretKey();// save the user$user->save();// show the new secret key$this->info('A new secret has been generated for '.$user->email);$this->info('The new secret is: '.$user->google2fa_secret);}
}

I've added comments to explain what the command does.

我添加了注释来解释命令的作用。

Read all about the creating console commands for the artisan console here.

在此处阅读有关为工匠控制台创建控制台命令的所有信息。

To use it, we go to the terminal and run

要使用它,我们转到终端并运行

php artisan 2fa:reauthenticate

It will prompt for the user's email and then ask for confirmation.

它将提示输入用户的电子邮件,然后要求确认。

We can also pass the user's email with the command by adding the --email option.

通过添加--email选项,我们还可以通过命令传递用户的电子邮件。

php artisan 2fa:reauthenticate --email johndoe@example.com

To skip confirmation check, we can force the command using the --force option

要跳过确认检查,我们可以使用--force选项强制执行该命令

php artisan 2fa:reauthenticate --force

The new secret key generated will be printed to the console, so you can copy it and send to your user so he can set up his app.

生成的新密钥将被打印到控制台,因此您可以将其复制并发送给您的用户,以便他可以设置他的应用程序。

结论 ( Conclusion )

In this tutorial, we've seen how we can add two factor authentication to a Laravel application. We modified both the registration and login flow, and even dealt with a couple edge cases.

在本教程中,我们已经看到了如何向Laravel应用程序添加两要素身份验证。 我们修改了注册和登录流程,甚至处理了一些极端情况。

If you want to get a Laravel 5.5 template with two factor authentication already set up, you can clone the repository(Don't forget to star it too). It was set up using the steps in this article.

如果您想获得一个已经设置了两因素身份验证的Laravel 5.5模板,则可以克隆存储库 (也不要忘记对其加注星标)。 它是使用本文中的步骤进行设置的。

As always, if you have any questions, suggestions, or comments, please leave them below.

与往常一样,如果您有任何问题,建议或意见,请留在下面。

翻译自: https://scotch.io/tutorials/how-to-add-googles-two-factor-authentication-to-laravel

laravel集成谷歌验证

laravel集成谷歌验证_如何将Google的两因素身份验证添加到Laravel相关推荐

  1. twitter验证_如何为Twitter启用两因素身份验证

    twitter验证 Two-Factor Authentication (2FA) is a great security tool as it makes it harder for attacke ...

  2. 如何在Raspberry Pi上设置两因素身份验证

    Kiklas/ShutterstockKiklas /快门 The Raspberry Pi is everywhere now, which is why it's caught the eye o ...

  3. mongodb启用身份验证_为您的Web应用程序启用两因素身份验证

    mongodb启用身份验证 支持两因素身份验证(2FA)几乎总是一个好主意,尤其是对于后台系统. 2FA有许多不同的形式,其中一些包括SMS,TOTP甚至是硬件令牌 . 启用它们需要类似的流程: 用户 ...

  4. 如何使用Google Authenticator在ASP.NET Core中设置两因素身份验证

    介绍 (Introduction) In this article, we are going to learn how to perform two-factor authentication in ...

  5. 火狐和chrome_Firefox,Chrome和Edge都将支持WebAuthn的硬件两因素身份验证

    火狐和chrome Logging into Gmail or Facebook could soon mean plugging in a USB device, potentially makin ...

  6. 为您的Web应用程序启用两因素身份验证

    支持两因素身份验证(2FA)几乎总是一个好主意,尤其是对于后台系统. 2FA有许多不同的形式,其中一些包括SMS,TOTP甚至是硬件令牌 . 启用它们需要类似的流程: 用户转到其个人资料页面(如果要在 ...

  7. 两因素身份验证增强您的Spring Security

    通过要求用户提供第二种身份验证,双重身份验证为您的Web应用程序增加了一层额外的安全保护. 常见的第二个因素包括: 验证码生物识别电子邮件或短信代码 让我们探讨如何利用Nexmo向现有的Web应用程序 ...

  8. 亚马逊一直停留在身份验证_如何为您的Amazon帐户启用两因素身份验证

    亚马逊一直停留在身份验证 Two-Factor Authentication (2FA) is a great security tool, and we always recommend it. M ...

  9. python 代理服务器 身份验证_如何使用Python+Selenium设置代理身份验证(用户和密码)...

    有一个Firefox+Python的例子,但是没有身份验证here.然后可以在源代码中找到其他可用参数here.所以看起来你需要以下几点:socksUsername socksPassword 例如: ...

最新文章

  1. 通过Mellanox ConnectX NIC使用XDP加速
  2. Spark 学习文章
  3. 上班请病假还得看AI脸色,10秒钟判别真假,打工人太难了
  4. 计算机网络课程优秀备考PPT之第五章网络层(五)
  5. Coursera algorithm II PA4
  6. C语言 函数的封装示例(允许存在同名但形参不同函数)
  7. C语言再学习 -- 详解C++/C 面试题 1
  8. xdocument查找节点值_二叉查找树(java)
  9. 李迟2022年3月工作生活总结
  10. linux网速卡怎么办_手机同是4G网络,为什么总比别人慢,学会这个方法,网速成倍提升...
  11. lambda表达式for_each,find_if简介
  12. python学什么东西_什么是Python?你应该学习和使用它的13个理由
  13. LNMP详解(十三)——Nginx子页面详解
  14. python-excel 批量新建excel工作表
  15. 【Database】人脸数据库介绍及下载链接
  16. Activiti工作流引擎
  17. WINRM实现端口复用后门
  18. C#范例开发大全.刘丽霞李俊民(奋斗的小鸟)_PDF 电子书
  19. H5性能测试以及H5性能测试工具
  20. 从女孩儿手中音乐般滑落

热门文章

  1. 【Mysql】InnoDB 中 B+ 树索引的注意事项
  2. 用DiskGenius彻底删除文件能不能确保无法恢复
  3. OpenCV3.4.8实现立体视觉校正与标定
  4. 计算机网络习题:第三单元
  5. 计算机应用课程的体会,计算机课程心得体会
  6. CSS常用背景属性(背景颜色、背景图片、背景平铺、背景位置、背景附着、背景色半透明、背景属性复合写法)
  7. python人工智能面试题爱奇艺面试题_经典算法题:爱奇艺研发工程师算法笔试题...
  8. Selenium基础用法
  9. 美团html页面代码,html+css+js制作美团官网
  10. 【微信小程序】选择器组件picker