(Re)Learning Backbone Part 9

(Note: The code for this project at this point in our progress can be downloaded from Github at commit: 8a19651c576968b29f143d271147b0b288ca63a7)

Authentication and Authorization

In this installment we'll tackle some functionality that I feel many tutorials leave out - authentication. We are going to implement a simple model that will both authenticate users and determine whether they are authorized to perform a function. This implementation is not meant to be bulletproof but to get a basic workflow in place. We'll be identifying a user as an admin with permissions to delete users. In practice, I usually keep all admin type functions out of my main application. Keeping them to themselves in a purpose built app allows you to restrict the audience and enforce other security measures, such as IP whitelisting.

HTTP is a stateless transaction by default. Whether we create a server side session to track user details or not, we need some way to identify an incoming request as being made by a particular user. We will be using JSON Web Tokens to provide this identification. They will be generated by our server when a user authenticates themselves and stored in the browser's local storage. To demonstrate authorization and personalizing the interface we will also be asking the server for the user information for the currently logged in user and a set of permissions for actions they are allowed to take. We will use these permissions on the client to present a better experience for the user; we won't easily allow them to perform an action they are not authorized to perform. Ultimately, all actions will be verified on the server to prevent users from bypassing our UI restrictions.

Before we get into the code, let's take a look at the workflow of authenticating a user. Let's assume we have a home page accessible to anyone, our users page, accessible to logged in users, and the delete button accessible to anyone with Admin permissions.

We can describe our workflow in two places: the router and application wide AJAX error handling.

Here is the logic workflow we will be implementing in the router and supporting classes:

Along with these decisions, we will intercept and handle the following HTTP error codes returned by our backend:

401
The User is not Authenticated - Redirect to Login
403
The User is not Authorized - Redirect to Home
500
Generic Error Handling

So, in the case that a user has a token, but it has expired, when they go to retrieve their User object, we will return a 401 error, forcing them to login.

Creating An Admin User (The Wrong Way)

We don't want to create a full featured permissions model or management console at this point. We haven't coded any features so trying to write permissions would be premature. It would be helpful for testing and prototyping, however, to indicate that one or more of our users had a specific property. To add these permissions to a user, we are going to cheat. For our POST /api/users and PUT /api/users/:user_id routes, we are going to check the request query parameters. Any parameters that match permission=foo will get added to a permissions block on the user. If there are none, the permissions block will be set to empty. We will also want to update our User schema to return these permissions as part of our normal retrieval functionality.

/app/models/user.js

var mongoose = require('mongoose');  
var Schema = mongoose.Schema;


var UserSchema = new Schema({  
    name: String,
    email: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true, select: false},
    permissions: [String]
});

module.exports = mongoose.model('User', UserSchema);  

Here we simply added an Array of Strings named permissions to the Schema.

And update the POST and PUT blocks in /app/routes/user.js to include

user.permissions = req.query.permissions || [];  

where we set the other user properties. Now, using our Postman utility, create or update an existing user and some permissions to the url. For example:

localhost:1337/api/users/54ea3206488bfd24c5ac7ee8?permissions=admin&permissions=superhero  

This would then add admin and superhero to our permissions array. If we leave them off, an empty array is used. Again, this is The Wrong Way to do this, but it will serve our purposes.

Changes

So, let's run down the code changes we are going to make

  • We are going to modify our backend server code and

    • create an /api/authenticate endpoint that will accept credentials. If successful, it will return a token.
    • modify the /api/user(s) endpoints to check for the presence of a valid token before performing any actions. If one is not found, a 401 Unauthenticated error code will be returned.
    • modify the DELETE /api/users/:user_id endpoint to verify the authenticated user also has admin permissions. If not, a 403 Unauthorized error code will be returned.
    • update our server to accept requests from other domains. (More on this later).

  • We will create a login screen and

    • extend the existing single user form view
    • add some simple client side validation to enforce name and email requirements
    • call the authentication endpoint
    • upon successful login we'll store the token received

  • We will create a logout action in our navigation bar that

    • will be visible only when logged in
    • will remove the stored token when activated

  • We will display information about the logged in user in the navigation bar

  • We will modify our router to

    • ensure that we are authenticated before showing the Users view

  • We will create an application wide object to

    • perform authentication and logout actions
    • provide access to our currently logged in user

  • We will add application wide AJAX error handling

Server Updates

Authentication Endpoint - Until now, we've been storing our passwords in the database in cleartext. We should really be encrypting them. Let's grab a crypto library to handle that, along with the JSON Web Tokens library.

npm install bcrypt-nodejs jsonwebtoken --save  

In /app/models/user.js let's go ahead and require the crypto library and add some functionality to use it.

var bcrypt = require('bcrypt-nodejs');

UserSchema.pre('save', function(next){  
    var user = this;
    if (!user.isModified()){
        return next();
    }

    bcrypt.hash(user.password, null, null, function(err,hash){
        if (err) {
            return next(err);
        }
        user.password = hash;
        next();
    })
});

