我正在使用Laravel 5.5和PHP 7.1 我正在使用标准的内置Auth和中间件,但尚未自定义任何内容。
我想在api.php路由文件中创建一个如下所示的路由:
Route::group(array('prefix' => 'mobile'), function () {
Route::get('requestaccess', ['uses' => 'MobileController@RequestAccess']);
});
然后在我的MobileController中,我将得到以下代码:
public function RequestAccess() {
try {
$input = request()->all();
$token = $input['token'];
//$page = $input['page'];
$user = User::where('mobile_access_token', $token)->first();
if (!$user)
return view('public.error', ['errorCode' => 901]);
if ($user->mobile_access_expires < Carbon::now())
return view('public.error', ['errorCode' => 902]);
// I tried with and without the second param (true)
if (!Auth::loginUsingId($user->id, true))
return view('public.error', ['errorCode' => 903]);
// My code makes it to here just fine which means the token
// was valid and I
// successfully logged in.
// Now I want to send them to a page where the user
// can browse and remain logged in.
// I tried the following line but it does not work
// It just immediately redirects me to the login page
return redirect(url('dashboard'));
// The following line works but if user clicks a link
// to go to any other page it redirects them to the login page
return view('console.dashboard.dashboard');
} catch (\Exception $e) {
return view('public.error', ['errorCode' => 900, 'errorMessage' => $e->getMessage()]);
}
}
并且在web.php路由文件中,我具有以下内容:
Route::group(['middleware' => 'auth'], function() {
Route::get('dashboard', ['uses' => 'DashboardController@getDashboard']);
});
当然,为了进行测试,我正在浏览器中输入以下内容:
example.com/api/mobile/requestaccess?token=abc
一切都在一个域中,我只是想让用户登录并让他们在浏览网站时保持登录状态。
任何帮助将不胜感激。
答案 0 :(得分:2)
API路由没有\Illuminate\Session\Middleware\StartSession::class
这个中间件,这意味着它没有对session
的任何访问权,因此您无法维护会话状态,即登录状态。 api
路由的目的是进行无状态传输。
答案 1 :(得分:1)
您可以使用Auth::login()
这样登录用户
public function RequestAccess() {
try {
$input = request()->all();
$token = $input['token'];
$user = User::where('mobile_access_token', $token)->first();
if (!$user){
return view('public.error', ['errorCode' => 901, 'errorMessage' => 'Could not find user']);
}
Auth::login($user);
redirect()->('dashboard');
}catch(\Exception $e){
return view('public.error', ['errorCode' => 900, 'errorMessage' => $e->getMessage()]);
}
}
注意:您已编写路由,并在api和控制器中渲染视图,请确保此代码适用于具有web
中间件的StartSession
后卫。如果您要查找api身份验证,则可以查看this
选中其他身份验证方法部分 https://laravel.com/docs/5.6/authentication#authenticating-users