logo

React JWT Example: Integrating React.js and JSON Web Tokens in Isomorphic Applications

作者:公子世无双2024.01.29 22:03浏览量:5

简介:Learn how to integrate JSON Web Tokens (JWT) with React.js in an isomorphic application, including authentication, authorization, and token storage. This article assumes a basic understanding of React and JWT.

React.js is a popular JavaScript library for building user interfaces, and JSON Web Tokens (JWT) are a secure way to authenticate and authorize users in web applications. Integrating these two technologies in an isomorphic application allows you to share code between the client and server, improving maintainability and reducing重复的工作量. In this example, we’ll demonstrate how to set up an isomorphic React application with JWT authentication, authorization, and token storage.
First, make sure you have Node.js and npm installed on your machine. Then, follow these steps to create a new React application with JWT integration:
Step 1: Set up the Project
Open a terminal and navigate to the directory where you want to create your project. Run the following commands:

  1. npx create-react-app my-react-jwt-app
  2. cd my-react-jwt-app

Step 2: Install Dependencies
Next, you’ll need to install the necessary dependencies for JWT integration. Run the following command:

  1. npm install --save jsonwebtoken express express-jwt jwks-rsa

These dependencies will provide the functionality for handling JWTs on the server-side.
Step 3: Configure Server-Side JWT Middleware
Open the server.js file located in the src directory and add the following code:

  1. const express = require('express');
  2. const jwt = require('jsonwebtoken');
  3. const jwksRsa = require('jwks-rsa');
  4. const app = express();
  5. // Middleware for protecting routes that require authentication
  6. function authenticateToken(req, res, next) {
  7. const authHeader = req.headers['authorization'];
  8. const token = authHeader && authHeader.split(' ')[1]; // Extract token from header
  9. if (token == null) return res.sendStatus(401); // Token not found, return 401 Unauthorized status
  10. try {
  11. // Verify the token using the JWKs (JSON Web Key Set) endpoint provided by your identity provider (e.g., Auth0)
  12. const decoded = jwt.verify(token, process.env.JWT_SECRET); // Replace process.env.JWT_SECRET with your actual JWT secret key
  13. req.user = decoded; // Attach the decoded user data to the request object for further use in your application logic
  14. next(); // All checks passed, continue to the next middleware or route handler
  15. } catch (err) {
  16. res.sendStatus(403); // Token is invalid or expired, return 403 Forbidden status
  17. }
  18. }

In this code, we define a middleware function called authenticateToken that checks for an authentication token in the request headers. If a valid token is found, it will be decoded using the JWKs provided by your identity provider (e.g., Auth0). The decoded user data is then attached to the request object for further use in your application logic. If no token is found or if the token is invalid or expired, a 401 or 403 status code is returned accordingly.
Step 4: Create a Route Handler for User Authentication
Next, you’ll need to create a route handler for user authentication. Open the App.js file located in the src directory and replace the existing code with the following:
```javascript
import React from ‘react’;
import { useNavigate } from ‘react-router-dom’;
import axios from ‘axios’; // HTTP client for making API requests
import { Link } from ‘react-router-dom’; // Router Link component for navigation
import { loginUser } from ‘./api/auth’; // Import your authentication API endpoint function (to be implemented later)
function App() {
const navigate = useNavigate(); // Hook for router navigation logic (to be implemented later)
const handleLogin = async (event) => {
event.preventDefault(); // Prevent form submission by default behavior
const { username, password } = event.target; // Extract form values from event object
try {
// Call your authentication API endpoint function to obtain a JWT (to be implemented later)
const response = await loginUser(username.value, password.value); // Replace loginUser

相关文章推荐

发表评论

活动