OAuth and JWT — when to use and how to implement

Josip Vojak
CodeX
Published in
7 min readDec 8, 2022

Authorization, authentication…who knows the difference, right?

Before diving deeper into the concepts of OAuth and JWT, you can take a look at the quick recap to understand the difference between Authorization and Authentication,

Authentication and authorization are two related but distinct concepts in the field of computer security.

Authentication is the process of verifying the identity of a user or a system. This typically involves the user providing a username and password, which the system then verifies against a database of registered users. If the username and password match an entry in the database, the user is considered to be authenticated, and they are granted access to the system.

Authorization, on the other hand, is the process of determining whether an authenticated user has permission to perform a specific action or access a specific resource. This typically involves the system checking the authenticated user’s access rights or privileges against a set of rules or policies to determine whether the user is authorized to perform the requested action.

In summary, authentication is the process of verifying a user’s identity, while authorization is the process of verifying a user’s permissions. Together, these two processes form the cornerstone of secure access control in computer systems.

What is OAuth?

OAuth (Open Authorization) is an open standard for access delegation, which allows users to grant third-party applications access to their resources without sharing their passwords. It provides a secure way for applications to access resources on behalf of users, without requiring the users to share their credentials.

OAuth uses a combination of tokens and secrets to authenticate users and authorize access to resources. It allows users to authorize access to their resources by providing a token, which is issued by the OAuth server and passed along with the request for access. The OAuth server then verifies the token and grants access to the requested resources if it is valid.

What is JWT?

JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is typically used for authorizing requests and exchanging information between parties, such as between a server and a client application.

JWT is a self-contained token, which means that it includes all the necessary information about the user within the token itself. This eliminates the need for the server to query a database to verify the user’s credentials. Instead, the server can simply decode the JWT and extract the relevant information about the user, such as their username, role, and other claims.

JWT is based on the JSON (JavaScript Object Notation) data format, which is widely used for exchanging data between applications. It is encoded in a compact and URL-safe way, which makes it easy to transmit and exchange between parties. It is also digitally signed, which ensures that it cannot be tampered with or forged.

JWT is often used in conjunction with other protocols and technologies, such as OAuth and OpenID Connect, to provide a complete authentication and authorization solution. It is widely used by many popular web and mobile applications, such as Facebook, Google, and Twitter, to securely exchange information about authenticated users.

Core Difference

OAuth and JWT are two different standards for handling authentication and authorization. OAuth (Open Authorization) is an open standard for access delegation, which allows users to grant third-party applications access to their resources without sharing their passwords. It works by providing a secure way for applications to access resources on behalf of users, without requiring the users to share their credentials.

OAuth Implementation in Node.js

To implement OAuth in a Node.js application, you can use a third-party library such as Passport.js. Passport.js is a popular authentication middleware for Node.js that provides a simple and flexible way to implement OAuth.

To use Passport.js, you will first need to install it in your Node.js application. You can do this using the following command:

npm install passport

Next, you will need to configure Passport.js to use the OAuth authentication strategy. This involves specifying the OAuth provider (such as Facebook or Google) and providing the necessary credentials, such as the client ID and secret.

Once Passport.js is configured, you can use it to handle the authentication process. This typically involves setting up routes for handling the authentication request, callback, and other events. Passport.js will take care of the details of the OAuth authentication flow, such as generating and verifying tokens, and providing the authenticated user’s information to your application.

Below, you can find an example of a Node.js application that uses Passport.js to implement OAuth with Facebook:

const express = require('express');
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const app = express();
// Configure Passport to use the Facebook strategy
passport.use(new FacebookStrategy({
clientID: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
}, (accessToken, refreshToken, profile, done) => {
// Save the authenticated user's information
done(null, profile);
}));
// Set up routes to handle the authentication flow
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
(req, res) => {
// Successful authentication, redirect to the user's profile page
res.redirect('/profile');
}
);
app.listen(3000);

JWT Implementation in Node.js

JWT, or JSON Web Token, is a way of securely transmitting information between two parties. In a Node.js application, you can use a third-party library such as jsonwebtoken to easily generate and verify JWT tokens.

To generate a JWT token, you first need to create a JSON object with the information you want to transmit, such as the authenticated user’s username and role. Then, you can use the jsonwebtoken library to sign this JSON object using a secret key. This will generate a JWT token that can be transmitted to the client.

