Auth :: user()返回null Laravel 5.1 oauth 2.0

时间:2017-02-11 17:11:01

标签: php laravel-5 oauth

我知道这似乎有些重复。我已经检查了这些线程:

但我没有找到解决问题的方法

使用凭据成功获取用户的access_token后,Auth :: user()会在控制器中返回null。

这是我的Kernel.php

  protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,
];

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class,
    'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class,
    'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class,
    'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class,
    'csrf' => \App\Http\Middleware\VerifyCsrfToken::class,
];

这是我的routes.php

Route::group(['prefix' => $api_prefix, 'middleware' => 'oauth', 'namespace' => 'Api'], function () {
    Route::resource('user', 'UserController', ['except' => ['create', 'store']]);
    Route::resource('post', 'PostController');

    Route::post('follow/{user}', 'UserRelationsController@follow');
    Route::post('unfollow/{user}', 'UserRelationsController@unfollow');
    Route::post('trade/{user}', 'UserRelationsController@trade');
    Route::post('untrade/{user}', 'UserRelationsController@untrade');
    Route::post('capturetime', 'TimeCaptureController@store');

});

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

您需要使用Authorizer :: getResourceOwnerId()来获取用户ID。之后,您应该能够使用Auth :: loginUsingId($ userId)登录该请求的用户。你可以设置一个中间件为你做这个,就像这样:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $userId = Authorizer::getResourceOwnerId();
    if($userId) {
        Auth::loginUsingId($userId);
    }
    return $next($request);
}