Skip to content

Commit cca3288

Browse files
committed
Update README.md
1 parent 6a147b7 commit cca3288

File tree

1 file changed

+1
-135
lines changed

1 file changed

+1
-135
lines changed

README.md

Lines changed: 1 addition & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -1404,18 +1404,6 @@ Please note - before pid. This converts a pid to a group of pids for process kil
14041404

14051405
<br/>
14061406

1407-
## Q. How can you listen on port 80 with Node?
1408-
1409-
Instead of running on port 80 we can redirect port 80 to your application\'s port (>1024) using
1410-
1411-
```bash
1412-
iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3000
1413-
```
1414-
1415-
<div align="right">
1416-
<b><a href="#table-of-contents">↥ back to top</a></b>
1417-
</div>
1418-
14191407
## Q. How to use JSON Web Token (JWT) for authentication in Node.js?
14201408

14211409
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
@@ -1425,7 +1413,7 @@ There are some advantages of using JWT for authorization:
14251413
* Purely stateless. No additional server or infra required to store session information.
14261414
* It can be easily shared among services.
14271415

1428-
JSON Web Tokens consist of three parts separated by dots (.), which are:
1416+
**Syntax:**
14291417

14301418
```js
14311419
jwt.sign(payload, secretOrPrivateKey, [options, callback])
@@ -1501,128 +1489,6 @@ The `jwt.sign()` method takes a payload and the secret key defined in `config.js
15011489
<b><a href="#table-of-contents">↥ back to top</a></b>
15021490
</div>
15031491

1504-
## Q. How to implement asymmetric cryptography when signing and verify JSON Web Token (JWT) for authentication in Node.js?
1505-
1506-
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
1507-
1508-
There are some advantages of using JWT for authorization:
1509-
1510-
- Purely stateless. No additional server or infra required to store session information.
1511-
- It can be easily shared among services.
1512-
1513-
**Syntax:**
1514-
1515-
```js
1516-
jwt.sign(payload, secretOrPrivateKey, [options, callback]);
1517-
```
1518-
1519-
**1. Header** - Consists of two parts: the type of token (i.e., JWT) and the signing algorithm (i.e., HS512)
1520-
1521-
**2. Payload** - Contains the claims that provide information about a user who has been authenticated along with other information such as token expiration time.
1522-
1523-
**3. Signature** - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret
1524-
1525-
**Installation:**
1526-
1527-
```bash
1528-
npm install jsonwebtoken bcryptjs --save
1529-
```
1530-
1531-
**Usage:**
1532-
1533-
1. `mkdir certs` then run `cd certs`
1534-
1535-
**Inside the certs folder generate public and private key pairs:**
1536-
1537-
```bash
1538-
// Private Key
1539-
>> openssl genrsa -out accessTokenPrivatekey.pem 4096
1540-
1541-
// Public Key
1542-
>> openssl rsa -pubout -in accessTokenPrivatekey.pem -out accessTokenPublickey.pem
1543-
```
1544-
1545-
**Example**:
1546-
1547-
```js
1548-
/**
1549-
* AuthController.js
1550-
*/
1551-
const express = require('express');
1552-
const router = express.Router();
1553-
const bodyParser = require('body-parser');
1554-
const { readFileSync } = require('fs');
1555-
const User = require('../user/User');
1556-
1557-
const jwt = require('jsonwebtoken');
1558-
const bcrypt = require('bcryptjs');
1559-
const config = require('../config');
1560-
1561-
router.use(bodyParser.urlencoded({ extended: false }));
1562-
router.use(bodyParser.json());
1563-
1564-
router.post('/register', function (req, res) {
1565-
const hashedPassword = bcrypt.hashSync(req.body.password, 8);
1566-
1567-
User.create(
1568-
{
1569-
name: req.body.name,
1570-
email: req.body.email,
1571-
password: hashedPassword,
1572-
},
1573-
(err, user) => {
1574-
if (err) {
1575-
return res.status(500).send('There was a problem registering the user.');
1576-
}
1577-
1578-
// Using the fs module get the private key of the accesstoken you created.
1579-
const ACCESS_TOKEN_PRIV_KEY = readFileSync(
1580-
'./certs/accessTokenPrivateKey.pem',
1581-
'utf8'
1582-
);
1583-
1584-
// Create an access token using the private key pair, and specify the algorithm you will use.
1585-
const token = jwt.sign({ id: user._id }, ACCESS_TOKEN_PRIV_KEY, {
1586-
algorithm: 'RS256',
1587-
expiresIn: 86400, // expires in 24 hours
1588-
});
1589-
res.status(200).send({ auth: true, token: token });
1590-
}
1591-
);
1592-
});
1593-
```
1594-
1595-
**To verify a token use the public key:**
1596-
1597-
```js
1598-
const ACCESS_TOKEN_PUB_KEY = readFileSync(
1599-
'./certs/accessTokenPubliKey.pem',
1600-
'utf-8'
1601-
);
1602-
1603-
/** Use the Access token Public Key to verify the JWT access token */
1604-
jwt.verify(
1605-
token,
1606-
ACCESS_TOKEN_PUB_KEY,
1607-
{ algorithms: ['RS256'] },
1608-
(err, user) => {
1609-
console.log(err);
1610-
if (err) res.status(403);
1611-
console.log(user);
1612-
}
1613-
);
1614-
```
1615-
1616-
The `jwt.sign()` method takes a payload, private key defined in `./certs/accessTokenPrivateKey.pem` and an object which contains other information about the token, this includes the algorithm `{ algorithm: 'RS256'}`. It creates a unique string of characters representing the payload.
1617-
1618-
**Reference:**
1619-
1620-
* *[https://www.npmjs.com/package/jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)*
1621-
1622-
<div align="right">
1623-
<b><a href="#table-of-contents">↥ back to top</a></b>
1624-
</div>
1625-
16261492
## Q. How to build a microservices architecture with Node.js?
16271493

16281494
Microservices are a style of **Service Oriented Architecture (SOA)** where the app is structured on an assembly of interconnected services. With microservices, the application architecture is built with lightweight protocols. The services are finely seeded in the architecture. Microservices disintegrate the app into smaller services and enable improved modularity.

0 commit comments

Comments
 (0)