使用 REST API 的 Laravel 电子邮件验证 5.7

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52362927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:03:32  来源:igfitidea点击:

Laravel Email Verification 5.7 using REST API

phplaravelapiemailemail-verification

提问by Илья Зеленько

How to remake Laravel 5.7 Email Verification for Rest API?

如何为 Rest API 重新制作 Laravel 5.7 电子邮件验证?

Or is it worth doing everything from scratch?

或者是否值得从头开始做所有事情?

回答by Илья Зеленько

This case works for me. Full project code here.

这个案例对我有用。完整的项目代码在这里

1) Redesigned VerificationControllercontroller

1) 重新设计的VerificationController控制器

Removed redirects and made response()->json(...)responses.

删除了重定向并做出了response()->json(...)回应。

<?php

namespace App\Http\Controllers\API\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;

class VerificationController extends Controller
{
    use VerifiesEmails;

    /**
     * Show the email verification notice.
     *
     */
    public function show()
    {
        //
    }

    /**
     * Mark the authenticated user's email address as verified.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function verify(Request $request)
    {
        // ->route('id') gets route user id and getKey() gets current user id() 
        // do not forget that you must send Authorization header to get the user from the request
        if ($request->route('id') == $request->user()->getKey() &&
            $request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return response()->json('Email verified!');
//        return redirect($this->redirectPath());
    }

    /**
     * Resend the email verification notification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return response()->json('User already have verified email!', 422);
//            return redirect($this->redirectPath());
        }

        $request->user()->sendEmailVerificationNotification();

        return response()->json('The notification has been resubmitted');
//        return back()->with('resent', true);
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}

2) Added my Notification:

2)添加了我的通知:

I made it so that the link in the email message led to my frontend and contained a temporarySignedRoute link for the request.

我这样做是为了使电子邮件中的链接指向我的前端并包含请求的临时签名路由链接。

use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;

class VerifyEmail extends VerifyEmailBase
{
//    use Queueable;

    /**
     * Get the verification URL for the given notifiable.
     *
     * @param  mixed  $notifiable
     * @return string
     */
    protected function verificationUrl($notifiable)
    {
        $prefix = config('frontend.url') . config('frontend.email_verify_url');
        $temporarySignedURL = URL::temporarySignedRoute(
            'verification.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
        );

        // I use urlencode to pass a link to my frontend.
        return $prefix . urlencode($temporarySignedURL);
    }
}

3) Added config frontend.php:

3)添加配置frontend.php

return [
    'url' => env('FRONTEND_URL', 'http://localhost:8080'),
    // path to my frontend page with query param queryURL(temporarySignedRoute URL)
    'email_verify_url' => env('FRONTEND_EMAIL_VERIFY_URL', '/verify-email?queryURL='),
];

4) Added to User model:

4) 添加到用户模型:

use App\Notifications\VerifyEmail;

and

/**
 * Send the email verification notification.
 *
 * @return void
 */
public function sendEmailVerificationNotification()
{
    $this->notify(new VerifyEmail); // my notification
}

5) Added routes

5) 添加路线

The following routes are used in Laravel:

Laravel 中使用了以下路由:

// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');

They are added to the application if used Auth::routes();.

如果使用,它们会被添加到应用程序中Auth::routes();

As far as I understand the email/verifyroute and its method in the controller are not needed for Rest API.

据我了解email/verify,Rest API 不需要控制器中的路由及其方法。

6) On my frontend page /verify-email(from frontend.phpconfig) i make a request to the address contained in the parameter queryURL

6)在我的前端页面/verify-email(来自frontend.php配置)我向参数中包含的地址发出请求queryURL

The received URL looks like this:

接收到的 URL 如下所示:

"http://localhost:8000/api/email/verify/6?expires=1537122891&signature=0e439ae2d511f4a04723a09f23d439ca96e96be54f7af322544fb76e3b39dd32"

My request(with Authorization header):

我的请求(带有授权标头):

await this.$get(queryURL) // typical get request


The code perfectly verify the email and I can catch the error if it has already been verified. Also I can successfully resend the message to the email.

该代码完美地验证了电子邮件,如果已经过验证,我可以捕获错误。我也可以成功地将消息重新发送到电子邮件。

Did I make a mistake somewhere? Also I will be grateful if you improve something.

我是不是在某个地方弄错了?另外,如果您有所改进,我将不胜感激。

回答by Giacomo

I tried Илья Зеленько answer but I must modify VerificationController construct method as follow

我试过 Илья Зеленько 的答案,但我必须修改 VerificationController 构造方法如下

public function __construct()
{
    $this->middleware('auth')->except(['verify','resend']);
    $this->middleware('signed')->only('verify');
    $this->middleware('throttle:6,1')->only('verify', 'resend');
}

otherwise laravel need autentication to access verify and resend routes

否则 Laravel 需要身份验证才能访问验证和重新发送路由