Blog

OAuth and JWT: How To Use Together + Best Practices

In this article, we'll break down OAuth and JWT, explaining how each works, pointing out the key differences, and sharing best practices for implementing each - separately or together.


Choosing an authentication standard is a big decision for any company creating software, so understanding the options at your disposal, and their implications, is essential.

OAuth and JWT are both open standards that can form a core part of any SaaS application’s authentication stack. Beyond that though, there are many differences: Implementation, security, and the final user experience will all differ based on your chosen approach.

In this article, we'll break down OAuth and JWT, explaining how each works, pointing out the key differences, and sharing best practices for implementing each - separately or together.

Comparing OAuth with JWT

Before getting into the details, it’s important to clarify the relationship between OAuth and JWT.

Developers frequently ask us whether they should use OAuth or JWTs as the underlying standard for their Single Sign-On (SSO) or authentication solution. In practice, these two standards should not be directly compared. 

In fact, we frequently recommend that OAuth access tokens (which have no fixed format) should be issued as a JWT.

Not sure exactly what this means? Let’s explore both standards in detail.

What is OAuth?

OAuth stands for Open Authorization. It’s an open standard for access delegation, commonly used for both authentication and authorization. It allows users to grant limited access to their data or accounts from one service to another.

For example, OAuth can allow a user to authenticate themselves with your app via their Google account.

The main benefits of OAuth are:

  • It's decentralized - there's no single point of failure.
  • It's secure - passwords are never shared directly.
  • It's flexible - can be used for various types of authorization.

The downsides are:

  • It can be complex to implement.
  • There are many versions and options which can lead to vulnerability if not properly configured.

OAuth is best used for:

  • Providing access to user data or accounts between separate apps or websites. For example, allowing a photo app to access your photos stored on another service.
  • Enabling "Login with..." buttons - logging in with your Github, Facebook or other accounts.

If implemented properly, OAuth is a secure and powerful way to enable data sharing between apps and services.

What is JWT?

JWT, or JSON Web Tokens, are an open standard for securely transmitting information between parties, specifically as a JSON object. JWTs are simple, compact tokens used for authentication. 

Some key advantages and disadvantages of JWTs are as follows:

Pros:

  • Self-contained: All the information is in the token, so it has all the necessary data to verify and read the claims. That allows you to create stateless applications that don’t need to verify claims via a third party.
  • Easy to Use: Very compact, URL-safe, and can be used in web apps, mobile apps, and APIs.
  • Scalable: Can hold an unlimited amount of data (unlike Cookies) and is well suited for distributed applications and microservices.
  • Digitally Signed: Each JWT is cryptographically secured, so you can rely on the contents.

Cons:

  • Difficult to Revoke: JWTs have a fixed lifespan. After they’re issued they can’t be altered, so if you want to rescind access to a particular user, it is difficult to do that before the token expires.
  • Slow to Process: The cryptography required to use JWTs takes time, which is worth considering if you are issuing tokens at volume. You could be limited to creating and signing 100’s per second or fewer, depending on your hardware.

Use Cases:

JWTs are a solid choice for authentication because of their versatility, scalability and security when proper practices are followed. They can be used for:

  • Authorization: JWTs can prove you have access to resources after logging in.
  • Information Exchange: JWTs can be used to securely transmit information between parties.
  • Time-Based Authorization: JWTs can have an expiration time, meaning you can grant access for a specified period. For example, you might want to limit the time frame in which an email validation or password reset can be completed.

Which one should you use?

If you want to enable delegated access, where a user authorizes your app to access their data stored elsewhere, OAuth is the best choice for this. 

The access tokens issued by the authorization server are best generated and shared as JWTs. 

On the other hand, if you simply need to verify user identity and basic claims and don’t need the full capabilities of OAuth, then JWT is a great lightweight option. 

JWTs contain all the necessary user info in the token itself, so no database lookups are required to validate a user. This also makes JWT perfect for microservices that don't share a data store.

Some key differences to consider:

  • OAuth requires an authorization server, while JWT can be used stand-alone.
  • OAuth requires client registration, JWT does not.
  • OAuth access tokens can use opaque strings, but JWTs contain readable user info.
  • OAuth tokens can be revoked but JWTs typically cannot be revoked once issued - although a related refresh token can be revoked.

For most scenarios, the combined approach works best. Use OAuth for initial authentication and authorization, then issue that access token as a JWT.

How to use JWT With OAuth 2 for Secure SSO

Using JWT with OAuth 2 for SSO provides the security and convenience of single sign-on with the flexibility of JWTs.

How It Works

With this approach, users sign in to an OAuth service, which returns a JWT as its access token. The token is then used to access protected resources in other applications.

Open ID Connect uses this approach and is a great option if you want to combine both technologies, combining their strengths.

Benefits:

  • Flexibility: JWTs contain custom claims so you can share user info between apps.
  • Security: JWTs are signed, so applications can verify their authenticity.
  • Scalability: This approach works for both smaller apps and large enterprise systems.

Using JWT With WorkOS for Secure SSO

WorkOS’ unified Single Sign-On API supports both SAML and OpenID Connect, which uses OAuth with JWT-based access tokens.

Thankfully, most of this complexity and configuration is taken care of behind the scenes by WorkOS, freeing you up to focus on creating the user experience instead of wrestling with an authentication backend.

