惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
宝玉的分享
宝玉的分享
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Exploit Database - CXSecurity.com
Help Net Security
Help Net Security
腾讯CDC
Project Zero
Project Zero
C
CXSECURITY Database RSS Feed - CXSecurity.com
IT之家
IT之家
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tailwind CSS Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 最新话题
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
N
News | PayPal Newsroom
C
Cybersecurity and Infrastructure Security Agency CISA
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
SegmentFault 最新的问题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Proofpoint News Feed
A
Arctic Wolf
B
Blog RSS Feed
Forbes - Security
Forbes - Security
P
Privacy & Cybersecurity Law Blog
Attack and Defense Labs
Attack and Defense Labs
V2EX - 技术
V2EX - 技术
P
Proofpoint News Feed
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
阮一峰的网络日志
阮一峰的网络日志
aimingoo的专栏
aimingoo的专栏
T
Tenable Blog
MyScale Blog
MyScale Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
W
WeLiveSecurity
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
罗磊的独立博客
The Last Watchdog
The Last Watchdog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Vulnerabilities – Threatpost
美团技术团队
Microsoft Security Blog
Microsoft Security Blog

Clerk Blog

Going to production with Clerk Deploy Clerk Init: The fastest way to start a new project Introducing Clerk CLI Middleware-based route protection bypass Postmortem: Clerk System Outage (March 10, 2026) Clerk for the AI era Add API Key support to your SaaS in minutes Postmortem: Clerk System Outage (February 19, 2026) Using Clerk in a React Native app Postmortem: DNS Provider Outage (February 10, 2026) How do I implement passkeys in Next.js? Clerk ranked #4 fastest-growing software vendor on Ramp’s December 2025 list How do I handle JWT verification in Next.js? Committing to Agent Identity: Clerk raises $50m Series C from Menlo and Anthropic’s Anthology Fund What is the best way to handle authentication in Next.js App Router? Postmortem: Database Incident (September 14–18, 2025) How do I add authentication to a Next.js app? Introducing Free Trials in Clerk Billing Postmortem: August 28, 2025 - elevated API latency and errors Introducing Mosaic: Bring Your Brand to Every Authentication Flow Multi-tenant authentication: What you need to know (and how Clerk helps) What are the risks and challenges of multi-tenancy? Resilience in Practice: Regional Failover at Clerk Build a Cross-Platform B2B App with Clerk, Expo, and Supabase Highlights from the MiduDev/Clerk Hackathon Add multi-tenancy to an app built with Clerk, Lovable, and Supabase How to build an AI coding rules app with Clerk, Lovable, and Supabase How to Build Multi-Tenant Authentication with Clerk Choosing the right SaaS architecture: Multi-Tenant vs. Single-Tenant Postmortem: June 26, 2025 service outage How to Design a Multi-Tenant SaaS Architecture What is multi-tenancy and why it matters for B2B SaaS How OAuth Works Synchronize user data from Clerk to Supabase Add subscriptions to your SaaS with Clerk Billing Getting started with Clerk Billing Multi-tenant analytics with Tinybird and Clerk How Huntr Migrated 250K Users to Clerk: A Scalable Auth Solution for Startups How to take Clerk to Production How to take your Clerk application to production A practical guide to testing Clerk Next.js applications Implementing multi-tenancy into a Supabase app with Clerk How Clerk integrates with a Next.js application using Supabase How Clerk integrates with Supabase Build a blog with tRPC, Prisma, Next.js and Clerk How to enrich PostHog events with Clerk user data How to build a secure project management platform with Next.js, Clerk, and Neon Validate your SaaS idea while building an audience Postmortem: February 6, 2025 service outage Implement Role-Based Access Control in Next.js 15 Build a Next.js sign-up form with React Hook Form Build a Next.js login page template How to implement Google authentication in Next.js 15 What is middleware in Next.js? How to customize Next.js metadata How to set environment variables in Node.js Building a React Login Page Template How to implement per-user OAuth scopes with Clerk Using Clerk SSO to access Google Calendar and other service data Streamline enterprise customer onboarding with SAML and Clerk Clerk launches EASIE SSO and eliminates SSO fees How to secure Liveblocks Rooms with Clerk in Next.js Securing Node.js Express APIs with Clerk and React Combining the benefits of session tokens and JWTs Build a task manager with Next.js, Supabase, and Clerk Comparing Clerk Webhooks vs Backend API Automate Neon schema changes with Drizzle and GitHub Actions A guide to reading authenticated user data from Clerk Role based access control with Clerk Organizations Mitigating OAuth’s recently discovered Open Response Type vulnerability Per-user B2B monetization with Stripe and Clerk Organizations Build a team-based task manager with Next.js, Neon, and Clerk Building a Hybrid Sign-Up/Subscribe Form with Stripe Elements Welcoming Colin from Zod as our inaugural Open Source Fellow Build a modern authenticated chat application with Next.js, Ably, and Clerk Build a waitlist with Clerk user metadata How to use Clerk with PostHog Identify in Next.js How to secure API Gateway using JWT and Lambda Authorizers with Clerk What are passkeys and how do they work? Comparing Authentication in React.js vs. Next.js How to Add an Onboarding Flow for your Application with Clerk Create Your Own Custom User Menu with Radix - Part 2 Introducing Webhook Workflows with Inngest & Svix Clerk raises $30M Series B from CRV and Stripe Clerk in 2023: A Year in Review Build a Movie Emoji Quiz App with Remix, Fauna, and Clerk Ultimate Guide to Magic Link Authentication Create Your Own Custom User Menu with Radix Introducing has(), protect(), and <Protect> Updated Pricing: 10,000 MAUs Free, and a new “Pro Plan” Next.js Authentication with Clerk: Streamlined SSR Handling Clerk Webhooks: Data Sync with Convex Exploring Clerk Metadata with Stripe Webhooks The Ultimate Guide to Next.js Authentication Empower Your Support Team With User Impersonation Clerk Webhooks: Getting Started A Complete Guide to Session Management in Next.js The Advanced Guide to Passwordless Authentication in Next.js How We Roll – Chapter 10: Roundup How We Roll – Chapter 9: Infrastructure
Implementing OAuth 2.0 to React for User Authorization
Gideon Idoko · 2023-04-14 · via Clerk Blog

