Skip to content

Commit abe08a0

Browse files
committed
Angular Security course
1 parent 9741f5e commit abe08a0

8 files changed

+95
-23
lines changed

demos/jwt-check-hs256.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@ var jwt = require('jsonwebtoken');
33

44

55
// verify an existing JWT
6-
var existingToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhbGdvcml0aG0iOiJIUzI1NiIsImRhdGEiOnsidXNlcklkIjoxfSwiaWF0IjoxNTAyODgxOTIxfQ.6ayBjYiaTMJ8Z3tYx6VfueFLDN1U8SFl94B7U3ZWO6Q';
6+
var existingToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWxpY2UiLCJpYXQiOjE1MDI4ODkxOTF9._tPQtlZz2GhXHXATn5W09K4XCG0Z5LyEQqikJf3qXF8';
77

88

99
var secretKey = 'secret-key';
1010

1111

1212

13-
const verify = jwt.verify(existingToken, secretKey, {algorithm: 'HS256' });
13+
const verify = jwt.verify(existingToken, secretKey);
1414

1515

1616
console.log("Decoded JWT:", verify);

demos/jwt-check-rs256.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@ var fs = require('fs');
44

55

66
// verify an existing JWT
7-
var existingToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAbWFpbGluYXRvci5jb20iLCJpYXQiOjE1MDI4ODAzODB9.LiZZp_SIy2TApLnJGjWfWhKUU0uc6oh5wJa5gLY4l82cmgB4MGMssxbagaIROmkmSA68tk57YihBmbz7d76lyV1dWw6HAZ6KttvkHnvk8Zyg0QethIG6TYPJ083H_xWUBTDDF-bQCXf3AgELMuKyUWqVONW294tW5n7vKqo41eMx-r372oxHdL9Du_GzZ2LJrWtxPnaIWh5hb0MiPz5KNKlWh0D4MBb-lEkmghc7QE69mIKJ2u3-ZYe_i3KGEclCZArKusmpxfhNbmfvU_JX2kF7ko4HS5qe4a7ZV04Bzgovz5TNZ-13j79jSWpWod3jA_xZZfLfMpgBhteWuxhImw';
7+
var existingToken = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWxpY2UiLCJpYXQiOjE1MDI4OTA4NjYsImV4cCI6MTUwMjg5MDk4Niwic3ViIjoiMSJ9.SkF5CArLIU9A0MeCiv-HOiRctivGESnXHnxGSwc7lx1nBP0-qO7-r3LO4TVLlLydQBce0hQAbiik1lndgiR1V_8TN-dMGcpFYZlSv3gp4cJD5LNxl_fQ9CBhpznkNo6Yuys8DYIfL90uWpm0jjnSJh2hFDxbGwPaXTciJ0Xdj-QLq2hc_jHrRKaWlB6eCbs9P43tfrUw_pXb0lCdYfPMjPLHJMNyZMLxCxExBoHay7UoYDx_cYU-UTR1hQQ2xbHfrA8oMz1fOCjwCChEXuDKVDqOF9W4LhbrdvGmVgv8mvdl72VSHkqH5jWc3vh0u5xJtsMpRBwg0-OBU3hOebtlyg';
88

99

1010
var publicKey = fs.readFileSync('./demos/public.key');
1111

1212

1313
console.log("verifying");
1414

15-
const verify = jwt.verify(existingToken, publicKey, {algorithm: 'RS256' });
15+
const verify = jwt.verify(existingToken, publicKey);
1616

1717

1818

demos/jwt-hs256.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,14 @@ var jwt = require('jsonwebtoken');
66
var secretKey = 'secret-key';
77

88
var payload = {
9-
userId: 1
9+
name: 'Alice'
1010
};
1111

1212

1313
// create a JWT
14-
var newToken = jwt.sign({
15-
algorithm: 'HS256',
16-
data: payload
17-
}, secretKey);
14+
var newToken = jwt.sign(payload, secretKey, {
15+
algorithm: 'HS256'
16+
});
1817

1918
console.log("JWT created:", newToken);
2019

demos/jwt-rs256.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ var fs = require('fs');
66
var privateKey = fs.readFileSync('./demos/private.key');
77

88
var payload = {
9-
userId: 1
9+
name: 'Alice'
1010
};
1111

1212

