【问题标题】:Laravel 5.3 Authentication IssueLaravel 5.3 身份验证问题
【发布时间】:2017-05-25 04:47:06
【问题描述】:

我在获取 Laravel 5.3 中当前经过身份验证的用户时遇到问题。更具体地说,我正在向我的 api.php 文件发出 HTTP 请求,该文件的路由定义为 api/test/create。

控制器代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Test;

class TestController extends Controller
{
    public function store(Request $request) {
        $this->validate($request, [
            'test_name' => 'required',
            'youtube_id' => 'required',
            'is_live_test' => 'required',
        ]);

        //Laravel 5.3 allows to get the user via request
        $user = $request->user;

        if($user) {
            return 'We are logged in';
        } else {
            return 'We are not logged in';
        }

        return '';      
    }
}

每次它返回“我们没有登录”。为了测试这一点,我在刀片文件中引用了 {{ Auth::check() }},它返回为“1”。我不太清楚为什么控制器无法识别用户已登录;有什么想法吗?

我尝试过引用身份验证的不同变体,包括导入 Facade 和执行 Auth::check()、Auth::user(),但无论如何都会带来相同的结果。

【问题讨论】:

  • 它的 $request-&gt;user() 并且您需要确保路由使用 auth 中间件
  • api 中间件应该有auth:api
  • 当使用api路线时,您需要设置护照:laravel.com/docs/5.3/passport
  • 更具体地说,供您的用户使用 api:laravel.com/docs/5.3/…
  • 直接去url将无法访问api路由

标签: laravel laravel-5.3


【解决方案1】:

获取用户对象:

$user = $request->user();

或者:

$user = auth()->user();

【讨论】:

  • 感谢您的提醒——不过,仍然会收到“未登录”。
  • 请显示路由文件内容。还有你使用什么路由文件?
【解决方案2】:

你可以使用:

Auth::user();

还有

auth()->user();

还有

$request->user(); 

【讨论】:

    【解决方案3】:

    您可以直接在Controller中使用Auth::check()方法。

    if (Auth::check()){
        // User is logged in
        // Do something with the Authenticated User.
    }else
    {
        // User is not logged in
    }  
    

    要获取用户数据,请执行以下操作

    $user = Auth::user();
    
    $userId = $user->id;
    

    等等

    【讨论】:

      猜你喜欢
      • 2017-03-15
      • 2017-05-13
      • 1970-01-01
      • 2014-05-10
      • 2017-06-18
      相关资源
      最近更新 更多