Quantcast
Channel: Suhair
Viewing all articles
Browse latest Browse all 10

ExpressJS start to Authentication

0
0

ExpressJS start to Authentication

Manually installing and managaing packages could soon become nightmare in any platform and Node Package Manager (NPM) is the solution to automate packages discovery and installation on Node javascript framework.

mkdir express_auth
cd express_auth
npm info express version
npm init
npm install express --save

Once the application directory is created and moved on to that directory we can use npm to discover and manage the dependencies. info command gives all the information regarding a given package and appending version to that command displays only the latest version number.

Node Package Manager will use package.json file to install the application dependencies. We dont have package.json file and the easy way to create is to issue init command to npm. We then installs express and provides the —save argument so that npm will mark the express package as a dependency to our application. The created package.json is as follows.

{"name": "express_auth","version": "0.0.0","description": "Sample app to demonstrate ExpressJS and Passport","main": "index.js","scripts": {"test": "echo \"Error: no test specified\"&& exit 1"
  },"author": "","license": "BSD","dependencies": {"express": "~3.4.2"
  }
}

The name and version forms an identifier of the application and are required fields. Thanks to our usage of —save switch, the express package is now a dependency for our application.

Exress Hello World

The basic Express concept is the route that could respond to a request from browser.

var express = require("express");


var app = express();
app.get("/", function(req, res){
  res.send("Hello World");
});

app.listen(3000);
console.log("Have fun at port 3000");

Routing for HTTPGET requests could be provided through the get method on the Express application. get method accepts a path (a string or regular expression) that is used for determining to which request this route should respond. In this case GET request to root of the site will be handled. Our route then uses a high level method offered by Express to send the “Hello World” message as HTML content type.

listen is just a convenience method defined on Express application to listen for requests on the given host and port.

Responding by sending string of content will not be practical except in simple scenarios and we can revert to rendering views (View in MVC) which offers better separation of concerns.

var express = require("express");


var app = express();
app.get("/", function(req, res){
  res.render("index");
});

app.listen(3000);
console.log("Have fun at port 3000");

The only change we have made is to use render method (instead of send) which accepts the name of the view to render. We have provided yet to be created index view as the name. When server is run again and root of the site is accessed, we are greeted with an error.

Error: No default engine was specified and no extension was provided. at new View

Let’s try to correct the error by the easiest suggestion.

var express = require("express");


var app = express();
app.get("/", function(req, res){
  res.render("index.jade");
});

app.listen(3000);
console.log("Have fun at port 3000");

We have chosen jade templating engine from this list of Node template engines and added jade as the extension for our view. In this way Express could load jade into our application and do the rest. But running the application gives a different error.

Error: Cannot find module ‘jade’ at Function.Module._resolveFilename

This time Node is coplaining that it does not know about jade module and the solution is easy.

npm install jade --save

Now the application tells that it could not find index.jade template by throwing error Error: Failed to lookup view “index.jade” at Function.app.render. That’s a vlaid complaint since we have not created that template yet. Let’s create the index.jade template (and where?). We will create views folder inside the application and will place the index.jade file there. We will rip off our sample content from jade website itself since we are not (yet) comfortable with the new jade syntax.

doctype 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) {
         bar(1 + 5)
      }
  body
    h1 Jade - node template engine
    #container.col
      if youAreUsingJade
        p You are amazing
      else
        p Get on it!
      p.
        Jade is a terse and simple
        templating language with a
        strong focus on performance
        and powerful features.

Now everything works fine but we have to provide the jade extension to the view name every time we use render. What if we can set the template engine site wide as suggested by one of our previous error messages?.

var express = require("express");


var app = express();
app.set("view engine", "jade");

app.get("/", function(req, res){
  res.render("index");
});

app.listen(3000);
console.log("Have fun at port 3000");

set function assigns jade as view engine which is one of the settings that supported by Express out of the box. This takes care of rendering the jade view by default.

Basic Authentication

Basic Authentication (BA) is the simplest method to enforce access controls for a website. In this mode it is upto the browser to provide the user credentials of the valid user. Browser will ask for the credentials to the user and will supply it to the remote server for verification.

var express = require("express");


var app = express();
app.set("view engine", "jade");
app.use(express.basicAuth("aladdin", "opensesame"));

app.get("/", function(req, res){
  res.render("index");
});

app.listen(3000);
console.log("Have fun at port 3000");

As we have instructed Express to use the basicAuth middle ware, the browser will ask for our hard coded credentials to grant access to the main page which was public previously.

In order to understand what the middleware basicAuth is doing we can seek the help of curl to display the headers by issuing the command curl -I http://localhost:3000/.

HTTP/1.1 401 Unauthorized
X-Powered-By: Express
WWW-Authenticate: Basic realm="Authorization Required"
Date: ****
Connection: keep-alive

Thanks to the basicAuth middleware, the server is sending 401 Unauthorized response code and sets the WWW-Authenticate header to use the Basic authentication. The realm set by this header is then used by the borwser to use as title bar or info of the popup box to the user.

In addition to giving restriction to the page, basicAuth also populates the req.user variable to user name or user object.

Logging the user out from basic auth. log:out@website.com seems a good solution.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images