13-
var token = jwt.sign({
13+
var token = jwt.sign(payload, privateKey, {
1414
algorithm: 'RS256',
15-
data: payload
16-
}, privateKey);
15+
expiresIn: 120,
16+
subject: "1"
17+
});
1718

1819

1920
console.log('RSA 256 JWT', token);

server/auth.middleware.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import {Request, Response, NextFunction} from 'express';
2+
import {isSessionTokenValid} from "./security.utils";
3+
4+
5+
export function retrieveUserIdFromRequest(req: Request, res: Response, next: NextFunction) {
6+
7+
const jwt = req.cookies['SESSIONID'];
8+
9+
if (jwt) {
10+
handleSessionCookie(jwt, req, next);
11+
}
12+
else {
13+
next();
14+
}
15+
}
16+
17+
async function handleSessionCookie(jwt, req: Request, next: NextFunction) {
18+
try {
19+
20+
const token = await isSessionTokenValid(jwt);
21+
22+
console.log("decoded token", token);
23+
24+
req['userId'] = token.sub;
25+
26+
}
27+
catch (error) {
28+
console.error("Error: Could not extract user from request");
29+
}
30+
finally {
31+
next();
32+
}
33+
}
34+
35+
36+
export function checkIfAuthenticated(req: Request, res: Response, next: NextFunction) {
37+
38+
console.log("Calling check if authenticated ...");
39+
40+
next();
41+
42+
}

server/get-user.route.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ import {Request, Response} from "express";
66

77
export function getUser(req:Request, res:Response) {
88

9-
const sessionId = req.cookies['SESSIONID'];
9+
const userId = req.cookies['SESSIONID'];
1010

1111
//TODO
12-
const user = {};
12+
const user = {email:'test@gmail.com'};
1313

1414

1515
if (user) {

server/security.utils.ts

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,42 @@ import * as fs from "fs";
1111

1212
const RSA_PRIVATE_KEY = fs.readFileSync('./demos/private.key');
1313

14+
const RSA_PUBLIC_KEY = fs.readFileSync('./demos/public.key');
15+
16+
17+
1418
export const randomBytes = util.promisify(crypto.randomBytes);
1519

1620

1721

1822
export async function createSessionToken(userId:number) {
1923
return jwt.sign(
24+
{
25+
},
26+
RSA_PRIVATE_KEY,
2027
{
2128
algorithm: 'RS256',
22-
exp: (moment().add(2,"minutes").toDate().getTime() / 1000),
23-
subject: userId
24-
}, RSA_PRIVATE_KEY);
25-
}
29+
expiresIn: 120,
30+
subject: '' + userId
31+
});
32+
}
33+
34+
35+
export async function isSessionTokenValid(sessionToken:string) {
36+
37+
console.log("validating token", sessionToken);
38+
39+
const verify = await jwt.verify(sessionToken, RSA_PUBLIC_KEY);
40+
41+
console.log("decoded token", verify);
42+
43+
return verify;
44+
}
45+
46+
47+
48+
49+
50+
51+
52+

server/server.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,17 @@ import {createUser} from "./create-user.route";
99
import {getUser} from "./get-user.route";
1010
import {logout} from "./logout.route";
1111
import {login} from "./login.route";
12+
import {checkIfAuthenticated, retrieveUserIdFromRequest} from "./auth.middleware";
1213
const bodyParser = require('body-parser');
1314
const cookieParser = require('cookie-parser');
1415

1516

1617
const app: Application = express();
1718

18-
app.use(bodyParser.json());
1919
app.use(cookieParser());
20+
app.use(retrieveUserIdFromRequest);
21+
app.use(bodyParser.json());
22+
2023

2124
const commandLineArgs = require('command-line-args');
2225

@@ -29,16 +32,16 @@ const options = commandLineArgs(optionDefinitions);
2932

3033
// REST API
3134
app.route('/api/lessons')
32-
.get(readAllLessons);
35+
.get(checkIfAuthenticated, readAllLessons);
3336

3437
app.route('/api/signup')
3538
.post(createUser);
3639

3740
app.route('/api/user')
38-
.get(getUser);
41+
.get(checkIfAuthenticated, getUser);
3942

4043
app.route('/api/logout')
41-
.post(logout);
44+
.post(checkIfAuthenticated, logout);
4245

4346
app.route('/api/login')
4447
.post(login);

0 commit comments

Comments
 (0)