Starter authentication server that utilizes JWT or local passport strategies for protected resources.
- mongoose - elegant mongodb object modeling for node.js
- expressjs - Fast, unopinionated, minimalist web framework for Node.js
- passport - Simple, unobtrusive authentication for Node.js
- JWT - JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
- user model
- encryption of passwords
Add your own config.js
in the root directory of your project.
You will see errors when trying to start the app if you don't provide these properties.
// config.js
module.exports = {
// Secret key for JWT signing and encryption
'secret': 'super secret passphrase',
// Database connection information
'database': 'mongodb://localhost:auth/auth',
// Setting port for server
'port': process.env.PORT || 3090
}
Signup route will require email
and password
to be sent and will check if email provided is already in use.
app.post('/signup', Authentication.signup);
Signin route will also require email
and password
to be sent and server will validate credentials provided.
app.post('/signin', requireSignin, Authentication.signin);
Sample route that requires JWT authentication.
app.get('/', requireAuth, (req, res, next) => {
res.send({ access: 'granted' });
});
curl -X POST \
http://localhost:3090/signup \
-d '{
"email":"me@me.com",
"password": "test"
}'
{
"error": "Email is in use."
}
or
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1OWYzODQxYTY5MjFhYjI3ZWJlODY0NDciLCJpYXQiOjE1MDkxMzEyOTAzMzgsImVtYWlsIjoibWVAbWUyLmNvbSJ9.sLG8rCopHvDsFD_3eHeJ7Lja9vKYWNj1py4DrukBv8g"
}
curl -X GET \
http://localhost:3090/ \
-H 'authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1OWYzNmQwNzg5ZTYwNTFlN2FkZjY2ZTkiLCJpYXQiOjE1MDkxMjUzODMyMTQsImVtYWlsIjoiYnV0dHRlcjJAZXh4YW1wbGUuY29tIn0.sWrBHQ85ErGQF1lZ18qB8LGfKutAOgXifbb8yX9b0Ds' \
-H 'content-type: application/json' \
Response returns 'Unauthorized' or the protect resource depending on if the JWT sent was valid or not
{
"access": "granted"
}
curl -X POST \
http://localhost:3090/signin \
-H 'content-type: application/json' \
-d '{
"email":"me@me.com",
"password": "test"
}'
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1OWYzNzNlMjA1MWY0NzIyNTc0YWY1ZTkiLCJpYXQiOjE1MDkxMjg0MjczNTcsImVtYWlsIjoibWVAbWUuY29tIn0.XPFY88mQZUPSibLV6COdGeHtZf6ZoYp2NKV-cX0llw4"
}
Reference: http://blog.slatepeak.com/refactoring-a-basic-authenticated-api-with-node-express-and-mongo/