在 Laravel API 中使用会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47482482/
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
Use sessions in laravel APIs
提问by A.B.Developer
To create a Two-factor SMS verification in larvel 5.5 and via dingopackage, I follow this Simplified workflow:
要在 larvel 5.5 和通过dingo包创建双因素 SMS 验证,我遵循以下简化的工作流程:
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.
首先检查 isTwoFactorActive 在您的登录功能中是真还是假,如果它是真的发送短信并给出响应以获取收到的短信代码。如果为false则直接返回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.
现在在前端检查响应是否存在令牌,然后继续显示主页或显示输入 SMS 代码屏幕并在表单中捕获 SMS 代码,然后再次将详细信息发布到此 API。
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.
如您所见,我使用 session 来存储创建的令牌,以便在成功的两因素授权后发送它。但似乎我们不能在 Laravel 和 API 中使用 session。
what can I do in this case?
在这种情况下我该怎么办?
回答by Matt McAlister
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?
Laravel API 默认设置不包括会话。但我相信您可以手动添加它们。这是我很快找到的链接。 Laravel 5.3 - 如何在没有 CSRF 的情况下将会话添加到`API`?
But the Laravel documentation for Sessionsand Middlewaremay also be useful.