How It Works

When a user needs to authenticate on your app, you can make a request to WorkOS’ SSO API (or use one of our SDKs). Your user is then passed to a familiar Single Sign-On interface which corresponds with the identity provider they’re using. 

Once the user has authenticated, they’ll be passed back to the callback URL you supply in the initial API call. Behind the scenes, your app will be supplied with a Profile object. This contains relevant attributes on that user from the identity provider, such as their name, any groups they belong to and their email address.

Here’s what that initial call looks like in Next.JS, using the WorkOS Node SDK:


import type { NextApiRequest, NextApiResponse } from 'next';
import { WorkOS } from '@workos-inc/node';

const workos = new WorkOS(process.env.WORKOS_API_KEY);
const clientId = process.env.WORKOS_CLIENT_ID;

export default (_req: NextApiRequest, res: NextApiResponse) => {
  // The provider to authenticate with
  const provider = 'GoogleOAuth';

  // The callback URI WorkOS should redirect to after the authentication
  const redirectURI = 'https://dashboard.my-app.com';

  const authorizationUrl = workos.sso.getAuthorizationURL({
    provider,
    redirectURI,
    clientId,
  });

  res.redirect(authorizationUrl);
};

You can find a full guide to implementing WorkOS by clicking here. 

Benefits:

  • Decoupled User Authentication: WorkOS handles validating users so you don't have to build and maintain an authentication system.
  • Improved Security: JWTs are digitally signed, so their contents can be trusted. WorkOS also rotates signing keys regularly to prevent spoofing.
  • Reduced Friction: By handling SSO, WorkOS provides a seamless login experience for your users. They can sign in once and access all their enterprise apps.

Best Practices and Troubleshooting

Regardless of whether you choose OAuth or JWTs, follow these best practices to keep your authentication solution secure and running smoothly:

Monitor Access

You’ll want to review access logs frequently to make sure only authorized users are accessing protected resources. Keep an eye out for any suspicious activity like login attempts from unknown devices or locations. It’s also a good idea to set up alerts to notify you of important events like failed login attempts.

Rotate Keys

For added security, you should rotate (change) your JWT signing keys every few months. This will invalidate any existing JWTs and force users to request new tokens with the updated key. Be sure to continue accepting tokens signed with the previous key for a few days to avoid disrupting user access during the transition.

Handle Expirations

Your JWTs and OAuth access tokens will eventually expire. Make sure you have a process in place to refresh tokens before they become invalid to avoid disrupting user access. Some libraries and services will handle this for you, but it’s good to understand how the expiration and refresh flows work.

Ever-evolving best practices like these, and many others, are handled automatically for you when using a done-for-you service like WorkOS.

OAuth and JWT - FAQ:

Here are answers to some common questions about OAuth and JWT:

What’s the difference between OAuth and JWT? 

OAuth is an open standard used for authorization, while JWT is a token format. OAuth uses access tokens to securely transmit information between applications. OAuth can use JWTs for this!

Which is better for enterprise authorization? 

It depends on your needs. OAuth is best if you need to authorize access to APIs and resources. JWT works well for transmitting information in a compact, URL-safe format. Many startups use them together, with OAuth for authorization and JWT for transmitting user info.

Can I use JWT with OAuth? 

Yes, OAuth and JWT complement each other well. OAuth can JWTs as its access tokens, which can contain user info and auth details. This allows for secure, optimized transmission of authentication data between applications.

What can a JWT Include? 

A JWT access token contains data like the user’s info, auth scope, and expiry, encoded as a compact string. Applications can verify and decode the JWT to get user details.

What platforms/services work with JWT and OAuth? 

Most modern auth services, APIs, and platforms support OAuth and/or JWT, including WorkOS, Okta, Google API, Facebook API and more. Both standards have widespread adoption.

How can I implement JWT and OAuth? 

You have a few options:

  • Use an auth-as-a-service platform like WorkOS.
  • Build your own OAuth server and use a library like PyJWT (Python) or jose (JavaScript) to generate JWTs.
  • Use a user management platform with built-in support like Cloudflare Access, AWS Cognito, or Firebase Auth.

Conclusion

OAuth and JWT can both suit different use cases. If you need a simple way to verify user identity and access tokens across domains, OAuth is a great choice. If you need a compact token format to share information between applications - especially internally-networked applications - then JWT is ideal. 

But these two standards excel when they’re used together as a robust authentication solution for your apps. Using JWT as an access token for OAuth is an industry-standard approach to authentication, offering you both security and flexibility.

Of course, if you’d rather not sweat the details or spend the time rolling your own authentication stack, then look at a done-for-you authentication service like WorkOS:

  • Get Started Fast: With SDKs for every popular platform, and Slack-based support, you can implement SSO in minutes rather than weeks.
  • Avoid The Back-And-Forth: WorkOS’ Admin Portal takes the pain out of onboarding your customers’ IT teams and configuring your app to work with their identity provider.
  • Pricing That Makes Sense: Unlike competitors who price by monthly active users, WorkOS charges a flat rate for each company you onboard - whether they bring 10 or 10,000 users to your app.

Explore Unified SSO by WorkOS.

In this article

This site uses cookies to improve your experience. Please accept the use of cookies on this site. You can review our cookie policy here and our privacy policy here. If you choose to refuse, functionality of this site will be limited.