Created
July 12, 2019 22:33
-
-
Save danman113/9adb2952c244dcc857e492619deea780 to your computer and use it in GitHub Desktop.
JWT Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
secret: 'hellowthisismyskret', | |
port: process.env.PORT || 9001, | |
users: [['test', 'tester'], ['daniel', 'wordpass']] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jwt = require('jsonwebtoken') | |
const config = require('./config') | |
const app = require('express')() | |
const tokenMiddleware = (req, res, next) => { | |
const authHeader = req.headers['authorization'] | |
let token | |
if (authHeader && authHeader.startsWith('Bearer ')) token = authHeader.slice(7, authHeader.length) | |
if (token) { | |
jwt.verify(token, config.secret, {}, (err, decoded) => { | |
if (err) return next(err) | |
req.decoded = decoded | |
return next() | |
}) | |
} else { | |
return next(new Error('Could not find token')) | |
} | |
} | |
const loginController = (req, res) => { | |
const { | |
username = '', | |
password = '' | |
} = req.query | |
const requestedUser = config.users.find(usr => usr[0] === username) | |
if (requestedUser && requestedUser[1] === password) { | |
const token = jwt.sign({ username }, config.secret, { | |
expiresIn: '12s' | |
}) | |
res.json({ token }) | |
} else { | |
next(new Error('No user found with those credentials')) | |
} | |
} | |
app.get('/', (req, res) => res.send('hello world')) | |
app.get('/api/login', loginController) | |
app.get('/api/test', tokenMiddleware, (req, res) => { | |
res.send({ decoded: req.decoded.username }) | |
}) | |
app.use('/api', (err, req, res, next) => { | |
if (err) res.status(403).send({ error: err.toString()}) | |
}) | |
app.listen(config.port, () => console.log(`Now listening on port ${config.port}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment