There are different types of API architecture available. You can use REST APIs, GraphQL API, and gRPC to communicate between client and server. These communications also involve user authentications and authorization.
Let’s take a look at GraphQL and how you can authenticate and authorize users using it.
It is a query language that allows you to read and mutate the data in APIs. With GraphQL, you can quickly solve the problems of under-fetching and over-fetching. You get precisely the data that you request. No more, no else. You have a single entry point, i.e., /graphql, that you use to get the data.
There are different ways you can authenticate a user in GraphQL. You can use the HTTP header to pass the authentication credentials to the server or utilize JSON Web Token.
You can use ApolloServer for setting up GraphQL. The code below extracts the user token from the Authorization header included in each operation request. The server then processes the token and retrieves the appropriate user object for that token. Finally, it adds this object to the context
object that is passed to every executed resolver.
Once everything is done, each resolver can use this object to determine what data the user can access and what the user can request.
js
const {ApolloServer} = require('apollo-server');const server = new ApolloServer({typeDefs,resolvers,context: ({req}) => {// Get the user token from the headers.const token = req.headers.authorization || '';// Try to retrieve a user with the tokenconst user = getUser(token);// Add the user to the contextreturn {user};}});server.listen().then(({url}) => {console.log(`Server running at ${url}`);});
There are different authorization methods that you can use with GraphQL. Here are some of them: