2017-02-27 31 views
2

我有一個公共路線,任何用戶都可以訪問它。 (/timeline)。
在這個動作中,如果用戶被認證,我必須告訴他他是否喜歡這個帖子。
如果路由有auth:api中間件,我可以使用$request->user()獲得通過身份驗證的用戶,但是如果我不使用auth:api中間件,那麼即使用戶發送了正確的access_token,我也無法檢查用戶是否已通過身份驗證。
如何在沒有中間件的情況下檢查access_token是否正確並在控制器中驗證用戶身份?如何在沒有認證的情況下驗證用戶:laravel 5.3中的api中間件?

回答

7

您可以將警衛傳遞給您的方法,以檢查用戶是否使用特定警衛登錄。

$request->user('api'); 
+0

非常感謝Peter Pan。 –

+0

我的榮幸。 ;) – PeterPan666

+3

您也可以在沒有請求對象的情況下使用** Auth :: guard('api') - > user()**。 – Gkiokan

3

您使用的是auth:api,所以我假定您正在討論JSON請求。訪問令牌通常坐在你的請求的頭,所以你可以檢查它像這樣

public function timeline(Request $request) { 
    if ($request->has('access_token') || $request->header('access_token')) { 
     $user = Auth::guard('api')->user(); 
    } 

    ... 
} 
+0

謝謝埃迪。 –

+0

當您沒有將注入請求的實例注入您的方法時,這會更有用。謝謝 – iko

+0

當你沒有注入你的方法的Request實例時,這更有用。謝謝 – iko

1

我沒有在代碼中挖的時候,但你可以看看AUTH:API中間件。你會發現身份驗證過程如何工作。如果你還沒有找到一件事讓我知道,我會在今晚看看它,並改善我的答案。

在文件Laravel\Passport\Http\Middleware\CheckClientCredentials,你會發現這一點:

<?php 

namespace Laravel\Passport\Http\Middleware; 

use Closure; 
use League\OAuth2\Server\ResourceServer; 
use Illuminate\Auth\AuthenticationException; 
use League\OAuth2\Server\Exception\OAuthServerException; 
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory; 

class CheckClientCredentials 
{ 
    /** 
    * The Resource Server instance. 
    * 
    * @var ResourceServer 
    */ 
    private $server; 

    /** 
    * Create a new middleware instance. 
    * 
    * @param ResourceServer $server 
    * @return void 
    */ 
    public function __construct(ResourceServer $server) 
    { 
     $this->server = $server; 
    } 

    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    * 
    * @throws \Illuminate\Auth\AuthenticationException 
    */ 
    public function handle($request, Closure $next, ...$scopes) 
    { 
     $psr = (new DiactorosFactory)->createRequest($request); 

     try{ 
      $psr = $this->server->validateAuthenticatedRequest($psr); 
     } catch (OAuthServerException $e) { 
      throw new AuthenticationException; 
     } 

     foreach ($scopes as $scope) { 
      if (!in_array($scope,$psr->getAttribute('oauth_scopes'))) { 
      throw new AuthenticationException; 
      } 
     } 

     return $next($request); 
    } 
} 

當你越挖越深,你會看到,請求被這裏League\OAuth2\Server\RecourceServer.php驗證。我的猜測是你會找到你的答案

+0

謝謝你Ilyas。我通過傳球后與PeterPan的幫助合作。 –

相關問題