07: "Sessions" with JWT
Find user by email
Compare passwords
Generate token
Respond with token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InZhbGlkVXNlcm5hbWUifQ.N5ppD4k72pbST4_DESbHzqjrFCZK4QEzhGHI0H49GtM
header: { "typ": "JWT", "alg": "HS256" }
payload: { "username": "validUsername" }
<signature>
signature = HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload) +
<secret>)
const jwt = require('jwt-simple');
const secret = 'some top secret string';
const payload = {
username: 'theneva',
};
// Token for sending
const signedToken = jwt.encode(payload, secret);
console.log(signedToken); // eyJ0eXAiOiJKV1QiLC…
// Decode the token using the secret
const decodedPayload = jwt.decode(signedToken, secret);
console.log(decodedPayload); // { username: 'theneva' }There's a package for that!
jwt-simple to the rescue
const app = require('express')();
const jwt = require('jwt-simple');
app.post('/sessions', (req, res) => {
// get and validate login info
if (invalid) {
// respond with 401 unauthorized
} else {
// encode jwt with payload & sign with secret
// return the jwt
}
});
app.get('/user', (req, res) => {
// verify & decode jwt
// get jwt payload username
// retrieve user by username from DB
// return user info
});
app.listen(1234, () => console.log('listening on port 1234'));Example
// Store
localStorage.token = 'something';
// Get
const token = localStorage.token;function authenticate() {
const url = api + '/authenticate';
const body = {
username: 'blah',
password: 'glola'
};
fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body),
})
.then(res => res.text())
.then(token => localStorage.token = token);
}
function getWithToken(url) {
return fetch(url, {
headers: {
'X-Token': localStorage.token
}
});
}THIS IS PLAIN JS!
const bcrypt = require('bcryptjs');
const password = 'ananas';
const passwordHash = bcrypt.hashSync(password, 10);
console.log(password + ' -> ' + passwordHash);
const isMatch = bcrypt.compareSync(password, passwordHash);
console.log(isMatch);