locorecto
locorecto

Reputation: 1203

Auth::user() returns null Laravel 5.1 oauth 2.0

I know this may seem duplicated. I have already checked these threads:

But I haven't found the solution to my problem

After successfully getting the access_token for a user using the credentials Auth::user() returns null within the controllers.

Here is my 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,
];

Here is my 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');

});

Any help would be appreciated

Upvotes: 1

Views: 433

Answers (1)

Luis Sierra
Luis Sierra

Reputation: 36

You need to use Authorizer::getResourceOwnerId() to get the user id. After that you should be able to use Auth::loginUsingId($userId) to log in the user for that request. You could set up a middleware to do this for you, would be something like this:

/**
 * 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);
}

Upvotes: 2

Related Questions