Implementing JWT
Server-Side Implementationβ
Libraries and Tools:
- Node.js:
jsonwebtoken
library - Python:
PyJWT
library - Java:
jjwt
library - Ruby:
jwt
gem
Example Code Snippets
- JavaScript
- Python
- Java
- Ruby
- Output
Creating a Token (Node.js using jsonwebtoken
):
-
Install the library:
npm install jsonwebtoken
-
Code to create a token:
const jwt = require('jsonwebtoken');
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true
};
const secret = "your-256-bit-secret";
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log(token);
Verifying a Token (Node.js using jsonwebtoken
):
- Code to verify a token:
const jwt = require('jsonwebtoken');
const token = "your.jwt.token.here";
const secret = "your-256-bit-secret";
try {
const decoded = jwt.verify(token, secret);
console.log(decoded);
} catch (err) {
console.error('Token verification failed:', err);
}
Installationβ
First, you need to install the PyJWT library if you haven't already:
pip install pyjwt
Creating (Encoding) a Tokenβ
To create a JWT, you need a payload (data) and a secret key. The payload typically contains claims about the user and any additional metadata.
import jwt
import datetime
# Define the payload
payload = {
'user_id': 123,
'username': 'example_user',
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) # Token expiration time
}
# Define the secret key
secret_key = 'your_secret_key'
# Create the token
token = jwt.encode(payload, secret_key, algorithm='HS256')
print(f"Generated Token: {token}")
Verifying (Decoding) a Tokenβ
To verify a JWT, you need the token and the same secret key that was used to create the token. If the token is valid and has not expired, you can decode it to retrieve the payload.
# Define the token you received
received_token = token
# Decode the token
try:
decoded_payload = jwt.decode(received_token, secret_key, algorithms=['HS256'])
print(f"Decoded Payload: {decoded_payload}")
except jwt.ExpiredSignatureError:
print("Token has expired")
except jwt.InvalidTokenError:
print("Invalid token")
Setupβ
First, add the jjwt
library to your project. If you're using Maven, add the following dependency to your pom.xml
:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version> <!-- Check for the latest version -->
</dependency>
If you're using Gradle, add the following to your build.gradle
:
implementation 'io.jsonwebtoken:jjwt:0.9.1' // Check for the latest version
Creating (Encoding) a Tokenβ
Hereβs how to create a JWT using jjwt
:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtExample {
private static final String SECRET_KEY = "your_secret_key";
public static String createToken(String userId, String username) {
return Jwts.builder()
.setSubject(userId)
.claim("username", username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000)) // 30 minutes expiration
.signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes())
.compact();
}
public static void main(String[] args) {
String token = createToken("123", "example_user");
System.out.println("Generated Token: " + token);
}
}
Verifying (Decoding) a Tokenβ
To verify and decode a JWT, use the following code:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
public class JwtExample {
private static final String SECRET_KEY = "your_secret_key";
public static Claims decodeToken(String token) {
try {
return Jwts.parser()
.setSigningKey(SECRET_KEY.getBytes())
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
System.out.println("Token has expired");
} catch (SignatureException e) {
System.out.println("Invalid token");
}
return null;
}
public static void main(String[] args) {
String token = createToken("123", "example_user");
System.out.println("Generated Token: " + token);
Claims claims = decodeToken(token);
if (claims != null) {
System.out.println("Decoded Claims: " + claims);
}
}
}
Installationβ
First, add the jwt
gem to your Gemfile:
gem 'jwt'
Then run:
bundle install
Alternatively, you can install it directly using:
gem install jwt
Creating (Encoding) a Tokenβ
To create a JWT, you need a payload (data) and a secret key. The payload can contain any data you need to include in the token, such as user information or claims.
require 'jwt'
# Define the payload
payload = {
user_id: 123,
username: 'example_user',
exp: Time.now.to_i + 30 * 60 # Token expiration time (30 minutes from now)
}
# Define the secret key
secret_key = 'your_secret_key'
# Create the token
token = JWT.encode(payload, secret_key, 'HS256')
puts "Generated Token: #{token}"
Verifying (Decoding) a Tokenβ
To verify a JWT, use the same secret key that was used to create the token. If the token is valid and has not expired, you can decode it to retrieve the payload.
require 'jwt'
# Define the token you received
received_token = token
# Define the secret key
secret_key = 'your_secret_key'
# Decode the token
begin
decoded_payload = JWT.decode(received_token, secret_key, true, { algorithm: 'HS256' })
puts "Decoded Payload: #{decoded_payload.first}"
rescue JWT::ExpiredSignature
puts "Token has expired"
rescue JWT::DecodeError
puts "Invalid token"
end
How to Created in the Token Backend Basic Exampleβ
Client-Side Implementationβ
Storing the Token Securely:
-
localStorage:
localStorage.setItem('token', token);
const token = localStorage.getItem('token'); -
sessionStorage:
sessionStorage.setItem('token', token);
const token = sessionStorage.getItem('token'); -
Cookies (Using
js-cookie
library):-
Install the library:
npm install js-cookie
-
Code to store and retrieve the token:
const Cookies = require('js-cookie');
// Set a cookie
Cookies.set('token', token, { expires: 1 }); // 1 day expiration
// Get a cookie
const token = Cookies.get('token');
-
Sending the Token in Requests (Authorization Header):
-
Using Fetch API:
const token = localStorage.getItem('token');
fetch('https://your-api-endpoint.com', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error)); -
Using Axios:
-
Install Axios:
npm install axios
-
Code to send a request with token:
const axios = require('axios');
const token = localStorage.getItem('token');
axios.get('https://your-api-endpoint.com', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
-
Example:β
Backend
backend listen in 5000..
Frontend
Get to the data in backend use JWT