Laravel Passport仅在验证电子邮件时发送“未经身份验证”

时间:2019-10-21 03:41:42

标签: php laravel laravel-passport

我正在做我的项目,我的API有问题。注册和登录系统运行良好。我有一条详细的路线,可以在其中检索有关当前用户的信息。这意味着应用程序能够看到用户已通过身份验证并以正确的方式进行操作。

我开始从事电子邮件验证工作(老实说,要使一切正常工作非常困难)。电子邮件发送正确,但是链接有问题。当我在电子邮件中单击它时,我收到一条错误消息,指出该路由不存在(这是正常的,因为我在api上)。但是,当我添加application / json的标头“ Accept”和Authorization标头时,即使用户经过了正确的身份验证,我也会收到消息“ Unauthenticated”。

路线:

Auth::routes(['verify' => true]);

Route::post('login', 'UserController@login');
Route::post('register', 'UserController@register');

Route::group(['middleware' => 'auth:api'], function() {
    Route::post('details', 'UserController@details');
});

用户模型:

<?php

namespace App;

use App\Notifications\VerifyEmail;
use Laravel\Passport\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname', 'lastname', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function sendEmailVerificationNotification()
    {
        $this->notify(new VerifyEmail);
    }

注册控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;

class UserController extends Controller
{
    public $successStatus = 200;

    public function login() {
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $user = Auth::user();
            $success['token'] = $user->createToken('MyApp')->accessToken;
            return response()->json(['success' => $success], $this->successStatus);
        }
        else {
            return response()->json(['error' => 'Unauthorised'], 401);
        }
    }

    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
            'firstname' => 'required',
            'lastname' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required', 
            'c_password' => 'required|same:password'
        ]);

        if($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')-> accessToken; 
        $success['name'] =  $user->name;
        $user->sendEmailVerificationNotification();
        return response()->json(['success' => $success], $this->successStatus);
    }

    public function details() 
    { 
        $user = Auth::user(); 
        return response()->json(['success' => $user], $this->successStatus); 
    } 
}

验证控制器:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * 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');
    }
}

电子邮件验证通知:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class VerifyEmail extends \Illuminate\Auth\Notifications\VerifyEmail
{
    /**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $verificationUrl = $this->verificationUrl($notifiable);

        if (static::$toMailCallback) {
            return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
        }

        return (new MailMessage)
            ->subject(('Vérification de l\'addresse email'))
            ->line(('Veuillez cliquer sur le bouton ci-dessous pour vérifier votre addresse email.'))
            ->action(('Vérifier mon addresse email'), $verificationUrl)
            ->line(('Si vous n\'avez pas créé de compte, vous n\'avez rien à faire de plus.'));
    }

}

1 个答案:

答案 0 :(得分:1)

您可以在byte[]的构造函数中看到df = pd.DataFrame({'date': pd.date_range('2018-10-01','2019-09-01', freq='D')}) 。您应该将其更改为VerificationController

但是,验证是浏览器加载的内容。它不应该使用$this->middleware('auth');保护,它应该是auth:api(默认行为)。您需要先使用普通的登录方法(而不是通过API)登录,因为那不是API的工作方式。

正确的用例就是将api放在web中。