This is actually very simple if you think about it. Look at the REST API. What do you do if you want to call a list of users? You call
GET https://example.com/api/users
And then you get some kind of JSON with a list of users. And when do you want to call a specific user?
GET https://example.com/api/users/5
And you get a single user object in JSON format. How does this work in graphql? Similar but instead of calling separate routes you have a single endpoint and you just prepare the query for that endpoint just like you would do for example in SQL. If you want to fetch data you use queries and when you want to modify data you use mutations. So the simplest query would be:
{
users {
id
name
surname
profile_pic
}
}
And you get a response similar to when you would call https://example.com/api/users
That’s a general idea.
Now when it comes to authentication it’s also the same. How do you generally authenticate REST API written using express? You generate some sort of token and send it to the user and then the user sends that token with each request to authenticate it. That’s the most basic example. You do something very similar in Apollo. And there is a very simple example you can check:
In short in your context function, you check if the header or cookie of the request contains a token, verify that token, and load the user assigned to it. And from that moment user is available in the context object. It’s the same context that also contains data sources and other things.
Now, when it comes to token storage there is really no need to use REDIS. Just use your regular database. And manually check the expiration date (if there is one). You can also run a query that delete expired token by simply comparing expiration dates with a current date.
There is also a way to use it without ANY database by using JWT. You can read about JWT tokens here:
In short, JWT is a token that can contain data, expiration date, and other useful stuff.
When a user creates an account or changes a password you re-generate the certificate/passphrase you use to generate and verify the token. You do that to make sure that if a user’s token leaks (like when his device gets stolen) and he changes the password on the website or you detect a leak inside your app - you just regenerate everyone’s certificate/passphrase and it’s all good because old tokens will not be verified.
Why I’m saying that you do not need a database? Because token authenticity can be verified - you do not need to store them anywhere.
When he authenticates, you send that token to the client app and the client app uses the token to authenticate every request. When apollo receives JWT, you decode it, you pull the user ID if present. And then you verify the token using the certificate/passphrase assigned to the user.
If authentication is successful, you can put that user data in the context and you should know what to do from here.