Skip to content

Commit

Permalink
Merge pull request #4 from buccfer/docs-improvements
Browse files Browse the repository at this point in the history
Docs improvements
  • Loading branch information
buccfer authored Jul 27, 2019
2 parents 2a30a29 + 4ef3a68 commit e832c71
Show file tree
Hide file tree
Showing 10 changed files with 151 additions and 50 deletions.
8 changes: 7 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,10 @@ jobs:
local_dir: out
target_branch: gh-pages
keep_history: false
committer_from_gh: true
committer_from_gh: true
- stage: Deploy to NPM
if: branch = master
deploy:
provider: npm
email: [email protected]
api_key: $NPM_AUTH_TOKEN
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# AWS Cognito Express

[![NPM](https://nodei.co/npm/aws-cognito-express.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/aws-cognito-express/)

[![Build Status](https://travis-ci.org/buccfer/aws-cognito-express.svg?branch=master)](https://travis-ci.org/buccfer/aws-cognito-express)
[![Maintainability](https://api.codeclimate.com/v1/badges/8d53f5de9594eab264e2/maintainability)](https://codeclimate.com/github/buccfer/aws-cognito-express/maintainability)
[![Coverage Status](https://coveralls.io/repos/github/buccfer/aws-cognito-express/badge.svg?branch=master)](https://coveralls.io/github/buccfer/aws-cognito-express?branch=master)
Expand All @@ -18,7 +20,7 @@ It implements the [AWS Guideline for JWT validation](https://docs.aws.amazon.com
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Documentation](https://buccfer.github.io/aws-cognito-express)
- [Documentation](https://buccfer.github.io/aws-cognito-express/tutorial-01-quick-start.html)
- [Releases](https://github.com/buccfer/aws-cognito-express/wiki/Changelog)
- [Responsible disclosure](#responsible-disclosure)

Expand Down
3 changes: 2 additions & 1 deletion jsdoc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@
},
"templates": {
"better-docs": {
"logo": "https://s3.us-east-2.amazonaws.com/assets.buccfer.io/aws-cognito-express/logo_transparent_background_83x83.png",
"name": "aws-cognito-express",
"navigation": [
{
"label": "Github",
"href": "https://github.com/buccfer/aws-cognito-jwt-validator"
"href": "https://github.com/buccfer/aws-cognito-express"
}
]
}
Expand Down
11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
{
"name": "aws-cognito-express",
"version": "1.1.0",
"version": "1.2.0",
"description": "Verification of Access and ID tokens issued by AWS Cognito for Node.js",
"main": "index.js",
"files": [
"src"
],
"scripts": {
"lint": "eslint --format compact .",
"test": "NODE_ENV=test nyc mocha 'test/**/*.spec.js'",
Expand All @@ -11,7 +14,7 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/buccfer/aws-cognito-jwt-validator.git"
"url": "git+https://github.com/buccfer/aws-cognito-express.git"
},
"keywords": [
"aws",
Expand All @@ -24,9 +27,9 @@
"author": "Fernando Buccella",
"license": "MIT",
"bugs": {
"url": "https://github.com/buccfer/aws-cognito-jwt-validator/issues"
"url": "https://github.com/buccfer/aws-cognito-express/issues"
},
"homepage": "https://github.com/buccfer/aws-cognito-jwt-validator#readme",
"homepage": "https://github.com/buccfer/aws-cognito-express#readme",
"engines": {
"node": ">=8.x",
"npm": ">=5.x"
Expand Down
24 changes: 13 additions & 11 deletions tutorials/01-quick-start.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,38 @@
#### 1. Make sure you have Node.js >= 8.
##### 1. Make sure you have Node.js >= 8
```bash
$ node -v
=> v10.16.0
```

#### 2. Install aws-cognito-express using npm:
##### 2. Install aws-cognito-express using npm
```bash
$ npm install --save aws-cognito-express
```

#### 3. Add the Cognito authentication middleware and error handler to your Express.js application:
##### 3. Add the authentication middleware and error handler to your Express.js application
```javascript
// app.js

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const { authenticate, authenticationError } = require('aws-cognito-express');
const router = require('./router');

const app = express();

app.use(bodyParser.json());

// Add authentication middleware.
// Add the authentication middleware.
app.use(authenticate({
region: 'us-east-2',
userPoolId: 'us-east-2_6IfDT7ZUq',
tokenUse: ['id', 'access'],
audience: ['55plsi2cl0o267lfusmgaf67pf']
}));

app.use('/', router);
// Protected route.
app.get('/articles', (req, res, next) => {
console.log('JWT payload: ', req.cognito);
});

// Add authentication error handler.
// Add the authentication error handler.
app.use(authenticationError());

module.exports = app;
Expand Down
75 changes: 75 additions & 0 deletions tutorials/02-fetch-user-from-database.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
Most use cases require that the user data is fetched from a database. For example, when you want to check the user permissions
or retrieve some data based on the user settings. In that case, you can create your own authentication middleware reusing the
one provided by this library.

In the following example we will use the [compose-middleware](https://www.npmjs.com/package/compose-middleware) package to create
our own authentication middleware that will:

1. Validate the JWT.
2. If the JWT is valid, it will fetch the user from the *User* MongoDB collection.

```javascript
// authentication.middleware.js
'use strict';

const HttpErrors = require('http-errors');
const mongoose = require('mongoose');
const { compose } = require('compose-middleware');
const { authenticate } = require('aws-cognito-express');

// Custom middleware to fetch the user from the 'User' MongoDB collection.
async function fetchUser(req, res, next) {
const { email } = req.cognito;
const User = mongoose.model('User');

try {
const user = await User.findOne({ email });

if (!user) {
// NOTE: You should create an error handler for http errors.
return next(new HttpErrors.Unauthorized(`User with email ${email} does not exist`));
}

req.user = user;
return next();
} catch (err) {
return next(err);
}
}

module.exports = compose([
authenticate({
region: 'us-east-2',
userPoolId: 'us-east-2_6IfDT7ZUq',
tokenUse: ['id', 'access'],
audience: ['55plsi2cl0o267lfusmgaf67pf']
}),
fetchUser
]);
```

Finally, you can use your custom middleware as follows:

```javascript
// app.js
'use strict';

const express = require('express');
const { authenticationError } = require('aws-cognito-express');
const customAuthenticationMiddleware = require('./authentication.middleware');

const app = express();

// Add the custom authentication middleware.
app.use(customAuthenticationMiddleware);

// Protected route.
app.get('/articles', (req, res, next) => {
console.log('Logged in user: ', req.user);
});

// Add the authentication error handler.
app.use(authenticationError());

module.exports = app;
```
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
If you are not using Express.js or if you want to write your custom authentication and error handling logic, we've got your back.
This module exports some helpers for you to use.
If you are not using Express.js or if you want to write your custom authentication and error handling logic, this module
exports some helpers you can use to achieve such goal.

### 1. Validating tokens.
### Validating tokens

To write your custom authentication logic, you can make use of the `JWTValidator` class.
To write your custom authentication logic, you can make use of the [JWTValidator](JWTValidator.html) class.

> **IMPORTANT**: You must instantiate a validator **only once** and then use it to validate the tokens in each request.
> **IMPORTANT**: You *must* instantiate a validator **only once** and then use it to validate the tokens in each request.
To be initialized, validators make an http request to the Cognito's JWKS endpoint. So if you instantiate a new validator
for each request, you will add unnecessary overhead due to the initialization process.

Expand All @@ -28,10 +28,10 @@ jwtValidator.validate(token)
.catch(err => console.error(err));
```

### 2. Handling validation errors.
### Handling validation errors

This module exports a convenient function `isJWTValidatorError` that you can use in your custom error handlers to verify
if the error was thrown by the JWT validator.
This module exports a convenient function [isJWTValidatorError](global.html#isJWTValidatorError) that you can use in your
custom error handlers to verify if the error was thrown by the JWT validator.

```javascript
'use strict';
Expand Down
40 changes: 20 additions & 20 deletions tutorials/03-testing.md → tutorials/04-testing.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
If you are wondering how could you write your application tests without the need of creating a Cognito User Pool just for that, then we've got your back.
The JWT Validator has an additional property `pems` that you can provide in the constructor `config` parameter.
If you want to write your application tests without the need of creating a Cognito User Pool, instances of the
[JWTValidator](JWTValidator.html) class have an additional property **pems** that you can provide in the constructor **config**
parameter.

When a validator is instantiated with the `pems` property, no initialization process takes place. This means that there won't be any http request to Cognito
to fetch the JWKS.
When a JWT validator is instantiated with the *pems* property, no initialization process takes place. This means that there
won't be any http request to Cognito to fetch the JWKS.

In the following sections we illustrate how to set the `pems` property and how to create valid JWTs for testing.
In the following sections we illustrate how to set the *pems* property and how to create valid JWTs for testing.

### 1. Setting custom pems.
## 1. Setting custom pems

#### 1.1. Creating an RSA key pair.
#### 1.1. Creating an RSA key pair

In order to create your own JWTs for testing you will need a RSA key pair to sign those tokens. To generate a RSA key pair and
store it in the `rsa_keys` folder you can use OpenSSL as follows:
In order to create your own JWTs for testing you will first need a RSA key pair to sign those tokens. To generate a RSA key pair
and store it in the *rsa_keys* folder you can use OpenSSL as follows:

```bash
# Create destination folder.
Expand All @@ -24,9 +25,9 @@ $ openssl genrsa -out rsa_keys/key.pem 2048
$ openssl rsa -in rsa_keys/key.pem -pubout -out rsa_keys/key.pub
```

#### 1.2. Setting the pems property.
#### 1.2. Setting the pems property

The `pems` property must be set to a non-empty object with the following structure:
The *pems* property must be set to a non-empty object with the following structure:

```javascript
const pems = {
Expand All @@ -35,7 +36,7 @@ const pems = {
};
```

where each key is the value of the JWT `kid` header and each value is a string containing the PEM encoded RSA public key.
where each key is the value of the JWT *kid* header and each value is a string containing the PEM encoded RSA public key.
As an example:

```javascript
Expand All @@ -61,8 +62,8 @@ if (process.env.NODE_ENV === 'test') {
const jwtValidator = new JWTValidator(jwtValidatorConfig);
```

**NOTE**: If you are using the Express.js authentication middleware provided by this library, then you should provide the `pems`
property in the `config` parameter of the `authenticate` function:
If you are using the Express.js authentication middleware provided by this library, then you should provide the *pems*
property in the *config* parameter of the [authenticate](global.html#authenticate) function as follows:

```javascript
'use strict';
Expand Down Expand Up @@ -92,18 +93,17 @@ app.use(authenticate(authenticateConfig));
module.exports = app;
```

### 2. Creating valid JWTs for testing.
## 2. Creating valid JWTs for testing

When testing your code, you will want to generate valid JWTs to authenticate your users. You can use the `jsonwebtoken`
library to accomplish that.

First you have to install it:
To generate valid JWTs to authenticate your users in your tests, you can use the [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)
library. Since the JWTs you are going to create are just for testing purposes, you only need to install the *jsonwebtoken*
library as a dev dependency.

```bash
$ npm install --save-dev jsonwebtoken
```

Now you can generate your own JWTs to authenticate users in your tests.
In the example below, we illustrate how to create a JWT such that the JWT validator recognizes it as a valid token.

```javascript
'use strict';
Expand Down
6 changes: 6 additions & 0 deletions tutorials/05-debugging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
This library uses the [debug](https://www.npmjs.com/package/debug) package for debugging, which is disabled by default. To enable it,
you have to set the *DEBUG* environment variable as follows:

```text
DEBUG=aws-cognito-express
```
14 changes: 10 additions & 4 deletions tutorials/tutorials.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
{
"01-quick-start": {
"title": "Quick Start"
"title": "Quick start"
},
"02-custom-validation": {
"title": "Custom Validation & Error Handling"
"02-fetch-user-from-database": {
"title": "Fetching users from a database"
},
"03-testing": {
"03-custom-authentication": {
"title": "Custom authentication flow"
},
"04-testing": {
"title": "Testing"
},
"05-debugging": {
"title": "Debugging"
}
}

0 comments on commit e832c71

Please sign in to comment.