在Laravel API中使用会话 [英] Use sessions in laravel APIs

查看:95
本文介绍了在Laravel API中使用会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在larvel 5.5中并通过 dingo 包创建两因素SMS验证,请按照以下简化操作进行操作工作流程:

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

第一次检查isTwoFactorActive在登录函数中是否为true或false,如果它为true,则发送SMS并给出响应以获取接收到的SMS代码.如果它为false,则直接返回令牌.

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));

    }
});

现在在前端检查响应是否存在令牌,然后继续显示主页或显示输入SMS代码屏幕,并以表格形式捕获SMS代码,然后将详细信息再次发布到此API.

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!'));

   }
});

如您所见,在成功进行两因素授权后,我使用会话存储了创建的令牌以将其发送.但是似乎我们不能在laravel和API中使用会话.

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?

推荐答案

Laravel API默认设置不包括会话.但我相信您可以手动添加它们.这是我很快找到的链接. Laravel 5.3-如何将会话添加到`API `没有CSRF?

The Laravel API default setup doesn't include session. But I believe you can add them manually. Here is a link I quickly found. Laravel 5.3 - How to add Sessions to `API` without CSRF?

但是会话 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