Mastering Web Application

(Rick Simeone) #1

Securing Your Application


Providing server-side authentication and authorization


One thing that is common for all client/server applications is that the server is the
only place where data is safe. We cannot rely on code on the client side to block
access to sensitive information. Similarly, the server must never rely on the client to
validate data that is sent to it.


This is particularly pertinent in JavaScript applications, where it is
quite straightforward to read the source code, and then even modify
it to perform malicious actions.

In a real web application our server must provide the appropriate level of security.
For our demo application, the server has fairly simple security measures in place. We
implement authentication and authorization using Passport, which is an ExpressJS
plugin. The authenticated user ID is stored as part of an encrypted session cookie.
This is passed down to the browser, when the user is logged in. This cookie is sent
back to the server on each request, to allow the server to authenticate that request.


Handling unauthorized access


When a request is made to a URL, the server determines whether this URL requires
an authenticated user, and whether the authenticated user has sufficient privileges.
In our application, we have arranged for the server to respond with an HTTP 401
unauthorized error, if the client tries to do any of the following:



  • Any non-GET request (for example POST, PUT, or DELETE) on a database
    collection, when there is no current authenticated user

  • Any non-GET request on the users or projects database collections, when the
    user is not an administrator


In this way, we are able to secure data (JSON requests) from unauthorized access.
We could do the same with other assets such as HTML or images, if we wished to
control access to those too.


Providing a server-side authentication API


To allow the client application to authenticate users, our server exposes the following
HTTP API:



  • POST /login: This message authenticates the user by the given username
    and password parameters, passed in the body of the POST request.

Free download pdf