loading...
Cover image for GraphQL Auth with Passport and Lighthouse PHP

GraphQL Auth with Passport and Lighthouse PHP

joselfonseca profile image Jose Luis Fonseca Updated on ・7 min read

Writing a GraphQL API with Lighthouse PHP and Laravel is really fun, but something that you always have to do is add authentication. This is a common task that Laravel already covers with Passport, but what if you want to have your login and refresh token endpoints as mutations? That is actually a good idea since you don’t really have to document your authentication mechanisms apart from your GraphQL API. You can have it with mutations as well. This is what inspired me to write a little package called Lighthouse GraphQL Passport Auth which at first seems like a long name and to tell you the truth, it is. But let’s dive into how to use it and we worry about the name later XD.

Installation and configuration

First thing we need to do is install the package, now please keep in mind that Lighthouse PHP is required as well as passport, so why don’t we install it in one shot? In a brand new laravel app please enter:

composer require nuwave/lighthouse laravel/passport joselfonseca/lighthouse-graphql-passport-auth

Now let’s configure each of the packages starting with Laravel Passport, for that we are going to first run the migrations.

php artisan migrate

Then we should run the passport Install command.

php artisan passport:install

Then add the HasApiTokens trait to your user model


namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Now we should register the passport routes as we still need them to be able to get tokens internally.

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];
    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
    }
}

Once we have this let’s add the passport driver to the API guard in the config/auth.php file.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

This should conclude the passport configuration.

Now let’s configure and install the Lighthouse PHP package. since it was already pulled from composer we just need to run the following commands to publish the default schema.

php artisan vendor:publish --provider="Nuwave\Lighthouse\LighthouseServiceProvider" --tag=schema

This command will create a file in graphql/schema.graphql with the following schema

"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-01-01 13:00:00`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")

"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")

type Query {
    users: [User!]! @paginate(type: "paginator" model: "App\\User")
    user(id: ID @eq): User @find(model: "App\\User")
}
type User {
    id: ID!
    name: String!
    email: String!
    created_at: DateTime!
    updated_at: DateTime!
}

If you have this file you should be ready to continue with the Lighthouse GraphQL Passport Auth package.

To get the values you need to open your database client and grab the password oauth client from the oauth_clients table, get the client id and secret and put them in the .env file

PASSPORT_CLIENT_ID=2
PASSPORT_CLIENT_SECRET=69YJomGV9plchWIkGD2PyKBBTHfkNA7H83iYGc6j

Once you do that, publish the package configuration and default schema.

php artisan vendor:publish --provider="Joselfonseca\LighthouseGraphQLPassport\Providers\LighthouseGraphQLPassportServiceProvider"

This command should publish 2 files, the config/lighthouse-graphql-passport.php and graphql/auth.graphql file. For convenience and to be able to have better control over the auth schema lets update the config file to use the published schema by changing the value for the schema property to the path to the published file like this:

'schema' => base_path('graphql/auth.graphql')

This will allow us to manipulate the schema if we need to extend it or make changes to the resolvers.

Now let’s remove the user type from the auth schema since we already have it in the default one exported before. Go to the graphql/auth/graphql file and remove the following type

type User {
    id: ID!
    name: String!
    email: String!
}

Once we do that, we need to add a default mutation to the schema so the auth can extend it or we can simply move the auth mutations to the Mutation type in the main schema file. So look for this code in the graphql/auth.graphql file and move it to graphql/schema.graphql file

extend type Mutation {
    login(input: LoginInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Login@resolve")
    refreshToken(input: RefreshTokenInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\RefreshToken@resolve")
    logout: LogoutResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Logout@resolve")
    forgotPassword(input: ForgotPasswordInput! @spread): ForgotPasswordResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\ForgotPassword@resolve")
    updateForgottenPassword(input: NewPasswordWithCodeInput! @spread): ForgotPasswordResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\ResetPassword@resolve")
    register(input: RegisterInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Register@resolve")
}

Then remove the extend word

type Mutation {
    login(input: LoginInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Login@resolve")
    refreshToken(input: RefreshTokenInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\RefreshToken@resolve")
    logout: LogoutResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Logout@resolve")
    forgotPassword(input: ForgotPasswordInput! @spread): ForgotPasswordResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\ForgotPassword@resolve")
    updateForgottenPassword(input: NewPasswordWithCodeInput! @spread): ForgotPasswordResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\ResetPassword@resolve")
    register(input: RegisterInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Register@resolve")
}

You should now have your schema files like this

graphql/auth.graphql

input LoginInput {
    username: String!
    password: String!
}
input RefreshTokenInput {
    refresh_token: String
}
type AuthPayload {
    access_token: String!
    refresh_token: String!
    expires_in: Int!
    token_type: String!
    user: User!
}
type LogoutResponse {
    status: String!
    message: String
}
type ForgotPasswordResponse {
    status: String!
    message: String
}
input ForgotPasswordInput {
    email: String!
}
input NewPasswordWithCodeInput {
    email: String!
    token: String!
    password: String!
    password_confirmation: String!
}
input RegisterInput {
    name: String! @rules(apply: ["required", "string"])
    email: String! @rules(apply: ["required", "email"])
    password: String! @rules(apply: ["required", "confirmed", "min:8"])
    password_confirmation: String!
}

graphql/schema.graphql

"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-01-01 13:00:00`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")
"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")

type Query {
    users: [User!]! @paginate(type: "paginator" model: "App\\User")
    user(id: ID @eq): User @find(model: "App\\User")
}

type Mutation {
    login(input: LoginInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Login@resolve")
    refreshToken(input: RefreshTokenInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\RefreshToken@resolve")
    logout: LogoutResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Logout@resolve")
    forgotPassword(input: ForgotPasswordInput! @spread): ForgotPasswordResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\ForgotPassword@resolve")
    updateForgottenPassword(input: NewPasswordWithCodeInput! @spread): ForgotPasswordResponse! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\ResetPassword@resolve")
    register(input: RegisterInput @spread): AuthPayload! @field(resolver: "Joselfonseca\\LighthouseGraphQLPassport\\GraphQL\\Mutations\\Register@resolve")
}

type User {
    id: ID!
    name: String!
    email: String!
    created_at: DateTime!
    updated_at: DateTime!
}

Lastly we need to install the GraphQL playground we will use to send queries and mutations to our GraphQL server, for that run the following command

composer require mll-lab/laravel-graphql-playground

This is ready for tenting now!

Testing the auth mutations

Let’s start by running the PHP dev server

php artisan serve

This will open the port 8000 in our localhost for us to run the project, let’s navigate to http://127.0.0.1:8000/graphql-playground and you should see the playground like this

Now let’s create a user using a simple console command so we can log in using our graphql API. In the routes/console.php file enter

Artisan::command('user', function () {
    \App\User::create([
        'name' => 'Jose Fonseca',
        'email' => 'myemail@email.com',
        'password' => bcrypt('123456789qq')
    ]);
})->describe('Create sample user');

Then run the command in the console

php artisan user

Now that we have a user to test with, lets run the following mutation in the GraphQL Playground

mutation {
  login(input: {
    username: "myemail@email.com",
    password: "123456789qq"
  }) {
    access_token
    refresh_token
    expires_in
    token_type
    user {
      id
      email
      name
      created_at
      updated_at
    }
  }
}

This should give you the following response

{
  "data": {
    "login": {
      "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk3NDE3MTI1YjBmNjQyZDNkZDljMDkwOGJiNTM2NDQ5YTYwZWU5ZTQ0ZTBkYzEzY2E5M2FhNGFjODI5ZWRiNzkwMWZhZmY5NzVhZTc5MjRiIn0.eyJhdWQiOiIyIiwianRpIjoiOTc0MTcxMjViMGY2NDJkM2RkOWMwOTA4YmI1MzY0NDlhNjBlZTllNDRlMGRjMTNjYTkzYWE0YWM4MjllZGI3OTAxZmFmZjk3NWFlNzkyNGIiLCJpYXQiOjE1NjE0MDkyMDMsIm5iZiI6MTU2MTQwOTIwMywiZXhwIjoxNTkzMDMxNjAzLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.CZOpXN0mFHXAQexpA4-FPMOcV-bdZRJD7zUK7guzethg9KUMrALhzgwfQZJv3w74Gnj54aAbdswHBwZEt9DREyEer7Ht0c8108amOllPqb-ydLET1RL1oYCE9H9vvUK0ZafLp09pMrXKot6UcViGOy97KF7YilAvaFfyGxSOmTTZyn0noe9F2ztIOPd3u9XuPuTR5yL-NqHufTTtyJkdQ2xPo03bF4tRfpMXQ5prnIJi4rxmBkpASwMwVraL4lVSZg_9STWMxXWWFdvmXydkNUtQSAftQyHmwMy33OOTxRtFRDN_1Y9wW7U9okVRM-gindkx0o_EB7ekcP1mvHc2PwxwWPMfFxezex98wYX3jTo8y7CN4vDrgUdXqrKkFc6JzwBgn8q_f7c5SzbzxR824h6ujFzSgMaUk_8zKtHX_qgDqaqPVzTebazQ0Pu9PNoYcCkQi5bNldCGuuaMsMxz3H-CWstR4_pAj9_jeKdvC5MA0OkQ30b3RlSmhSqb65LfZEU-y3wG62FKHD49JxBOpPh_Ga8SOQvfOCIL3SzURX9uOvSgcprQqLBYkhJNJC0gobAFgrKHbDhrBVvGH5U4BbIPVX-gnhR44aoyIf8sXFJQkPJJ7-p8HrCqDqjahrlDXsf4DRZGaVJJFhX2VcWAkCcQA2yJ1LSS1XpNU5oL-x4",
      "refresh_token": "def502004531ba2a174546464239e59c3d07332f8aec44bf95db59ba578bcb58c1986dd494d887c79282daf7379d2959b35816e07245ad237e5fa5e6b3ea1ff19ca0058aa82abc4d0abad427eb045b894c7591e4e248d684ea0c6772011ac1723d3d63805e0e148ec0875277072e39d9ecafcbe55d29b28607dc3ea9f85bdc0ca88aadca41b97e8f061b9b326dc922708f6826aee7e2e3296891e923fd9b5386b4c99d46e9832cb8e191c63bb31394a3dc92a8fc1b907925e9c1888d8b0c4d8c30ea330785dd429623e93979670856fdb5bf80c6c8cac08dc7d040d796e535aa082e241dd38b4ab7a4b0055d554cd85888533c76af594bed20dddcded751bfecd0ffdb741169f204c732cef0e2c49c26ec81de9dd8099b5ab1a481283f70c9685a11ca7018c259688601359722aee0f527c95b8b48062be81d414ce3e10a334d8b5c4f64c25b248c0b76bc40596b99580e38310e7d3a4e82c910276645101d821f",
      "expires_in": 31622400,
      "token_type": "Bearer",
      "user": {
        "id": "1",
        "email": "myemail@email.com",
        "name": "Jose Fonseca",
        "created_at": "2019-06-24 20:43:53",
        "updated_at": "2019-06-24 20:43:53"
      }
    }
  }
}

That is IT! you can now use the token in your GraphQL API!

Testing a protected query

Let’s modify the users query to require authentication with passport, for that open the graphql/schema.graphql file and update the users query with the following

users: [User!]! @middleware(checks: ["auth:api"]) @paginate(type: "paginator" model: "App\\User")

Now try to run the a users query

{
  users(count: 20){
    data {
      id
      email
    }
  }
}

This should give you an authentication error like the following

{
  "errors": [
    {
      "debugMessage": "Unauthenticated.",
      "message": "Internal server error",
      "extensions": {
        "category": "internal"
      },
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "users"
      ],
      "trace": [
...
}

This means the query needs to have the access token in the request. To do that in the GraphQL Playground add the authorization header with the token we generated before

Re run the query and you should have the result just fine!

As you can see the query is protected and you can now use authentication in your GraphQL API.

Now go a head and try the rest of the mutations available to like refresh the token or reset a password.

If you like this little package please start it in Github and let me know if you run into any issues.

GitHub logo joselfonseca / lighthouse-graphql-passport-auth

Add GraphQL mutations to get tokens from passport for https://lighthouse-php.com/

Lighthouse GraphQL Passport Auth (Laravel ^5.8 / Lighthouse ^3.2)

Build Status Total Downloads StyleCI License

GraphQL mutations for Laravel Passport using Lighthouse PHP ^3.2.

Tutorial

You can see this tutorial for installation and usage.

Documentation

Find the detailed documentation in the documentation site

Change log

Please see the releases page https://github.com/joselfonseca/lighthouse-graphql-passport-auth/releases

Tests

To run the test in this package, navigate to the root folder of the project and run

    composer install

Then

    vendor/bin/phpunit

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email jose at ditecnologia dot com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Happy Coding!

Posted on by:

joselfonseca profile

Jose Luis Fonseca

@joselfonseca

Working on web since 2007, Node JS and PHP lover, currently software architect for Dom and Tom Inc.

Discussion

pic
Editor guide
 

Hola, a la hora de ejecutar composer require joselfonseca/lighthouse-graphql-passport-auth veo una incompatibilidad con laravel 6, hay planes para actualizar el paquete para laravel 6? te agradesco.

 

Si funciona en laravel 6, pero debes instalar passport 7.5.1 o inferior, así lo deje yo de momento y gracias Jose Luis, excelente aporte :)

"require": {
"php": "7.2",
"fideloper/proxy": "4.0",
"joselfonseca/lighthouse-graphql-passport-auth": "2.0",
"laravel/framework": "6.2",
"laravel/passport": "7.5.1",
"laravel/tinker": "1.0",
"nuwave/lighthouse": "4.5"
},

 

Gracias! igual ya soportamos Passport 8

github.com/joselfonseca/lighthouse...

Saludos!

Hola, muchas gracias, te agradesco tu tiempo

 

Hola, podrías por favor crear el issue en el repo con el error para mirarlo, gracias!

 

Hola, listo, ya abri un nuevo issue con el error. Muchas gracias.

Hola, el problema era que tenias Passport 8 y ese aun no lo teníamos en las dependencias,

github.com/joselfonseca/lighthouse...

Intenta con ese release que ya debe funcionar

 

Hola, ya implemente el login en mi sistema y funciona bien, pero sabes los middleware de laravel como 'auth' y 'guest' dejaron de funcionar, es decir en mi web.php tengo algo como esto:

Route::get('/login', 'MainController@index')->middleware('guest');
Route::get('/protected', 'MainController@index')->middleware('auth');

Pero no funcionan ahora, es decir si un usuario logueado entra a /login el middleware 'guest' no funciona y por lo tanto puedo acceder, o si entro a /protected logueado no logro ver la pagina, no funciona 'auth'.

Estoy usando react.

Sabes algo al respecto o como lo hago funcionar?? Te agradesco mucho

 

Hola, Este paquete no tiene nada que ver con esa funcionalidad, no la altera ni la usa. El guard que usa es API y es stateless por ende no tiene session persistente. No es el objetivo del paquete.

Saludos!

 

Hola gracias en verdad aprecio tu tiempo. Me estoy interesando mucho en esto de graphql pero ando algo confundido y tengo una duda ahora, sabes como puedo crear un middleware propio en el schema para que solo los admin puedan hacer ciertas queries/mutations (ejemplos ver productos protegidos o eliminar otros usuarios)? Ya sabes si NO son admin le salgan un mensaje tipo "unauthorized". Se me ocurre algo como hacer una consulta con "user" parecida a esto:
user {
id
rank
} y si rank es mayor o igual a 7 es admin (logica del sistema para ser un admin) pero como lo hago middleware para luego usarlo en las queries/mutations protejidos? Gracias

Para eso nosotros usamos github.com/spatie/laravel-permission y la directiva de middleware lighthouse-php.com/4.7/api-referen... El paquete de Spatie tiene un middleware para revisar si un usuario tiene o no un rol o permiso.

Hola, ya estube revisando spatie, actualmente tengo un rol "writer" de ejemplo, ahora mi duda es: ¿sabes como le paso el rol writer desde la directiva middleware de lighthouse para que el middleware de spatie sepa que es writer?

Tengo esto actualmente en mi schema para traer a todos los paises de mi tabla:

countries: [Country!]! @middleware(checks: ["auth:api", "Spatie\Permission\Middlewares\RoleMiddleware"]) @all

El error dice que RoleMiddleware de spatie le falta un argumento que es precisamente el rol.

Error: imgur.com/a/QAwBJhS

Como le paso el rol writer al middleware de spatie? Te agradesco una vez más.

Ya encontre la solución la dejo aquí por si le sirve a alguien en el futuro:

countries: [Country!]! @middleware(checks: ["auth:api", "role:writer"]) @all

 

Hola Jose Luis, Antes que nada quiero agradecer el excelente trabajo que hiciste con Passport y LightHouse.

Te cuento, desde hace un par de días he tenido problemas al instalar Lighthouse GraphQL Passport Auth; Todo funciona de maravilla con Playground, hasta que instalo Lighthouse GraphQL Passport Auth y es entonces cuando Playground me arroja error. Anteriormente ya había usado la libreria sin problemas, no se que esta pasando hago el mismo proceso de implementación.

Agradeceria me comentes si hay algún problema.

Gracias por tu ayuda

Saludos desde La Ciudad de México

"joselfonseca/lighthouse-graphql-passport-auth": "1.4",
"laravel/framework": "5.8.*",
"laravel/passport": "7.4",
"mll-lab/laravel-graphql-playground": "1.1",
"nuwave/lighthouse": "4.1"

thepracticaldev.s3.amazonaws.com/i...

thepracticaldev.s3.amazonaws.com/i...

 

Hola, normalmente eso pasa cuando no hay un mutation en el schema, el trata de extender Mutation pero si no hay por lo menos un Mutation en el schema no hay nada que extender y puede salir ese error. Hay un artículo sobre eso acá mismo en mi blog. Saludos!

 

Efectivamente era eso.

Te agradezco mucho tu ayuda y tu pronta respuesta

Saludos

 

hola jose un gusto seguir tus posts pero tengo un error en la mutation register, el login funciona normal donde puede estar el error si me pudiera ayudar.

{
"errors": [
{
"debugMessage": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'contable. users' doesn't exist (SQL: select count() as aggregate from users where email = la.morenita.38@hotmail.com)",
"message": "Internal server error",
"extensions": {
"category": "internal"
},
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"register"
],
"trace": [
{
"file": "D:\laragon\www\contable\vendor\laravel\framework\src\Illuminate\Database\Connection.php",
"line": 630,
"call": "Illuminate\Database\Connection::runQueryCallback('select count(
) as aggregate from users where email = ?', array(1), instance of Closure)"
},
{
"file": "D:\laragon\www\contable\vendor\laravel\framework\src\Illuminate\Database\Connection.php",
"line": 339,
"call": "Illuminate\Database\Connection::run('select count(*) as aggregate from users where email = ?', array(1), instance of Closure)"
},
{
"file": "D:\laragon\www\contable\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php",

 

Hola, Ese error quiere decir que la tabla no existe, si corriste las migraciones? mira la base de datos por que el error

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'contable. users' doesn't exist 

Dice que la tabla no existe en la base de datos

 

hola si corrio normal las migraciones la tabla existe porque la mutation login si me retorna los datos correctamente solo el register sale ese error no entiendo donde esta el error amigo

dev-to-uploads.s3.amazonaws.com/i/...

 

Jose, como podría implementar roles y permisos siguiendo el ejemplo que acabas de hacer,esta genial crack

 

Hola, Yo uso Spatie Permissions, hay un middleware que se puede aplicar para chequear el permiso al query o mutation. es solo usar la directive de middleware. lighthouse-php.com/3.7/api-referen... github.com/spatie/laravel-permission

 

Mucha gracias Jose, yo podría implementar laravel passport con OpenId Connect segun entiendo es mas seguro ya que me genera un id_Token y usando openID Connect puedo enviar permisos directamente en el token. no se que tan necesario sea.
una ultima pregunta, en donde me recomenda almacenar este token, el cliente que consume esta desarrollado con React y Redux.

Bueno lo que pasa en que Passport usa oAuth2, nosotros aca estamos usando eso mismo, OpenID seria otra implementación de auth distinta por ende Passport ya no seria una opción. Creo que los 2 son cosas distintas. Si lo que quieres es usar un Auth server que implemente OpenID seria otra cosa. Ahora si quieres pasar los permisos directos al front puedes incluirlo como parte del user type. YA en el cliente Redux puede guardarlo en el store. No estoy seguro por que dices que el id_Token es mas seguro, de pronto una referencia o documentación me ayudaría para entender el razonamiento por que para los 2 son igual de seguros solo que son implementaciones distintas, con Passport implementas oAuth2 (en una forma GraphQL) y con open id ellos tienen su propio protocolo y especificación si no estoy mal.

En resumen, si lo que quieres es pasar los permisos al Front puedes agregarlos al user type

type User {
    id: ID!
    name: String!
    email: String!
    roles: [Role]
    permissions: [Permission]
}

type Role {
    id: ID!
    name: String!
    permissions: [Permission]
}

type Permission {
    id: ID!
    name: String!
}

El middleware que se le aplique al query y al mutation es quien verifica si tiene o no el permiso para realizar la acción, pasando los permisos al front puedes controlar que el UI muestre o no cosas pero la validación del back es un si o si XD

Lo del Id_token era simplemente algo que escuche en un video por eso te preguntaba, ya que no sabia que eran implementaciones diferentes solo pense que se complementaban una con la otra.
listo jose muchas gracias entonces los permisos los incluyo en el user type pero de toda formas tengo que implementar el middleware en mutations y query

Si claro, La validacion en el back es Obligatoria com Mayusculas hahahaha. Espero haber ayudado. Saludos!

Jose Luis cada vez estoy mas interesado en el trabajo con graphql. A medida que avanzo aparecen nuevas inquietudes y ahora estoy revisando como hacer para que un solo middleware de autorizacion cubra todas las queries y mutations en lugar de indicarlo uno por uno

Hola, Pues middleware global se puede acá github.com/nuwave/lighthouse/blob/... pero hay que tener cuidado por que igual si necesita queries o mutations que no deba aplicar ese middleware ahi ya no le sirve esta solución.

Hola Jose, estoy trabajando el los middleware para toda la cuestion de cords, roles, autenticacion pero no entiendo muy bien como se implementa, por ejemplo tengo dentro de query:

projects: [Project!]! @all(model: "App\Project") @middleware(checks:["auth:api"])

Pero no entiendo de donde sale que va "auth:api", como seria para poner lo de roles , cords entre otros.
talvez si sabes alguna referencia o documentacion para poder entender bien esa cuestion de middleware con graphQl.
Muchas gracias, saludos.

Hola,

Los globales se pueden poner en

github.com/laravel/laravel/blob/ma...

Y los que se aplican a cada tipo se puede poner en el schema definition

lighthouse-php.com/3.7/api-referen...

Saludos

 

hola soy nuevo en laravel y me ocurre un problema todo el tutorial me corre bien pero al momento de modificar en "schema.graphql" no me actualiza las query y mutaciones para realizar pruebas con los cambios que realize
esta es las versiones que instale
"require": {
"php": "7.1.3",
"fideloper/proxy": "4.0",
"joselfonseca/lighthouse-graphql-passport-auth": "2.0",
"laravel/framework": "5.8.*",
"laravel/passport": "7.4",
"laravel/tinker": "1.0",
"mll-lab/laravel-graphql-playground": "1.1",
"nuwave/lighthouse": "4.3"
},
no se si me podrian decir que estoy haciendo mal

 

Hola, puede ser un problema de cache, ahora por defecto Lighthouse guarda el schema en cache.

php artisan cache:clear

Saludos!

 

muchas gracias eso soluciono mi falla

 

Hola una duda en la parte donde dice:

"For convenience and to be able to have better control over the auth schema lets update the config file"

con config file te refieres a config/lighthouse.php ?? gracias por tu tiempo.

 

No, me refiero al config del paquete que se publica con el comando anterior

 

Hola. Gracias. config/lighthouse-graphql-passport.php

A este archivo te refieres agregar la linea:

'schema' => base_path('graphql/auth.graphql')

??

No Agregar, en la configuracion inicial esta como null, hay que decirle la ruta del schema file como esta ahi.

 

Hi,

Have you had a chance to test a login process? I am having issues with the Passport, GraphQL and PHPUnit test. Think the initial issue was that I did not have a client login and secret in my .env file. I added a DB::table('oauth_clients')->insert at the start of the test, but it did not work. Getting "The user credentials were incorrect." (And I don't really want to be adding the DB::table('oauth_clients')->insert each time to get the user token.

Any help would be appreciated.

** UPDATE **

Ok, I have got it working.

I have called a private function for the DB::insert.

 

Thanks for the tutorial.
This version is outdated, check the manual on Github. In the case of the mutation, you are required to add @spread in order to execute it correctly.

login (input: LoginInput @ spread):

 

Thanks! I fixed it!

 

Hey man, hows it going? This is nice. I'm trying to implement this. But I think the instructions are outdated at the moment?

 

Not sure what you mean by that, are you facing any errors? Remember this is for a PHP Laravel app or API, if you are looking for something more like a service I would recommend you do hasura.io/ or prisma.io/

 

there are compatibility errors when I generate a new laravel app and run the very first terminal command composer require nuwave/lighthouse laravel/passport joselfonseca/lighthouse-graphql-passport-auth

I think that these instructions are only applicable to Laravel 7.* ?

If you are on Laravel 8 then I don't yet have a compatible version. I am working on that.

 

Hola Jose, si yo quisiera usar el email y un username secreto para logueo (tipo bancolombia), que archivos debo afectar aparte del auth.graphql? Gracias hermano por esta iniciativa con Graphql

 

puedes editar el input y usar el metodo findForPassport en el user model

laravel.com/docs/7.x/passport#cust...

 

José disculpa en register me sale este error despues de poner user_name como credencial pero si me registra. Donde más se podría configurar ese campo user_name para que me devuelva que si registró?

Jose disculpa te pregunto de nuevo. Con la credencial user_name me funciona en login cambiando el modelo como dices:
public function findForPassport($username)
{
return $this->where('user_name', $user_name)->first();
}
pero la mutación register funciona y devuelve error, es decir registra en la BD pero me devuelve esto:

"errors": [
{
"message": "Authentication exception",
"extensions": {
"reason": "Incorrect username or password",
"category": "authentication"
},
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"register"
],
"trace": [
{
"file": "C:\conjuntos laravel\horizontal_lighthouse\vendor\joselfonseca\lighthouse-graphql-passport-auth\src\GraphQL\Mutations\Register.php",
"line": 45,
"call": "Joselfonseca\LighthouseGraphQLPassport\GraphQL\Mutations\BaseAuthResolver::makeRequest(array(5))"

tambien hay que configurarlo en la config del paquete

config('lighthouse-graphql-passport.username')

 

Hola, una duda, quiero marcar los emails como verificado y estoy tratando de usar tu mutation VerifyEmail, me pide que inserte un token como argumento,
hasta ahorita tengo algo como esto cuando mande el link al correo del usuario usando $user->sendEmailVerificationNotification()

"example.com/email/verify/10/b2cce7e16059b006a97cb2a2e2fcde1cafeb7bc5?expires=1592270169&signature=b9a248271a992f36d5097b2a2683982a882ebfdbbb0546d447059c9b012b7cc0"

como obtengo tal token?
Gracias te agradesco

 

Encontre una solución para verificar el email, la dejo aquí por si le sirve a alguien en el futuro:
1.crear un mutation VerifyEMail.php con este codigo:
public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
{

    $email = $args['email'];
    $requestHash = $args['requestHash'];
    $requestID = $args['requestID'];

    $user = User::where('email', $email)->first();

    if (! hash_equals((string) $requestID, (string) $user->getKey())) {
        throw new AuthorizationException;
    }

    if (! hash_equals((string) $requestHash, sha1($user->getEmailForVerification()))) {
        throw new AuthorizationException;
    }

    if ($user->markEmailAsVerified()) {
        event(new Verified($user));

        return $user;
    }

}

2.testear:
mutation {
VerifyEMail(
email:"example@gmail.com"
requestID: 10
requestHash: "b2cce7e16059b006a97cb2a2e2fcde1cafeb7bc5"
) {
id
}
}

  1. en web.php:

Route::get('email/verify/{id}/{hash}', function () {
return view('welcome');
})->name('verification.verify')

4.desde la vista mandar el email que el usuario escribió, mandar la id y el hash

Ojala sirva.

 

Hola, esta librería me parece genial, pero tengo una duda. Cómo puedo hacer para iniciar sesión con el ID del usuario; algo como usar Auth::login($user);

Tengo entendido que puedes hacer tu propio resolver, pero es necesario que deba returnar access_token, refresh_token, expire_in para que pueda guardarlo desde el frontend o hay otra manera ?

Talvez me estoy acomplejando por la falta de conocimiento, pero alguien me podría ayudar a aclarar eso por favor ?

 

Esta librería esta pensada para usar Passport laravel.com/docs/7.x/passport yes solo un puente para el mismo, o sea que si usas los tokens, Si no necesitas este tipo de authentication puedes solo usar laravel o otros métodos.

 

Hiya, I'm trying to use this in an app and trying to check whether the users credentials were incorrect. I tried to enter some dummy data into the email and password field and got this response:
When using this mutation:

mutation {
login(input: { username: "dave@something.uk", password: "1431531" }) {
access_token
refresh_token
expires_in
token_type
}
}

I got this:

{
"errors": [
{
"message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
"extensions": {
"guards": [],
"category": "authentication"
},

Any reason why?

 

Buenas Jose Luis he segudo tu excelente turorial pero no se por que me sucede esto tengo la version 5.8 de laravel

por insomnia me he autenticado con passport ya sin problemas he realizado peticiones pero al momento de hacerlo con el playground tal como indicas revienta, si puedes ayudarme te lo agradezco Gracias

----CONSULTA----
mutation {
login(input: {
username: "lj.lizarraga@gmail.com",
password: "123456"
}) {
access_token
}
}

------ERROR

{
"errors": [
{
"message": "Client authentication failed",
"extensions": {
"guards": [],
"category": "authentication"
},
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"login"
],
"trace": [
{
"file": "/home/unknown/Escritorio/eqpon/vendor/joselfonseca/lighthouse-graphql-passport-auth/src/GraphQL/Mutations/Login.php",
"line": 21,
"call": "Joselfonseca\LighthouseGraphQLPassport\GraphQL\Mutations\BaseAuthResolver::makeRequest(array(5))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/Schema/Directives/FieldDirective.php",
"line": 71,
"call": "Joselfonseca\LighthouseGraphQLPassport\GraphQL\Mutations\Login::resolve(null, array(3), instance of Nuwave\Lighthouse\Schema\Context, instance of GraphQL\Type\Definition\ResolveInfo)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/Execution/Arguments/SpreadMiddleware.php",
"line": 42,
"call": "Nuwave\Lighthouse\Schema\Directives\FieldDirective::Nuwave\Lighthouse\Schema\Directives\{closure}(null, array(2), instance of Nuwave\Lighthouse\Schema\Context, instance of GraphQL\Type\Definition\ResolveInfo)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/Schema/Factories/FieldFactory.php",
"line": 194,
"call": "Nuwave\Lighthouse\Execution\Arguments\SpreadMiddleware::Nuwave\Lighthouse\Execution\Arguments\{closure}(null, array(1), instance of Nuwave\Lighthouse\Schema\Context, instance of GraphQL\Type\Definition\ResolveInfo)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 632,
"call": "Nuwave\Lighthouse\Schema\Factories\FieldFactory::Nuwave\Lighthouse\Schema\Factories\{closure}(null, array(1), instance of Nuwave\Lighthouse\Schema\Context, instance of GraphQL\Type\Definition\ResolveInfo)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 560,
"call": "GraphQL\Executor\ReferenceExecutor::resolveOrError(instance of GraphQL\Type\Definition\FieldDefinition, instance of GraphQL\Language\AST\FieldNode, instance of Closure, null, instance of Nuwave\Lighthouse\Schema\Context, instance of GraphQL\Type\Definition\ResolveInfo)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 478,
"call": "GraphQL\Executor\ReferenceExecutor::resolveField(GraphQLType: Mutation, null, instance of ArrayObject(1), array(1))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 921,
"call": "GraphQL\Executor\ReferenceExecutor::GraphQL\Executor\{closure}(array(0), 'login')"
},
{
"call": "GraphQL\Executor\ReferenceExecutor::GraphQL\Executor\{closure}(array(0), 'login')"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 923,
"function": "array_reduce(array(1), instance of Closure, array(0))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 494,
"call": "GraphQL\Executor\ReferenceExecutor::promiseReduce(array(1), instance of Closure, array(0))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 256,
"call": "GraphQL\Executor\ReferenceExecutor::executeFieldsSerially(GraphQLType: Mutation, null, array(0), instance of ArrayObject(1))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php",
"line": 208,
"call": "GraphQL\Executor\ReferenceExecutor::executeOperation(instance of GraphQL\Language\AST\OperationDefinitionNode, null)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/webonyx/graphql-php/src/Executor/Executor.php",
"line": 155,
"call": "GraphQL\Executor\ReferenceExecutor::doExecute()"
},
{
"file": "/home/unknown/Escritorio/eqpon/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, instance of Nuwave\Lighthouse\Schema\Context, array(0), null, null)"
},
{
"file": "/home/unknown/Escritorio/eqpon/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, 'mutation {\n login(input: {username: \"lj.lizarraga@gmail.com\", password: \"123456\"}) {\n access_token\n }\n}', null, instance of Nuwave\Lighthouse\Schema\Context, array(0), null, null, array(29))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/GraphQL.php",
"line": 170,
"call": "GraphQL\GraphQL::executeQuery(instance of GraphQL\Type\Schema, 'mutation {\n login(input: {username: \"lj.lizarraga@gmail.com\", password: \"123456\"}) {\n access_token\n }\n}', null, instance of Nuwave\Lighthouse\Schema\Context, array(0), null, null, array(29))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/GraphQL.php",
"line": 109,
"call": "Nuwave\Lighthouse\GraphQL::executeQuery('mutation {\n login(input: {username: \"lj.lizarraga@gmail.com\", password: \"123456\"}) {\n access_token\n }\n}', instance of Nuwave\Lighthouse\Schema\Context, array(0), null, null)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/Support/Http/Controllers/GraphQLController.php",
"line": 70,
"call": "Nuwave\Lighthouse\GraphQL::executeRequest(instance of Nuwave\Lighthouse\Execution\LighthouseRequest)"
},
{
"call": "Nuwave\Lighthouse\Support\Http\Controllers\GraphQLController::query(instance of Nuwave\Lighthouse\Execution\LighthouseRequest)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Controller.php",
"line": 54,
"function": "call_user_func_array(array(2), array(1))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php",
"line": 45,
"call": "Illuminate\Routing\Controller::callAction('query', array(1))"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
"line": 219,
"call": "Illuminate\Routing\ControllerDispatcher::dispatch(instance of Illuminate\Routing\Route, instance of Nuwave\Lighthouse\Support\Http\Controllers\GraphQLController, 'query')"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
"line": 176,
"call": "Illuminate\Routing\Route::runController()"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 680,
"call": "Illuminate\Routing\Route::run()"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 130,
"call": "Illuminate\Routing\Router::Illuminate\Routing\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AcceptJson.php",
"line": 30,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 171,
"call": "Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::handle(instance of Illuminate\Http\Request, instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 105,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 682,
"call": "Illuminate\Pipeline\Pipeline::then(instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 657,
"call": "Illuminate\Routing\Router::runRouteWithinStack(instance of Illuminate\Routing\Route, instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 623,
"call": "Illuminate\Routing\Router::runRoute(instance of Illuminate\Http\Request, instance of Illuminate\Routing\Route)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 612,
"call": "Illuminate\Routing\Router::dispatchToRoute(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
"line": 176,
"call": "Illuminate\Routing\Router::dispatch(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 130,
"call": "Illuminate\Foundation\Http\Kernel::Illuminate\Foundation\Http\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
"line": 21,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 171,
"call": "Illuminate\Foundation\Http\Middleware\TransformsRequest::handle(instance of Illuminate\Http\Request, instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
"line": 21,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 171,
"call": "Illuminate\Foundation\Http\Middleware\TransformsRequest::handle(instance of Illuminate\Http\Request, instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php",
"line": 27,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 171,
"call": "Illuminate\Foundation\Http\Middleware\ValidatePostSize::handle(instance of Illuminate\Http\Request, instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php",
"line": 62,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 171,
"call": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::handle(instance of Illuminate\Http\Request, instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/fideloper/proxy/src/TrustProxies.php",
"line": 57,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 171,
"call": "Fideloper\Proxy\TrustProxies::handle(instance of Illuminate\Http\Request, instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 105,
"call": "Illuminate\Pipeline\Pipeline::Illuminate\Pipeline\{closure}(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
"line": 151,
"call": "Illuminate\Pipeline\Pipeline::then(instance of Closure)"
},
{
"file": "/home/unknown/Escritorio/eqpon/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
"line": 116,
"call": "Illuminate\Foundation\Http\Kernel::sendRequestThroughRouter(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/public/index.php",
"line": 55,
"call": "Illuminate\Foundation\Http\Kernel::handle(instance of Illuminate\Http\Request)"
},
{
"file": "/home/unknown/Escritorio/eqpon/server.php",
"line": 21,
"function": "require_once('/home/unknown/Escritorio/eqpon/public/index.php')"
}
]
}
]
}

 

Mira que el cliente sea password grant y que este seteado correctamente en .env

 

This code above doesn't work for me.
I change "data:" to "input:" and works...
If someone have the same problem, just replace "data:" to "input:" and it will working fine.

Thanks for this package, @joselfonseca . ;)

mutation {
login(data: {
username: "myemail@email.com",
password: "123456789qq"
}) {
access_token
refresh_token
expires_in
token_type
user {
id
email
name
created_at
updated_at
}
}
}

 

Hello, I just released version 2.0 which uses input instead of data, thanks for pointing this out in the post, i have updated it.

github.com/joselfonseca/lighthouse...

i've also added registration routes

 

Hi luis, instead of having the default user table. Use my table with user info? Sorry for asking this im starting to learn laravel deeply specially on API part, hope you can give me guide

 

Hey there, so you need to configure your laravel App to authenticate with that table as well as the model and passport, Once you have that configured and working this package should work as it just uses Passport and the laravel auth behind the scenes.

 

hi jose, can you help me out? I got these error even the model are exists

error => {
"message": "Cannot query field \"_id\" on type \"User\". Did you mean \"id\"?",
"extensions": {
"category": "graphql"
},

this is my auth configuration
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],
],

'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User\User::class,
],
]

I am trying to figure this out but sad to say I cant solve it

Hey there, you are trying to query a field _id but that field does not exist, it should be id without the _

I am using my own user table, Im not relying on laravel's user default table. And I think I cannot see my own model, although I already configure the auth on using my own user table. Can you help me out?

Hi jose just for the update, I got this kind of error

'''The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed."''

 

Hola! Seguí todos los pasos que recomiendas, pero me sale este mensaje:
"message": "Authentication exception",
"extensions": {
"reason": "Incorrect username or password",
"category": "authentication"
},
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"login"
],

¿Es posible que este error salga porque mi base de datos esta en SQL SERVER? Tuve que quitar el created_at y updated_at con public $timestamps = false; en diferentes modelos porque me salia un error de formato de fecha al ejecutar el comando passport:install.

Si pudieras explicarme sobre este problema te lo agradecería mucho.

 

Es posible, nunca usamos esa base de datos. Pero si el problema es por passport entonces tendrías que buscar como soportar passport en SQL server.

 

hola, estoy usando este paquete en uno de mis proyectos, pero tengo un pequeño error con la mutacion de forgetPassword ** y **updateForgottenPassword

al ejecutar esta mutacion:
mutation tokenresetpassword{
forgotPassword(data:{email:"guechadaniel@gmail.com"}){
status
message
}
}

Me genera este error, pero no se que pueda ser:

{
"errors": [
{
"debugMessage": "Route [password.reset] not defined.",
"message": "Internal server error",
"extensions": {
"category": "internal"
},
"locations": [
{
"line": 36,
"column": 3
}
],
"path": [
"forgotPassword"
],
"trace": [
{
"file": "C:\Users\USUARIO\Laravel-projects\backend_app\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php",
"line": 782,
"call": "Illuminate\Routing\UrlGenerator::route('password.reset', array(2), false)"
}

 

Hola, El paquete usa la notificación por defecto de Laravel, esta notificación hace referencia a la vista de enviada al email la cual require esa ruta.

Tienes 2 opciones. Usar el Auth scaffold de laravel laravel.com/docs/6.x/authenticatio... o cambiar la notificación para que no incluya esa ruta.

Saludos!

 

Hola Jose! Que tal? Tengo una pregunta. Suponiendo que tengo una ruta de posts los cuales pertenecen a un usuario (Post BelongsTo User). A la hora de insertar un post, como haria para que se le asigne el posteo al usuario el cual esta autenticado? Saludos!

 

Hola, puedes usar la directiva de inject lighthouse-php.com/4.11/api-refere...

 

Hi Jose Luis and all,

i was so free to code a matching Front-end in React
github.com/noud/frontend

here is the implementation in the back-end
github.com/noud/saas

enjoy,
Noud

 

Nice! Thanks!

 

Hola! es posible integrarlo a una base de datos en sql server? Estoy teniendo problemas con laravel passport y el formato que genera el timestamps. Saludos.

 

Si se puede laravel si. Nuna usamos esa base de datos asi que no hay experiencias previas.

 

Is there any package to integrate spatie permission into lighthouse graphql

 

Not that I know of, but you can always use the can directive.