Share Tweet Reccomend

Express.js Authentication

Now we will discuss how to implement authentication in Express.js. Express.js was discussed previously in the Introduction to Express.js. In the discussion there, we looked at how Express is a web-application framework just like CodeIgniter, Django, or Laravel except instead of running on something like Apache or Ngnix, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. Before looking at the following section, it might be a good idea to be familiar with Express.js by reading the introduction to Express and be familiar with Node.js as well. A Node.js Primer will help you with that.

When you think authentication in web development, you think logging in and logging out. Note that this is a little bit different from authorization, which has more to do with whether a logged in user has the permissions to do a certain action on a website. This the reason that you have different roles such as “Administrator,” “Editor,” and “User” defined within different systems. For this section we’ll focus more on authentication, but a lot of the ways that you handle authentication can also be extended upon to implement authorization.

Session-Based Authentication

When you speak of authentication in modern web applications, there are a number of different implementations you could be talking about. One of the more traditional approaches is the use of sessions. Sessions go back as far as anyone can remember with anything having to do with the web. Express.js supports sessions and you can use them just as you would in other languages like PHP.

Place the following code in a file called server.js. Obviously, in a real application we’d want to separate the markup we’re returning out into views and use a templating language to render them like we did in the introduction to Express. But for now, this will do just to serve for purpose of example…

var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser('shhhh, very secret'));
app.use(express.session());
function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}
app.get('/', function(request, response) {
   response.send('This is the homepage');
});
app.get('/login', function(request, response) {
   response.send('<form method="post" action="/login">' +
  '<p>' +
    '<label>Username:</label>' +
    '<input type="text" name="username">' +
  '</p>' +
  '<p>' +
    '<label>Password:</label>' +
    '<input type="text" name="password">' +
  '</p>' +
  '<p>' +
    '<input type="submit" value="Login">' +
  '</p>' +
  '</form>');
});
app.post('/login', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if(username == 'demo' && password == 'demo'){
        request.session.regenerate(function(){
        request.session.user = username;
        response.redirect('/restricted');
        });
    }
    else {
       res.redirect('login');
    }	
});
app.get('/logout', function(request, response){
    request.session.destroy(function(){
        response.redirect('/');
    });
});
app.get('/restricted', restrict, function(request, response){
  response.send('This is the restricted area! Hello ' + request.session.user + '! click <a href="/logout">here to logout</a>');
});
app.listen(8124, function(){
    console.log('Server running...');
});

Now if you run the following command in the same directory as server.js…

node server

and then open up your browser to http://localhost:8124 you can see the homepage as defined by the default route.

Read More »

Share Tweet Reccomend

HMAC REST API Security

Now we’re going to talk a bit about security. I wouldn’t say this is really my area of expertise so take what follows with a bucket of salt, but I’ve recently been looking a bit deeper into REST API security; authenticating users, verifying requests… things of that nature. There are a number of different methods or protocols a developer can use to secure a REST API and all of them have strengths and weaknesses. One of the challenges that you face when handling REST API security is the fact that it is a principle of REST architecture to remain stateless where the server does not maintain any record of whether or not a user is authenticated/authorized (i.e. logged in via sessions). So in order to determine who is sending the request (and whether they are authorized to access a particular resource) on the server side, all of the information needed to handle this has to contained within the request coming from the client.

In other sections, some common methods of handling REST API authorization and authentication were discussed. Basic HTTP Authentication was discussed here and OAuth using Google as a provider was discussed here. In what follows, we’re going to look at another implementation that can also be a pretty good solution to securing REST APIs: HMAC. What is HMAC? No, it’s not a new burger that McDonalds is rolling out. HMAC stands for “hash-based message authentication code.” Like the name suggests, this means we’re going to be sending a hash (a jumble of letters and numbers) back and forth between the client and server and the system is going to be able to figure out (hopefully) if the request is coming from someone we trust or if it is coming from one of less than noble character.

There are some great articles that have been written on HMAC. Notably…

As is discussed in the articles above, the general idea behind HMAC is this… A client and a server know a secret key. This secret key is never sent over the wire. It is only used in combination with other pieces of data that *are* sent over the wire. That way, when we use our secret key and any other data transferred — say, a public key identifying the user (in the form of a header or a cookie), the message body, the current timestamp or anything else we want to use — and we run that data through an encryption algorithm such as SHA-1… we can create the same hash on both the client and the server! That’s how we know the request is valid. Only a client with the secret key would be able to reproduce the same hash it ends up sending to the server.

Read More »

Share Tweet Reccomend

Basic HTTP Authentication with the Slim PHP Framework REST API

When it comes to securing your REST API — authenticating and authorizing users — the situation is a bit interesting because the principle of an API being truly RESTful is that things remain stateless on the server side with each request. What that means is that the server isn’t really supposed to keep track of state in the form of sessions or anything else. To be truly RESTful all of the information that the web application needs to properly handle each request should be contained in the request itself.

If you wanted to, you could just cheat and handle everything using sessions. But according to the Internet, if you do this many kittens will die. So in the interest of at least trying to do things properly and saving the lives of millions of kittens, in the following bit we’re going to look at another one of the more common implementations for REST API authentication and authorization: Basic HTTP Authentication. We’ll be using the Slim Framework — a lightweight PHP REST API to demonstrate this, but the same principles apply if you’re using another framework or even another language.

To have user authentication within your app’s API and remain truly RESTful, it usually inevitably boils down to 2 choices: Basic HTTP Authentication and OAuth. OAuth was discussed previously in this article about using Google’s OAuth in order to access many different Google’s APIs. The developer docs at Twitter also have some good information on these two different forms of authentication.

Read More »

Share Tweet Reccomend

Using OAuth 2.0 for Google APIs

OAuth has become an incredibly popular way to manage authentication and authorization for apps — mobile, desktop, and web. What is OAuth? Well according to the OAuth site OAuth is…

An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.

Well, to be honest that’s pretty general and might not exactly clear everything up if you’re new to OAuth. Don’t worry though. In what follows, we are going to show some really simple implementations in a couple of different languages that will hopefully help you get a better grasp on what OAuth is and whether or not it’s a good choice for you to use on your website or in your application.

Read More »