Keywords: jQuery | AJAX | JWT | express-jwt | localStorage
Abstract: This article provides a detailed explanation of how to send JWT tokens from localStorage using jQuery AJAX. It covers setting the Authorization header, integrating with express-jwt middleware for backend validation, and includes code examples and security best practices.
Introduction
In modern web development, JSON Web Tokens (JWT) are commonly used for user authentication and authorization. When developing frontends with jQuery, sending JWT tokens via AJAX requests is a frequent requirement. This article details how to store and send tokens from localStorage.
Storing Tokens in localStorage
First, upon successful login, JWT tokens are typically stored in the client's localStorage. For example:
$.ajax({
url: "http://localhost:8080/login",
type: 'POST',
data: formData,
error : function(err) {
console.log('Error!', err);
},
success: function(data) {
console.log('Success!');
localStorage.setItem('token', data.id_token);
}
});This code stores the token in localStorage after a successful response for later use.
Sending Tokens in AJAX Requests
For protected routes, tokens need to be sent in the request headers. Using jQuery's $.ajax function, the headers property can be set:
$.ajax({
url: "http://localhost:8080/upload",
type: 'GET',
headers: {"Authorization": localStorage.getItem('token')}
});Here, the token is retrieved from localStorage and set as the Authorization header, ensuring the request is properly validated by the backend.
Backend Validation with express-jwt
On the Express.js backend, the express-jwt middleware is used to protect routes:
app.get('/upload', jwt({secret: config.secret}), function(req, res) {
res.sendFile(path.join(__dirname + '/upload.html'));
});This middleware automatically validates the JWT token in the request header, returning an error response if invalid.
Code Examples and Explanation
The code above illustrates the complete workflow. First, the user logs in and stores the token; then, when accessing protected resources, a request with the token is sent; finally, the backend validates the token and responds. This approach simplifies authentication and enhances application security.
Best Practices and Security Considerations
It is recommended to use HTTPS to encrypt transmission and prevent token interception. Additionally, regularly refresh tokens and set appropriate expiration times. Ensure tokens in localStorage are cleared at the end of user sessions to mitigate cross-site scripting (XSS) attacks.
Conclusion
By combining localStorage, jQuery AJAX, and express-jwt, efficient JWT authentication between frontend and backend can be achieved. This method is simple, secure, and represents a standard practice in modern web applications, suitable for projects of various scales.