JWT token
- React Native course
- Advanced
- Lesson 45/83
- 5 min
Learn JWT token management.
What is JWT?
A JWT (JSON Web Token) is a token given by the server after authentication. It has three parts: header.payload.signature. Each part is separated by a dot and base64 encoded. JWT is stateless; the server does not need to keep a session.
The header carries the signing algorithm (e.g. HS256). The payload carries claim information about the user: sub (user id), exp (expiry time). The signature is header and payload signed with a secret key. The app sends this token with every request.
Store and send the token
After login the token is written to expo-secure-store. You write it with await SecureStore.setItemAsync('token', token) and read it with getItemAsync('token'). When making an API request you add it to the Authorization header with the Bearer prefix.
Example header: Authorization: Bearer eyJhbGciOi.... The Bearer prefix marks the JWT bearer format. The server verifies the signature to identify the user. When the token expires you must log in again; the exp claim marks this.
Practice Build the Authorization header
Complete the authHeader function. Take the token and return { Authorization: \`Bearer ${token}\` }. If the token is empty return an empty object.
Starter code
export function authHeader(token) {
// return the Authorization header
}Sample solution
export function authHeader(token) {
if (!token) return {};
return { Authorization: `Bearer ${token}` };
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many parts does a JWT have?
- Three: header, payload, signature
- Two: user and password Correct answer
- Four: header, body, footer, signature
- One: only signature
Explanation: A JWT has three parts: header, payload, signature.
2 Match the JWT parts
| Term | Meaning |
|---|---|
header |
Signing algorithm |
payload |
User claims |
signature |
Signature with secret key |
exp |
Expiry time |
3 Write the Authorization prefix
headers: { Authorization: `____ ${token}` }
headers: { Authorization: `Bearer ${token}` }
Explanation: Bearer is the JWT bearer prefix.