UserSchema.methods.comparePassword = function(password){  
    var user = this;
    return bcrypt.compareSync(password, user.password);
};

We have two things going on here. First, we've added a hook to the User schema that will get called before any Save operation. If the document has been modified, or is new, we assume the password has been modified and is in cleartext. We convert it to an encrypted form, and then let the normal save function occur.

Secondly, we've added a comparePassword method to the User object. When we authenticate a user, we will use this compare the submitted password to the stored one.

Now let's update our user routes in /app/routes/user.js. First add our dependency:

var jwt = require('jsonwebtoken');

var superSecret = 'TheAmazingKreskin`;  

We've also created a "secret word" that we will use when encrypting and decrypting our token. This should probably be stored in a config file or passed in on the command line for better security.

After our default /api/ route, let's create our /api/authenticate route

var userRouter = express.Router();

userRouter.post('/authenticate', function (req, res) {  
    User.findOne({
        email: req.body.email
    }).select('name email password').exec(function (err, user) {
        if (err) throw err;

        if (!user) {
            res.json({success: false, message: 'User not found'});
        } else {
            var validPassword = user.comparePassword(req.body.password);
            if (!validPassword) {
                res.json({success: false, message: 'Wrong password'});
            } else {
                var token = jwt.sign({
                    name: user.name,
                    email: user.email,
                    _id: user._id
                }, superSecret, {
                    expiresInMinutes: 1440
                });

                res.json({
                    success: true,
                    message: 'login ok',
                    token: token,
                    _id: user._id
                });
            }
        }
    });
});

userRouter.get('/', function (req, res) {  
    res.json({message: 'api is loaded'});
});

When receive the POST request, we lookup the user by the provided email, and select their name and password as well. Remember, by default, our Schema does not return a password. In the event of an error or the user is not found, an error is returned to the user. In this instance, we don't send an error response. We expect that an unsuccessful attempt is a common occurrence, so we will explicitly handle the response. In this way, we could count the number of attempts or provide extra help, rather than just redirecting back to the login page.

If the user is found, we compare the submitted password to the one on record. If successful, we create a token with some user info in it and a timeout of 1440 minutes, or 24 hours. This will force the user to reauthenticate after one day, even if they have a proper token. Encrypting it will prevent the token from being modified by the client.

Using our Postman extension, we can test this endpoint right away. Using our prvious user editing capabilities, change the password on one of the users. This will ensure that the password associated with the user is encrypted in the database. (In fact, you may want to clean out any other users you created since they will need to have their passwords reset. For a production app, we could trap for this condition and handle it gracefully. Let's just delete them and make new ones.)

Make a POST request to /api/authenticate with a body of

{"email" : "email_value", "password": "password_value"}

using the values for that user you updated. Remember to set the Content-Type header to application/json. If the passwords match, you should see a response similar to

{
    "success": true,
    "message": "login ok",
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQnJpYW4gTSIsIl9pZCI6IjU0ZTZiMTYyZWIyYWM2MWM1NGU5YjgwZiIsImlhdCI6MTQyNDkyNTA4MCwiZXhwIjoxNDI1MDExNDgwfQ.90utguKl1XrpQZHU6tYPzOhskOeSl4k5RTTk6JcbuDo",
    "_id": "54e6b162eb2ac61c54e9b80f"
}

Even with our authentication endpoint in place, we have no problem accessing our app, even if we provided the wrong password. We'll need to tell the other routes to check for a valid token to be sent with every request.

After our default route, add the following code. Since this is declared after the default route, we will still be able to access it without authentication.

userRouter.get('/', function (req, res) {  
    res.json({message: 'api is loaded'});
});

userRouter.use(function (req, res, next) {  
    var token = req.body.token || req.params.token || req.headers['x-access-token'];
    if (token) {
        jwt.verify(token, superSecret, function (err, decoded) {
            if (err) {
                return res.status(401).send({success: false, message: 'Failed to authenticate token'});
            } else {
                req.decoded = decoded;
                next();
            }
        })
    } else {
        return res.status(401).send({success: false, message: 'No token provided'});
    }
});

With the use directive, we are adding some middleware to our route. For every request on routes declared after this we will attempt to find a token value in the body, in the parameters, or even in the headers. If a token is found, we verify it with our secret word. If it is valid, we continue to the next request handler, which will be our standard GET, PUT, POST, etc. calls. If there is no token, or it is invalid, we send a 401 HTTP error with an appropriate message. Our client will know that it needs to reauthenticate when it receives such a message.

Now, if we try to access our users page, we will get an error and nothing will display.

Next Steps

In our next installment, we'll wire up the client to call the authenticate endpoint when needed and send our token on future calls.

(The code at this state in the project can be checked out at commit: dae2b441bf1c718a6000df50679a6b096d70d8c4)