Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/juffalow/express-jwt-example
Example project for Express.js with JWT blogpost
https://github.com/juffalow/express-jwt-example
chai expressjs jwt mocha nodejs sinon
Last synced: about 2 months ago
JSON representation
Example project for Express.js with JWT blogpost
- Host: GitHub
- URL: https://github.com/juffalow/express-jwt-example
- Owner: juffalow
- Created: 2017-02-15T15:25:01.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2023-01-23T18:06:38.000Z (almost 2 years ago)
- Last Synced: 2024-04-14T05:11:05.681Z (9 months ago)
- Topics: chai, expressjs, jwt, mocha, nodejs, sinon
- Language: JavaScript
- Homepage: https://juffalow.com/javascript/express-server-with-jwt-authentication
- Size: 52.7 KB
- Stars: 32
- Watchers: 3
- Forks: 20
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Express.js with JWT example
This is an example project to show how to create login route and some other
route that is protected - could be called only if valid JWT token is provided.Everything is well tested with [mocha](https://mochajs.org), [chai](http://chaijs.com), [sinon](http://sinonjs.org) and [supertest](https://github.com/visionmedia/supertest).
## Dependencies
* express
* body-parser
* jsonwebtoken
* chai
* mocha
* sinon
* supertest## Scripts
`npm run start`
`npm run test`
## How to run the project
Install dependencies :
```
yarn install# or
npm install
```Edit `config.example.js` and save it as `config.js` :
```
module.exports = {
port: 8080,
jwtSecret: 'your jwt secret'
};
```Run tests :
```
npm run test
```If everything is OK, run the project :
```
npm start
```## How to test the project
When you run the project, you should be able to load the URL `http://localhost:8080/`, but you shouldn't be able to access `http://localhost:8080/api/hello-world`.
You can log in by sending a post on `http://localhost:8080/login` and send there username and password, both set to _admin_.
```
curl -XPOST -H "Content-Type: application/json" 'http://localhost:8080/login' -d '{"username":"admin","password":"admin"}'
```You should get back something like :
```
{
"id":1,
"username":"admin",
"jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNDg3NjM3OTg0LCJleHAiOjE0ODc2NDE1ODR9.1jMwROveQeR64baJOPdZV4SdpmKKVRvgPg0wJX9sHnI"
}
```Now, when you want to load `http://localhost:8080/api/hello-world` and you send there `Authorization` header with _jwt token_ from the previous response, you should be successful :
```
curl -XGET -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNDg3NjM3OTg0LCJleHAiOjE0ODc2NDE1ODR9.1jMwROveQeR64baJOPdZV4SdpmKKVRvgPg0wJX9sHnI' 'http://localhost:8080/api/hello-world'
```