Skip to content

Instantly share code, notes, and snippets.

@dominsights
Last active March 28, 2019 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dominsights/485db2b0a1472fbf0e7be891e53af33f to your computer and use it in GitHub Desktop.
Save dominsights/485db2b0a1472fbf0e7be891e53af33f to your computer and use it in GitHub Desktop.
Example of implementing a JWT token (login page) using node.js, express and Angular. You'll need the proxy.conf.json to run Angular and node in the same machine (to be able to access /api/login). Use ng serve --proxy-config proxy.conf.json -o.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { shareReplay, tap, catchError } from 'rxjs/operators';
import * as moment from "moment";
import { User } from './User';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {
}
login(user: User) {
if (user.name !== '' && user.password !== '') {
//Verify if response is valid ???
return this.http.post<User>('/api/login', user)
.pipe(
tap(this.setSession),
shareReplay()
);
}
}
logout() {
localStorage.removeItem("token");
localStorage.removeItem("expires_at");
}
public isLoggedIn() {
return moment().isBefore(this.getExpiration());
}
isLoggedOut() {
return !this.isLoggedIn();
}
getExpiration() {
const expiration = localStorage.getItem("expires_at");
const expiresAt = JSON.parse(expiration);
return moment(expiresAt);
}
private setSession(authResult) {
const expiresAt = moment().add(authResult.expiresIn, 'second');
localStorage.setItem('token', authResult.token);
localStorage.setItem('expires_at', JSON.stringify(expiresAt.valueOf()));
}
}
const express = require('express');
const fs = require('fs');
var _ = require("lodash");
var bodyParser = require("body-parser");
var jwt = require("jsonwebtoken");
var expressJwt = require('express-jwt');
var users = [
{
id: 1,
name: 'jonathanmh',
password: '%2yx4'
},
{
id: 2,
name: 'test',
password: 'test'
}
];
var privateKey = fs.readFileSync('./private.key', 'utf8');
var publicKey = fs.readFileSync('./public.key', 'utf8');
const checkIfAuthenticated = expressJwt({
secret: publicKey
});
var signOptions = {
expiresIn: "30d",
algorithm: 'RS256'
};
// Express
const app = express();
//parse usual forms
app.use(bodyParser.urlencoded({
extended: true
}));
//parse json for APIs
app.use(bodyParser.json());
app.get('/api', (req, res) => {
res.send({ hi: 'there' });
});
app.post('/api/login', function (req, res) {
if (req.body.name && req.body.password) {
var name = req.body.name;
}
var user = users[_.findIndex(users, { name: name })];
if (!user) {
res.status(401).json({ message: 'no such user found' });
}
if (user.password === req.body.password) {
var payload = { id: user.id };
var token = jwt.sign(payload, privateKey, signOptions);
res.json({
message: 'ok',
token: token,
expiresIn: jwt.decode(token).exp
});
} else {
res.status(401).json({ message: 'password did not match' });
}
});
app.route('/api/secret')
.get(checkIfAuthenticated, function (req, res) {
res.json({ message: "Success! You can not see this without a token" });
})
const PORT = process.env.PORT || 5000;
app.listen(PORT, function () {
console.log("Express running")
});
{
"/api/*": {
"target": "http://localhost:5000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
@jsbimra
Copy link

jsbimra commented Feb 28, 2019

How we can create private.key and public.key on windows, what does it would hold basically?

@bart314
Copy link

bart314 commented Mar 28, 2019

@jsbimra: You could use a site like csfieldguide to create both the public and the private keys. Just copy-paste them using your favorite (Windows)-editor. Those files would hold the public and private keys of the asymmetric encryption that is being used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment