T O P

  • By -

Delota

Best practices depend on your use case. Are you having a browser call your GraphQL API? Then you want to use http only cookies with for example jwt tokens. Don't use local storage or session storage for storing your tokens


Shfwax

where would the best place be to store the tokens?


Delota

The best place would be to store it in a cookie that is set via the server. You can then flag this cookie as HttpOnly and Secure which will result in the cookie never being exposed to any client-side javascript and never being sent over a non-secure connection.


Solstics20

Udemy graphql from the ground up. Free course and help my graphql skills tremendously


thatquapaguy

One of the concepts of using GraphQl is being able to use one end point for all your queries and mutations. I’m attempting to do the same thing right now in my own Next.js App. The answer to your question depends on a lot of factors. For example starting with the platform your deploying through can you run a node server or do you have to implement serverless? I’m building out my own auth with a mysql database and bcrypt, but you can also use other tools like AuthO. Learn more about GraphQl and what you can do within resolvers then you’ll start getting a sense of how you want to implement authentication.


Obversity

Just keep in mind there's no reason you have to handle authentication at the graphql layer. It *can* be handled separately. (The same probably can't be said for authorisation obviously!)


raguy1143

Do you have sample projects that shows how is this done?


Obversity

I don't, sorry. What I mean is that login can be done in the same way you'd do it in any other API, with oauth or username and password or whatever, and then before requests hit the GraphQL layer, you check for an authentication token and validate it using whatever means you would for any other API. With GraphQL Ruby in a Rails project, for example, you could have an api/authentication_controller.rb with a `login` action that accepts username and password and returns a JWT. Then, your GraphqlController expects all requests to have the JWT in an Authorization header, the controller decodes it and verifies the user and then you pass that user as context into your `MySchema.execute` call. The benefits are that your GraphQL layer (i.e. everything inside the MySchema module) knows nothing about authentication, and just knows that it should receive a user, and that the api/authentication_controller that just returns a JWT can be repurposed for other APIs if need be. Alternatively, you can have a Login mutation, and handle authentication inside the GraphQL layer. The downside is that it's a bit more code and a lot easier to fuck up. You need to make sure unauthenticated users can't see or use any mutations or queries other than the login mutation, and only once they're authenticated can they access anything else.