2017-02-27 1 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

이것은 메소드에 요청 인스턴스가 삽입되지 않은 경우에 더 유용합니다. Thanks – iko

+0

이것은 메소드에 요청 인스턴스가 삽입되어 있지 않은 경우에 더 유용합니다. 감사합니다 – iko

1

처럼 확인하실 수 있습니다,하지만 당신은 정식 볼 수 있습니다 : API 미들웨어. 인증 프로세스가 어떻게 작동하는지 확인할 수 있습니다. 너가 일을 발견하지 않으면 나에게 알리 라. 그러면 나는 오늘 밤 그것을 들여다보고, 나의 대답을 향상시킬 것이다. 파일에서

Laravel\Passport\Http\Middleware\CheckClientCredentials이를 발견 할 것이다 : 당신이 깊이 파고 때 요청이 여기 League\OAuth2\Server\RecourceServer.php 확인됩니다 것을 볼 수

<?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); 
    } 
} 

. 내 추측은 거기서 답을 찾을 수 있다는 것입니다.

+0

감사합니다 일리아스. 나는 경호원을 지나칠 때 PeterPan의 도움을 받아야했다. –

관련 문제