Skip to content

Instantly share code, notes, and snippets.

@deepaksood619
Last active May 16, 2020 14:42
Show Gist options
  • Save deepaksood619/4cc5656a42158927ca6006a1ec7d5eea to your computer and use it in GitHub Desktop.
Save deepaksood619/4cc5656a42158927ca6006a1ec7d5eea to your computer and use it in GitHub Desktop.
JWT in node demo
// https://blog.bitsrc.io/understanding-json-web-token-authentication-a1febf0e15
const express = require("express");
const expressjwt = require("express-jwt");
const bodyParser = require("body-parser");
const app = express();
const PORT = process.env.API_PORT || 5555;
const jwtCheck = expressjwt({
secret: "mykey"
});
app.use(bodyParser.json());
app.get("/asset/secret", jwtCheck, (req, res) => {
res.status(200).send("Only logged in people can see me");
});
app.get("/asset", (req, res) => {
res.status(200).send("Everybody can see this");
});
app.get("*", (req, res) => {
res.sendStatus(404);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
// https://blog.bitsrc.io/understanding-json-web-token-authentication-a1febf0e15
const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const cors = require("cors");
const app = express();
const PORT = 8888;
const users = [
{id: 1, username: "clarkKent", password: "superman"},
{id: 2, username: "bruceWayne", password: "batman"}
];
app.use(bodyParser.json());
app.use(cors());
app.get('/time', (req, res) => {
const time = (new Date()).toLocaleTimeString();
res.status(200).send(`The Time is ${time}`);
});
app.get("*", (req, res) => {
res.sendStatus(404);
});
app.post("/login", (req, res) => {
if (!req.body.username || !req.body.password) {
res.status(400).send("Error. Please enter the correct username and password");
return;
}
const user = users.find((u) => {
return u.username === req.body.username && u.password === req.body.password;
});
if (!user) {
res.status(401).send("User not found in database");
return;
}
const token = jwt.sign({
sub: user.id,
username: user.username
}, "mykey", {expiresIn: "10 sec"});
res.status(200).send({access_token: token})
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment