douxie3625 2018-07-05 03:54
浏览 33
已采纳

如何以编程方式登录然后使用Laravel 5.5进行重定向?

I am using Laravel 5.5 and PHP 7.1 I am using the standard built-in Auth and middleware, I have not customized anything.

I am wanting to create a route in the api.php routes file that would be something like this:

Route::group(array('prefix' => 'mobile'), function () {
      Route::get('requestaccess', ['uses' => 'MobileController@RequestAccess']);
});

Then in my MobileController I would have this code:

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()]);
    }
}

and in the web.php route file I have the following:

Route::group(['middleware' => 'auth'], function() {
    Route::get('dashboard', ['uses' => 'DashboardController@getDashboard']);
});

and of course for testing I am typing something like this in my browser:

example.com/api/mobile/requestaccess?token=abc

Everything is all in one domain I am just wanting to log the user in and have them stay logged in while browsing the site.

Any help will be greatly appreciated.

  • 写回答

2条回答 默认 最新

  • dongyong1400 2018-07-05 04:03
    关注

    The API route doesn't have \Illuminate\Session\Middleware\StartSession::class this middleware, meaning it doesn't have any access to session so you cannot maintain session state i.e. logged in state. The purpose of api route is to have a stateless transmission.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里