To verify a JWT token, you can use the jsonwebtoken library’s verify method. This method takes the token and the secret key as arguments, and returns the decoded JSON object if the token is valid. This allows the server to authenticate the user and authorize access to protected resources based on the information contained in the JWT.

Overall, JWT provides a simple and secure way to transmit information between parties, and jsonwebtoken makes it easy to implement in a Node.js application.

To use JSON Web Tokens (JWTs) in a Node.js application, you have to have jsonwebtoken package installed.

npm install jsonwebtoken

Once the package is installed, you can use it in your Node.js code to create and verify JWTs. Here is an example of how you might use the jsonwebtoken package to create a JWT that asserts a specific set of claims about the identity of the user associated with the token:

const jwt = require('jsonwebtoken');
// Set the secret that will be used to sign the JWT
const jwtSecret = '<your-jwt-secret>';
// Set the claims that the JWT will assert about the user
const claims = {
userId: 12345,
isAdmin: true
};
// Use the JWT library to create a JWT using the claims and the secret
const token = jwt.sign(claims, jwtSecret);

Once you have created a JWT, you can use it to authenticate the user in your API. This is how you can use the jsonwebtoken package to verify a JWT and extract the claims contained within it:

const jwt = require('jsonwebtoken');
// Set the secret that will be used to verify the JWT
const jwtSecret = '<your-jwt-secret>';
app.get('/', (req, res) => {
// Get the JWT from the request headers
const token = req.headers.authorization;
// Use the JWT library to verify the JWT and extract the claims
const decoded = jwt.verify(token, jwtSecret);
// Use the claims to authenticate the user and provide access to the API
if (decoded.isAdmin) {
res.send('Access granted to admin user');
} else {
res.send('Access granted to regular user');
}
});

Use OAuth with JWT

Here is an example of how you might use these libraries to create a simple server that uses OAuth and JWT for authentication:

const express = require('express');
const oauth = require('oauth');
const jwt = require('jsonwebtoken');
const app = express();
// Create an OAuth client to make requests to the OAuth provider
const oauthClient = new oauth.OAuth(
'https://<OAuth-provider-URL>/request_token',
'https://<OAuth-provider-URL>/access_token',
'<consumer-key>',
'<consumer-secret>',
'1.0',
'<callback-URL>',
'HMAC-SHA1'
);
// Use the OAuth client to make a request to the OAuth provider to get an access token
oauthClient.getOAuthAccessToken(
'<request-token>',
'<request-token-secret>',
(error, accessToken, accessTokenSecret, results) => {
if (error) {
// Handle error
} else {
// Use the access token to make authenticated requests
const options = {
url: 'https://<API-URL>/protected_resource',
oauth: {
consumer_key: '<consumer-key>',
consumer_secret: '<consumer-secret>',
token: accessToken,
token_secret: accessTokenSecret
}
};
request.get(options, (error, response, body) => {
if (error) {
// Handle error
} else {
// Use the JWT library to create a JWT using the access token
const token = jwt.sign({ accessToken }, '<jwt-secret>');
// Use the JWT in your API calls to authenticate the user
app.get('/', (req, res) => {
const decoded = jwt.verify(req.headers.authorization, '<jwt-secret>');
res.send(decoded);
});
}
});
}
}
);

This is a very basic example of how to use OAuth and JWT in a Node.js application. In a real-world application, you would need to handle error conditions, implement proper security measures, and provide a user-friendly interface for authentication.

Conclusion

In conclusion, JSON Web Tokens (JWTs) and OAuth are both industry-standard protocols for authentication and authorization. JWTs are used to create access tokens that assert a specific set of claims about the identity of the user associated with the token. OAuth is an open standard for access delegation, which allows third-party services to grant limited access to an HTTP service.

JWTs and OAuth can be used together to implement secure authentication and authorization in a Node.js application. JWTs can be used to create access tokens that are signed with a secret and can be verified by the API to authenticate the user. OAuth can be used to grant third-party services access to the API on behalf of the user, without the user having to share their credentials.

Overall, JWTs and OAuth are powerful tools for implementing secure authentication and authorization.

--

--

Josip Vojak
CodeX
Writer for

Software architect (AWS Certified) and a former professional volleyball player.