Graphql-laravel: Can not get authenticated user

Created on 17 Feb 2019  路  9Comments  路  Source: rebing/graphql-laravel

I'm going to get logged in user using Auth::user() method , but it always returns null.
Here is my config file:

<?php

use App\GraphQL\Type\TerminalType;
use App\GraphQL\Query\TerminalsQuery;
use App\GraphQL\Type\OrderType;
use App\GraphQL\Query\OrdersQuery;
use App\GraphQL\Type\FuelTypeType;
use App\GraphQL\Type\PaymentType;
use App\GraphQL\Query\PaymentsQuery;

return [

    // The prefix for routes
    'prefix' => 'gql',
    'routes' => '{graphql_schema?}',
    'controllers' => \Rebing\GraphQL\GraphQLController::class . '@query',
    'middleware' => [],
    'route_group_attributes' => [],

    'default_schema' => 'default',
    'schema' => 'default',
    'schemas' => [
        'default' => [
            'query' => [
                'terminals' => TerminalsQuery::class,
                'orders'    => OrdersQuery::class,
                'orders'    => PaymentsQuery::class,
            ],
            'mutation' => [],            
            'method' => ['get', 'post'],
        ],
    ],

    'types' => [
        'terminal'           => TerminalType::class,
        'order'              => OrderType::class,
        'fuelType'           => FuelTypeType::class,
        'payment'            => PaymentType::class,
    ],

    'error_formatter' => ['\Rebing\GraphQL\GraphQL', 'formatError'],    
    'errors_handler' => ['\Rebing\GraphQL\GraphQL', 'handleErrors'],
    'params_key'    => 'variables',
    'security' => [
        'query_max_complexity' => null,
        'query_max_depth' => null,
        'disable_introspection' => false,
    ],
    'custom_paginators' => [
    ],

    'graphiql' => [
        'prefix' => '/graphiql/{graphql_schema?}',
        'controller' => \Rebing\GraphQL\GraphQLController::class.'@graphiql',
        'middleware' => ['auth'],
        'view' => 'graphql::graphiql',
        'display' => env('ENABLE_GRAPHIQL', true),
    ],
];

And this is my Query class: (see the resolve function)

<?php

namespace App\GraphQL\Query;

use App\Terminal;
use GraphQL;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\SelectFields;
use GraphQL\Type\Definition\ResolveInfo;
use Auth;

class TerminalsQuery extends Query
{
    public function authorize(array $args)
    {
        // IT IS ALWAYS FALSE
        return ! Auth::guest();
    }

    protected $attributes = [
        'name' => "Terminals Query"
    ];

    public function type()
    {
        return Type::listOf(GraphQL::type('terminal'));
    }

    public function args()
    {
        return [
            'id' => [
                'name' => 'id',
                'type' => Type::int(),
            ],
            'name' => [
                'name' => 'name',
                'type' => Type::string(),
            ],
            'orders' => [
                'name' => 'orders',
                'type' => GraphQL::type('order'),
            ],
        ];
    }

    public function resolve($root, $args, SelectFields $fields, ResolveInfo $info)
    {
        $user = \Auth::user();
        if ($user) {
            if (isset($args['id'])) {
                return Terminal::where('user_id', $user->id)->where('id', $args['id'])->get();
            }
            if (isset($args['name'])) {
                return Terminal::where('user_id', $user->id)->where('name', $args['name'])->get();
            }
            return Terminal::get();
        }

    }
}

  • I'm using cookie to authenticate user.
  • If I create a route like below, I can get the authenticated user:
Auth::any('/gql', function () { dd(\Auth::user() ); });

How can I get the authenticated user?

Most helpful comment

@feniarca you need to specify the middleware group responsible handling your authentication layer:
image

As mentioned in #203 (comment) , it's usually:

'middleware' => [
    'web',
],

Thanks!!! that worked as expected

All 9 comments

Are you sure authorize returns null, because in that case you would not even reach the resolve method.

Also, there's an Auth::check() method for convenience

I added this function

public function authorize(array $args)
{
     return ! \Auth::guest();
}

to the TerminalsQuery
and this is the response:(I am login)

{"errors":[{"message":"Unauthorized","extensions":{"category":"graphql"},"locations":[{"line":2,"column":3}],"path":["terminals"],"trace":[{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/Executor\/ReferenceExecutor.php","line":613,"call":"Rebing\\GraphQL\\Support\\Field::Rebing\\GraphQL\\Support\\{closure}(null, array(0), null, instance of GraphQL\\Type\\Definition\\ResolveInfo)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/Executor\/ReferenceExecutor.php","line":548,"call":"GraphQL\\Executor\\ReferenceExecutor::resolveOrError(instance of GraphQL\\Type\\Definition\\FieldDefinition, instance of GraphQL\\Language\\AST\\FieldNode, instance of Closure, null, null, instance of GraphQL\\Type\\Definition\\ResolveInfo)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/Executor\/ReferenceExecutor.php","line":1212,"call":"GraphQL\\Executor\\ReferenceExecutor::resolveField(GraphQLType: Query, null, instance of ArrayObject(1), array(1))"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/Executor\/ReferenceExecutor.php","line":254,"call":"GraphQL\\Executor\\ReferenceExecutor::executeFields(GraphQLType: Query, null, array(0), instance of ArrayObject(1))"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/Executor\/ReferenceExecutor.php","line":207,"call":"GraphQL\\Executor\\ReferenceExecutor::executeOperation(instance of GraphQL\\Language\\AST\\OperationDefinitionNode, null)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/Executor\/Executor.php","line":155,"call":"GraphQL\\Executor\\ReferenceExecutor::doExecute()"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/GraphQL.php","line":165,"call":"GraphQL\\Executor\\Executor::promiseToExecute(instance of GraphQL\\Executor\\Promise\\Adapter\\SyncPromiseAdapter, instance of GraphQL\\Type\\Schema, instance of GraphQL\\Language\\AST\\DocumentNode, null, null, array(2), null, null)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/webonyx\/graphql-php\/src\/GraphQL.php","line":98,"call":"GraphQL\\GraphQL::promiseToExecute(instance of GraphQL\\Executor\\Promise\\Adapter\\SyncPromiseAdapter, instance of GraphQL\\Type\\Schema, 'query ($time_create_order_from: String, $time_create_order_to: String, $time_finish_niopdc_order_from: String, $time_finish_niopdc_order_to: String, $time_niopdc_sent_from: String, $time_niopdc_sent_to: String, $time_arrive_terminal_from: String, $time_arrive_terminal_to: String) {\n  terminals {\n    id\n    name\n    orders(time_create_order_from: $time_create_order_from, time_create_order_to: $time_create_order_to, time_finish_niopdc_order_from: $time_finish_niopdc_order_from, time_finish_niopdc_order_to: $time_finish_niopdc_order_to, time_niopdc_sent_from: $time_niopdc_sent_from, time_niopdc_sent_to: $time_niopdc_sent_to, time_arrive_terminal_from: $time_arrive_terminal_from, time_arrive_terminal_to: $time_arrive_terminal_to) {\n      id\n      liters\n      price_per_liter\n      fuel_type {\n        id\n        name\n        __typename\n      }\n      time_create_order\n      success_payment {\n        id\n        was_success\n        rrn\n        created_at\n        __typename\n      }\n      niopdc_order_id\n      __typename\n    }\n    __typename\n  }\n}', null, null, array(2), null, null, null)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/rebing\/graphql-laravel\/src\/Rebing\/GraphQL\/GraphQL.php","line":104,"call":"GraphQL\\GraphQL::executeQuery(instance of GraphQL\\Type\\Schema, 'query ($time_create_order_from: String, $time_create_order_to: String, $time_finish_niopdc_order_from: String, $time_finish_niopdc_order_to: String, $time_niopdc_sent_from: String, $time_niopdc_sent_to: String, $time_arrive_terminal_from: String, $time_arrive_terminal_to: String) {\n  terminals {\n    id\n    name\n    orders(time_create_order_from: $time_create_order_from, time_create_order_to: $time_create_order_to, time_finish_niopdc_order_from: $time_finish_niopdc_order_from, time_finish_niopdc_order_to: $time_finish_niopdc_order_to, time_niopdc_sent_from: $time_niopdc_sent_from, time_niopdc_sent_to: $time_niopdc_sent_to, time_arrive_terminal_from: $time_arrive_terminal_from, time_arrive_terminal_to: $time_arrive_terminal_to) {\n      id\n      liters\n      price_per_liter\n      fuel_type {\n        id\n        name\n        __typename\n      }\n      time_create_order\n      success_payment {\n        id\n        was_success\n        rrn\n        created_at\n        __typename\n      }\n      niopdc_order_id\n      __typename\n    }\n    __typename\n  }\n}', null, null, array(2), null)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/rebing\/graphql-laravel\/src\/Rebing\/GraphQL\/GraphQL.php","line":90,"call":"Rebing\\GraphQL\\GraphQL::queryAndReturnResult('query ($time_create_order_from: String, $time_create_order_to: String, $time_finish_niopdc_order_from: String, $time_finish_niopdc_order_to: String, $time_niopdc_sent_from: String, $time_niopdc_sent_to: String, $time_arrive_terminal_from: String, $time_arrive_terminal_to: String) {\n  terminals {\n    id\n    name\n    orders(time_create_order_from: $time_create_order_from, time_create_order_to: $time_create_order_to, time_finish_niopdc_order_from: $time_finish_niopdc_order_from, time_finish_niopdc_order_to: $time_finish_niopdc_order_to, time_niopdc_sent_from: $time_niopdc_sent_from, time_niopdc_sent_to: $time_niopdc_sent_to, time_arrive_terminal_from: $time_arrive_terminal_from, time_arrive_terminal_to: $time_arrive_terminal_to) {\n      id\n      liters\n      price_per_liter\n      fuel_type {\n        id\n        name\n        __typename\n      }\n      time_create_order\n      success_payment {\n        id\n        was_success\n        rrn\n        created_at\n        __typename\n      }\n      niopdc_order_id\n      __typename\n    }\n    __typename\n  }\n}', array(2), array(3))"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/rebing\/graphql-laravel\/src\/Rebing\/GraphQL\/GraphQLController.php","line":45,"call":"Rebing\\GraphQL\\GraphQL::query('query ($time_create_order_from: String, $time_create_order_to: String, $time_finish_niopdc_order_from: String, $time_finish_niopdc_order_to: String, $time_niopdc_sent_from: String, $time_niopdc_sent_to: String, $time_arrive_terminal_from: String, $time_arrive_terminal_to: String) {\n  terminals {\n    id\n    name\n    orders(time_create_order_from: $time_create_order_from, time_create_order_to: $time_create_order_to, time_finish_niopdc_order_from: $time_finish_niopdc_order_from, time_finish_niopdc_order_to: $time_finish_niopdc_order_to, time_niopdc_sent_from: $time_niopdc_sent_from, time_niopdc_sent_to: $time_niopdc_sent_to, time_arrive_terminal_from: $time_arrive_terminal_from, time_arrive_terminal_to: $time_arrive_terminal_to) {\n      id\n      liters\n      price_per_liter\n      fuel_type {\n        id\n        name\n        __typename\n      }\n      time_create_order\n      success_payment {\n        id\n        was_success\n        rrn\n        created_at\n        __typename\n      }\n      niopdc_order_id\n      __typename\n    }\n    __typename\n  }\n}', array(2), array(3))"},{"call":"Rebing\\GraphQL\\GraphQLController::query(instance of Illuminate\\Http\\Request, 'default')"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Controller.php","line":54,"function":"call_user_func_array(array(2), array(2))"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/ControllerDispatcher.php","line":45,"call":"Illuminate\\Routing\\Controller::callAction('query', array(2))"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Route.php","line":212,"call":"Illuminate\\Routing\\ControllerDispatcher::dispatch(instance of Illuminate\\Routing\\Route, instance of Rebing\\GraphQL\\GraphQLController, 'query')"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Route.php","line":169,"call":"Illuminate\\Routing\\Route::runController()"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Router.php","line":665,"call":"Illuminate\\Routing\\Route::run()"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":30,"call":"Illuminate\\Routing\\Router::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":104,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Router.php","line":667,"call":"Illuminate\\Pipeline\\Pipeline::then(instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Router.php","line":642,"call":"Illuminate\\Routing\\Router::runRouteWithinStack(instance of Illuminate\\Routing\\Route, instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Router.php","line":608,"call":"Illuminate\\Routing\\Router::runRoute(instance of Illuminate\\Http\\Request, instance of Illuminate\\Routing\\Route)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Router.php","line":597,"call":"Illuminate\\Routing\\Router::dispatchToRoute(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Kernel.php","line":176,"call":"Illuminate\\Routing\\Router::dispatch(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":30,"call":"Illuminate\\Foundation\\Http\\Kernel::Illuminate\\Foundation\\Http\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/fideloper\/proxy\/src\/TrustProxies.php","line":57,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":151,"call":"Fideloper\\Proxy\\TrustProxies::handle(instance of Illuminate\\Http\\Request, instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":53,"call":"Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Middleware\/TransformsRequest.php","line":31,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":151,"call":"Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest::handle(instance of Illuminate\\Http\\Request, instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":53,"call":"Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Middleware\/TransformsRequest.php","line":31,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":151,"call":"Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest::handle(instance of Illuminate\\Http\\Request, instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":53,"call":"Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Middleware\/ValidatePostSize.php","line":27,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":151,"call":"Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::handle(instance of Illuminate\\Http\\Request, instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":53,"call":"Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Middleware\/CheckForMaintenanceMode.php","line":62,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":151,"call":"Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode::handle(instance of Illuminate\\Http\\Request, instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Pipeline.php","line":53,"call":"Illuminate\\Pipeline\\Pipeline::Illuminate\\Pipeline\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Pipeline\/Pipeline.php","line":104,"call":"Illuminate\\Routing\\Pipeline::Illuminate\\Routing\\{closure}(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Kernel.php","line":151,"call":"Illuminate\\Pipeline\\Pipeline::then(instance of Closure)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Http\/Kernel.php","line":116,"call":"Illuminate\\Foundation\\Http\\Kernel::sendRequestThroughRouter(instance of Illuminate\\Http\\Request)"},{"file":"\/home\/mgh\/workspace\/php\/fuel\/public\/index.php","line":55,"call":"Illuminate\\Foundation\\Http\\Kernel::handle(instance of Illuminate\\Http\\Request)"}]}],"data":{"terminals":null}}

As I told, if I change the graphql's route and create a route in web.php like below , I can retrieve the logged in user:

Route::any('/api/gql', function () {
    return response()->json(\Auth::user());
});

I found 2 missing response headers.
If is send the request to

Route::any('/api/gql', function () {
    return response()->json(\Auth::user());
});

The response will contain 2 Set-Cookie headers(XSRF-TOKEN and laravel_session), BUT if I send the disable this route and enable qraphql's route, this 2 headers are missing. Look at this screen shots:(I disabled authorize method of qraphgl at the second shot)
1

The graphql response:

2

You have to set the 'middleware' group as well (web by default in Laravel)

I set the web middleware and it solved the problem. Thanks a lot.

I have the same problem but I use the librairi folklore graphlQL but I do not know how recovered the user logged and I modify the web middleware and I add the class \ App \ Http \ Middleware \ Authenticate :: class,
but it does not work

a little help please

I set the web middleware and it solved the problem. Thanks a lot.

gholami-mohammad, how did you set the web middleware?

@feniarca you need to specify the middleware group responsible handling your authentication layer:
image

As mentioned in https://github.com/rebing/graphql-laravel/issues/203#issuecomment-464663649 , it's usually:

'middleware' => [
    'web',
],

@feniarca you need to specify the middleware group responsible handling your authentication layer:
image

As mentioned in #203 (comment) , it's usually:

'middleware' => [
    'web',
],

Thanks!!! that worked as expected

Was this page helpful?
0 / 5 - 0 ratings

Related issues

edgarsn picture edgarsn  路  4Comments

dongkaipo picture dongkaipo  路  4Comments

constantinosergiou picture constantinosergiou  路  3Comments

AdrianCarreno picture AdrianCarreno  路  5Comments

drmax24 picture drmax24  路  6Comments