In today's digital age, applications are used for everything. From social media to online banking, so much can be done online. However, as society's reliance on online services grows, so does the need to keep personal information secure. This is where OAuth 2.0 comes in.

OAuth 2.0 is a popular protocol for both developers and users that lets you share certain information with a third-party app without providing a password. It's become the standard for many online businesses because it's secure and easy to use.

In this article, you'll learn more about OAuth 2.0 and the different ways it can be used. You'll also learn how to implement OAuth 2.0 in a React application for user authorization.

Looking for a simpler way to add OAuth to React? Learn more about our React support with pre-built flows for Google, GitHub, and other providers.

The first step in understanding OAuth 2.0 is understanding that while there are similarities between authentication and authorization, the two concepts are different.

Authentication is the process of verifying the identity of a user or system. Using a set of credentials, such as a username or password, authentication makes sure that users are who they say they are.

Meanwhile, authorization is the process of figuring out if an authenticated user has the right privileges to access certain resources or do certain things. It's mainly focused on figuring out what a user can do and what resources they can use based on their role or other characteristics.

Authentication and authorization are both important parts of web security. They work together to make sure that only people who are allowed to can use a system or its resources.

Now that you know how authentication and authorization work, let's dig into what OAuth 2.0 is.

What Is OAuth 2.0

OAuth 2.0, also referred to as the OAuth 2.0 Authorization Framework, is an open standard for authorization that lets users give third-party applications limited access to their web server resources without giving the applications their private credentials. OAuth 2.0 gives users more control over their data; they can selectively grant access to the applications they want to use.

