Boilerplate for API auth following secure standards. Includes user registration/login and authentication using bearer tokens and CSRF protection using CSRF-tokens.
This is a project meant to be used as a starting point for APIs that require user authentication (registration and sign on). Sign on sessions are showcased with protected routes that pass through authentication middleware. API is designed to be consumed by a SPA.
This is a WIP, if you find any issues or concerns with the security of the implementation, please, open a new issue or contact me directly @yanglorenzana on Twitter.
Read the tutorial series for this project if you'd like a more detailed explanation and walkthrough.
Tried following json:api specification for the design of the API for the error responses, but didn't get a good example for other response objects.
Project uses mongoose for data modeling and express.js for easy server setup.
The auth system uses 16 random bytes generated with the node.js crypto module as authentication tokens.
To run project locally:
npm install
in root directorysecrets.js
file or add it to your ENV variablesnpm start
to run nodemon in watch modegenerateToken()
method).csrf-token: 'YOUR TOKEN HERE'
that would change/modify server-side state. In this case, the DELETE api/users/me
and PUT api/users/logout
routes require a csrf token.csrfCheck
middleware. This middleware should be added to any route that would change state. The csrfCheck for the delete user route is somewhat redundant as it requires the user to provide credentials, but I included it to serve as example.An example of login route response and placing the csrf-token in headers:
Feedback and PR's welcome. Follow me @yanglorenzana, DM's always open.