Use sessions in laravel APIs

Viewed 25511

To create a Two-factor SMS verification in larvel 5.5 and via dingo package, I follow this Simplified workflow:

First check isTwoFactorActive is true or false in your login function if its true send SMS and give the response to get SMS code which is received. If its false directly return token.

Route::post('auth/login', function () {

    $credentials = Input::only('email', 'password');

    if ( ! $token = JWTAuth::attempt($credentials) )
    {
        // return the 401 response
        return Response::json(['error' => 'invalid_credentials'], 401);
    } 

    if(Auth::user()->isTwoFactorActive) {

    $code = rand(1000,9999);  //generate sms code

    $send_sms = SendSMS($code,Auth::user()->phone);  //write your own code here to send SMS to user mobile

    $data= collect(array('sms_code'=>$code,'token'=>$token));  // save sms_code and token in an array 

    Session::push(Auth::user()->id, $data); // save array into session.

    return Response::json(array('login_status'=>'success','user_id'=>Auth::user()->id,'sms_required'=>'yes'));

    } else {

    return Response::json(array('login_status'=>'success','token'=>$token));

    }
});

Now on front end check the response if the token present, then go ahead and show homepage or show enter SMS code screen and capture the SMS code in a form and then post the details to this API again.

Route::post('sms/verification', function () {

    $user_id = Request::input('user_id');
    $code= Request::input('code');

    $data = Session::get($user_id);

    if($data->sms_code == $code) {

    return Response::json(array('status'=>'success','token'=>$data->token));

    } else {

   return Response::json(array('status'=>'failed','msg'=>'Invalid sms code!'));

   }
});

As you can see I used session to store created token to send it after successful two-factor authorization. But seem we can not use session in laravel and APIs.

what can I do in this case?

2 Answers

I'm using Laravel 8 and this changes worked very well for me:

Find your App\Http\Kernel.php and make following changes to 'api' guard value of $middlewareGroups:

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
Related