📝 Notes: JWT and OAuth
🛡️ 1. JWT (JSON Web Token)
🔑 What is JWT?
JWT is a compact and self-contained way to represent information between two parties as a JSON object. It's commonly used for authentication and authorization purposes in web applications.
💡 How JWT Works:
- Header: Contains metadata about the token (e.g., signing algorithm).
- Payload: Contains claims, or the information you want to transmit (e.g., user info, permissions).
- Signature: Ensures the token has not been tampered with.
Example of JWT structure:
Header:
{
"alg": "HS256",
"typ": "JWT"
}
Payload:
{
"user_id": 123,
"role": "admin",
"exp": "timestamp"
}
Signature:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
🔑 JWT Example Code (Node.js):
const jwt = require('jsonwebtoken');
// Creating a JWT
const token = jwt.sign({ userId: 123, role: 'admin' }, 'your-secret-key', { expiresIn: '1h' });
console.log('JWT:', token);
// Verifying the JWT
jwt.verify(token, 'your-secret-key', (err, decoded) => {
if (err) {
console.log('Token is invalid or expired');
} else {
console.log('Decoded JWT:', decoded);
}
});
✅ Advantages of JWT:
- Stateless: The server does not need to store session data.
- Compact: Smaller in size, thus reducing overhead.
- Secure: Can be encrypted and signed.
🔑 2. OAuth (Open Authorization)
🛠️ What is OAuth?
OAuth is an open standard for access delegation commonly used for token-based authentication and authorization in web applications. It allows users to grant third-party services limited access to their resources without sharing their credentials.
💡 How OAuth Works:
- Authorization Code Grant: The user authorizes the client to access their data.
- Access Token: The client gets an access token to access resources.
- Refresh Token: Used to get a new access token when the old one expires.
Example of OAuth flow:
- User clicks on "Login with Google" on a website.
- Website redirects to Google's OAuth server.
- User grants permission to the website to access their Google profile.
- Google redirects back with an authorization code.
- Website exchanges the code for an access token and refresh token.
- Website uses the access token to fetch data from the user's Google profile.
🔑 OAuth Example Code (Node.js with Passport.js):
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: 'your-client-id',
clientSecret: 'your-client-secret',
callbackURL: 'http://localhost:3000/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
console.log('User Profile:', profile);
return done(null, profile);
}));
// Express route for Google login
app.get('/auth/google', passport.authenticate('google', {
scope: ['https://www.googleapis.com/auth/plus.login']
}));
// Google callback route
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => {
res.redirect('/profile');
});
✅ Advantages of OAuth:
- Delegated Access: Users can share their data without revealing credentials.
- Granular Permissions: Clients can request limited access, rather than full access.
- Secure: Avoids sharing passwords by using tokens.
🤔 Difference Between JWT and OAuth
| Feature | JWT | OAuth | |---------------------|-------------------------------------------------|------------------------------------------------| | Purpose | Authentication token format. | Authorization protocol. | | Usage | Used to authenticate users. | Used to authorize third-party access. | | Token Type | Single token (JWT). | Access token and refresh token. | | Stateful/Stateless | Stateless (self-contained). | Can be stateful (requires a server-side session). | | Token Storage | Stored in localStorage, cookies, etc. | Stored by authorization server. |
📊 Conclusion:
- JWT is a compact, self-contained method for transmitting information between two parties.
- OAuth is a protocol for authorization that allows users to grant access to third-party services securely without sharing credentials.