






















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.
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:
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:

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.
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:
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.
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.
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.
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 define the entities in an OAuth 2.0 flow, and there are four major roles:
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.
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.
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.
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:

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:
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!
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:
Name it. In this example, it's "standard-auth".
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:
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:
Add the email that you want to use to test the consent screen in the Test users section:
Click on APIs & Services on the sidebar again, and then select Credentials. Click on the CREATE CREDENTIALS button and then select OAuth client ID:
Complete the form and click on CREATE when you're done:

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.
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.
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:
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:

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

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

If you've followed along, you've officially implemented the OAuth 2.0 authorization code flow in React. Great work!
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:

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

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

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:

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!
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:

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.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。