In this example we use the Auth0 lock component in front of our application. This covers both sign up and sign in to our application. Read more about how to authenticate using Auth0. The screen shot below shows how the awesome Auth0 lock dialog looks like.
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
auth: {
params: { scope: 'openid email' } //Details: https://auth0.com/docs/scopes
}
});
...
lock.show();
The scope parameter is important to make sure that we get the user email address.
On a successful authentication, the Lock object fires an event with a user profile and the essential JSON Web Token (JWT). We use the JWT to log in to our restdb.io backend database by simply providing the JWT in the constructor.
lock.on("authenticated", function(authResult) {
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
// Handle error
return;
}
// log in to our database using JWT token
if (!db) {
db = new restdb(authResult.idToken, {"logging": false, "jwt": true});
}
localStorage.setItem('id_token', authResult.idToken);
// Display user information
show_profile_info(profile);
});
});
Now that we have an authenticated user and a session to our database, lets query for some data records from the "products" collection:
var query = {}; // all
var hint = {"$max": 10}; // first 10 only
db.product.find(query, hint, function(err, productlist){
// productlist is an array of product objects ...
}
Creating objects and saving it to the database is just as simple:
var p = new db.product({name: "from jsapi"});
p.save();
db.product.getById("5662d2d7632700720000008c", function(err, res){
var nukem = new db.product(res);
nukem.delete();
});
Basically, it's really simple to secure your API from anonymous access.
This blog post has shown how you can:
- Create a Auth0 client for your application
- Grab the JWT from the Lock dialog
- Use the JWT to log in to your database
Don't forget to visit this link to a working application example: https://www-websitedemo-4db9.restdb.io/auth0-demo.
Resources
Read more about restdb.io in the docs here: https://restdb.io/docs
Learn more about Auth0 here: https://auth0.com
Learn more about JWT here: https://jwt.io