For instance, OAuth 2.0 can be utilized to help users sign in to third-party applications with their Google account. This is often referred to as social login and is so common you've probably used it.

Here is a brief explanation of what occurs when you use a social login:

  1. A Google sign-up button will pop up on the screen of the third-party app.
  2. When you click the button, you'll be taken to Google's authorization server, where you'll be asked to sign into your Google account (if you aren't currently).
  3. Google displays a consent screen after you log in, listing the permissions the third-party application is requesting (ie your public information, such as email and name).
  4. Once you give your approval, Google will send you back to the app and provide it with an access token that will allow the app to access your public information.
  5. The third-party app can then use the access token to make API calls to Google on your behalf as long as the requests are within the scope of the permissions you granted.

This five-step process defines the OAuth 2.0 flow or grant type. An OAuth 2.0 flow (ie an OAuth 2.0 grant type) typically defines the steps involved in getting an access token, as seen here:

Sample OAuth 2.0 flow, courtesy of Gideon Idoko

By following this implicit OAuth 2.0 flow (more on this later), you can use a third-party application without giving it access to your Google credentials. You can also stop the application from using your account at any time.

Types of OAuth 2.0 Flows

OAuth 2.0 identifies a number of different grant types, or OAuth 2.0 flows, that can be used to get an access token (which is used to access a protected resource). The OAuth 2.0 flow chosen usually depends on the client application, the protected resource, and the trust between the client and the server that does the authorization.

The following are some of the most popular types of OAuth 2.0 flows:

Authorization Code Flow

In an authorization code flow, the resource owner is sent from the client application to the authorization server's authorization endpoint. Then the resource owner logs in and grants consent to the client, and is sent back to the client with an authorization code. Then the client exchanges this code for an access token.

Web applications commonly use this flow; however, it can also be used by mobile apps using the Proof Key for Code Exchange (PKCE) technique.

Implicit Flow with Form Post

The implicit flow with form post is similar to the authorization code flow but is used for browser-based client applications, especially single-page apps. In this case, instead of trading an authorization code for an access token, the authorization server gives the access token directly to the client application, as in the example flow discussed previously.

Resource Owner Password Flow

In a resource owner password flow, the resource owner already knows the client and feels comfortable giving them access to their credentials. The owner of the resource gives the client their private credentials directly, which the client then trades for an access token.

Client Credentials Flow

In the case of a client credentials flow, the client uses their own credentials to access protected resources instead of using the credentials of the resource owner. Afterward, the authorization server gives the client an access token.

OAuth 2.0 Roles

OAuth 2.0 roles define the entities in an OAuth 2.0 flow, and there are four major roles:

  1. Resource owner: The user who owns the protected resource that the client application needs to access. The resource owner may be a person, a system, or a device.
  2. Resource server: The server where the client wants to access a protected resource. The resource server is in charge of enforcing access controls on the protected resource.
  3. Client: The third-party app that wants to access the protected resource on behalf of the resource owner. The client could be a server-based, mobile, or web application.
  4. Authorization server: The server that verifies the resource owner's identity and gives access tokens to the client after the resource owner gives permission. The authorization server also checks the client's access tokens before letting them use protected resources.

Now that you have a better understanding of OAuth 2.0 and the different roles and flows, let's implement OAuth 2.0 in a React application.

Implementing OAuth 2.0 in a React Application

In this section, you'll learn how to implement an OAuth 2.0 authorization code flow in your React application. Additionally, you'll learn a less complicated approach to implementing user authorization with Clerk.

All the code for this tutorial can be found in this GitHub repo.

Prerequisites

Before you begin, you'll need Node.js version 16 or later installed on your machine. Node.js ships with npm, which you'll use to install the necessary packages.

In addition, it's recommended that you have a basic knowledge of React and JavaScript to help you complete this tutorial with ease.

OAuth 2.0 with the Standard Flow

So far, you've only learned about the various OAuth 2.0 flow types. Here, you'll implement one.

The authorization code flow is the most secure flow for web server applications, and this is how it works:

Authorization code OAuth 2.0 flow courtesy of Gideon Idoko

There are three main components: the authorization server, the frontend, and the backend. The final component is the resource (which is part of the backend) that only authorized users can access. In order for a user to be authorized, they must complete the authorization code flow:

  1. A user goes to the authorization server from the frontend to get an authorization code.
  2. The authorization code is then sent to the backend.
  3. The backend verifies the authorization code by getting tokens from the authorization server.
  4. The backend then authorizes the user to have access to the resource.

In this scenario, the frontend is a React application, and the backend/resource is a Node.js application. Building the authorization server is beyond the scope of this article, so instead, you'll leverage Google OAuth 2.0.

Alright, let's get started!

Get Your Google Client ID and Secret

Interacting with the authorization server to get the authorization code is the first step in the OAuth 2.0 flow. You'll need a Google client ID and secret to be able to achieve that.

Follow these steps to obtain the client ID and secret:

  1. Name it. In this example, it's "standard-auth".

  2. Locate the More Products section on the sidebar, and click on APIs & Services and then the OAuth consent screen. Select External user type and click on CREATE. This will create a new OAuth consent screen. The OAuth consent screen tells users what app is asking for access to their information and what information the app can access:

    Create a new OAuth consent screen

  3. Enter a name for your OAuth consent and the required email addresses; then click SAVE AND CONTINUE. At this point, you'll be shown the scope tab. Select the scopes indicated in the following image and click on the Update button to save it:

    Select scopes

  4. Add the email that you want to use to test the consent screen in the Test users section:

    Test users section

  5. Click on APIs & Services on the sidebar again, and then select Credentials. Click on the CREATE CREDENTIALS button and then select OAuth client ID:

    CREATE CREDENTIALS

  6. Complete the form and click on CREATE when you're done:

    OAuth Credentials screen

    The redirect URI specifies where Google should navigate after the consent screen. This means that the redirect or callback has to be created on the React frontend.

  7. Copy your newly created client ID and secret, and save them somewhere safe. You'll need them later when requesting an authorization code and tokens.

Implement the Node.js Backend

Now that you have your client ID and secret, it's time to implement the backend with Node.js and the Express framework.

To do so, create a new directory (ie standard-auth) to house the backend project:

Then create another directory inside it called server:

Initialize a new project within the server directory:

And install the necessary packages by running this command:

Create a new .env file and add the following to it:

Update the environment variables accordingly.

Create a new server.js file, which is where the server-side code will be stored:

Add the following code to server.js to import all the necessary dependencies and create a config object:

Here, config.authUrl is a link to the OAuth consent screen. It is sent along with some query parameters to the frontend. Then a request is made to config.tokenUrl, along with some query parameters to verify an authorization code.

You need to define the parameters for both URLs by adding the following code to server.js:

Initialize a new Express app:

And add the following middlewares to resolve CORS, parse cookies, and verify authorization, respectively:

At this point, you can start adding endpoints for different tasks.

Add the following endpoint (/auth/url) to return the authorization URL to the frontend:

Then add another endpoint (/auth/token) that will get an authorization code from the frontend and verify it:

If the authorization code is verified (ie exchanged for an access token successfully), a new token is signed for the current user. The signed token will then be set as a cookie that will expire based on the tokenExpiration key in the config object.

Add the /auth/logged_in endpoint to check the logged-in state of a user:

Then add the /auth/logout endpoint to log out a user in session:

This will clear the token cookie, which invalidates a logged-in user's session.

Finally, add the resource endpoint:

This basically fetches posts (resources) and returns them as a response. The middleware for validating user authorization (auth) is used here because only authorized users are allowed to access this endpoint.

Now you need to make the Express app listen on port 5000:

Implement the React Frontend

The easiest way to start a React project is to use boilerplate code. Go to the standard-auth directory and bootstrap a new React project using Create React App:

This will create a client directory with your React project inside it.

Change to the client directory using cd client and install the following packages:

Next, create a .env file in the root directory of your React project:

Open the App.css file in the src directory of your React project and add the following CSS code:

This will help style a button using the btn class.

Update your App.js file to import the necessary method and hooks by adding the following code just above the App component:

After updating the App.js file, you need to create a new React context to hold the logged-in and user states so they can be shared globally. To do so, add the following code just above the App component:

The checkLoginState function in this React context makes a call to your backend's /auth/logged_in endpoint. Here, it's called in a useEffect block to run every time the app initially renders.

Next, add the following Dashboard component just before the App component:

Later, you'll render this component conditional based on the logged-in state of a user.

Add the Login component:

This component renders a button that takes the user to the OAuth consent screen you made earlier.

Do you remember when you provided a callback URL when you created your client ID and secret? Because of this, you need to add a component to handle the callback:

Create a router to define routes that render the components you created earlier:

Finally, update the App component with the following code:

Now, it's time to test out the implementation. Go to your server directory and run the following command to spin up the server:

Open another terminal in your client directory and run this command to spin up your React server:

This command will open up http://localhost:3000 in your default browser. You should see something like this when the server is fully running:

React home

If you click on the login button, you'll be redirected to the OAuth consent screen:

OAuth consent screen

After you're redirected, you'll be logged in and authorized to access the post resources:

Dashboard

If you've followed along, you've officially implemented the OAuth 2.0 authorization code flow in React. Great work!

Authorization with Clerk

As you can see, implementing OAuth 2.0 is complicated and time-consuming. This is where Clerk can help.

Clerk is a service that takes care of user management. This means developers don't have to keep reinventing the wheel and can focus on what they do best. Moreover, Clerk can also take care of authorization.

In this section, you'll see how Clerk can easily be used to replicate the implementation in the previous section.

Before you proceed, you need to have a Clerk account. An account will give you access to both a publishable key and a secret key, as well as other customizations.

If you don't already have an account, go to Clerk's sign-up page and create one:

Clerk sign-up page

After you've signed up, click on Add application to create a new project:

Add a new application on Clerk

Update the settings for your new application to match the settings shown here:

New application settings

When you're done, click on FINISH, and a new application will be created.

Navigate to the API Keys section. Copy your publishable and secret keys, and save them somewhere safe:

Clerk API Keys page

Implement the Node.js Backend

For this Clerk example, you need to rewrite the Node.js implementation you did previously. Update your .env file in the server directory with the following:

Update the environment variable accordingly.

Then run the following command in your server directory to install Clerk's Node.js SDK:

Update your server.js file with the following code:

Here, you're using the ClerkExpressRequireAuth() middleware to allow only authorized access to the /user/posts/ route. It's that easy!

Implement the React Frontend

To implement the React frontend, update the .env file in your client directory with the following:

Remember to update the environment variable accordingly.

Then run the following command in the client directory to install the Clerk React SDK:

Update the App.js file inside the src directory in your client directory with the following code:

Clerk's React SDK exports prebuilt components that are very useful. For instance, the SignedIn component renders its children (in this case, the Dashboard component) only when a user is signed in. The SignedOut component does the opposite.

The RedirectToSignIn component redirects the users to a form where they can choose their authentication method. In this case, the users will be prompted to use their Google account or email address (you set this when creating your Clerk application).

The Dashboard component makes a request to get post resources using the token provided by the useAuth hook from the Clerk SDK.

If you go through the sign-up process, you'll end up with something like this:

Dashboard after Clerk

Standard Authorization vs. Clerk

As you can see, implementing a standard and secure authorization can be difficult, time-consuming, and in some cases, unnecessary. However, you can solve these issues with Clerk, which can help you implement user authentication and authorization with ease.

Clerk does this by providing a range of authentication methods, including social login, password-based, and multifactor authentication. It also gives developers access to a user interface where they can control their applications' authentication and user management settings. Moreover, analytics and reporting capabilities are available to developers to help them keep track of user behavior.

If you enjoyed this article, you might also like our guide to implementing session-based authentication with React and Express.