Securing Your Application
Preventing cross-site request forgery
In any application where the server must trust who the user is, that is, they are logged
in, and allows them access to actions on the server based on that trust, there is the
potential for other sites to pretend to be you, and then get access to those actions
themselves. This is called cross-site request forgery (XSRF). If you visit an evil site
when you are already logged into a secure site, the evil site's web page could post to
your secure site, since it trusts that you are currently authenticated.
This attack is often in the form of a fraudulent src attribute on an tag, which
the user inadvertently loads by browsing to an evil page, while still logged into a
secure site. When the browser tries to load the image, it actually makes a request to
the secure site.
<img src="http://my.securesite.com/createAdminUser?username=badguy">
The solution is for the server to provide a secret to the browser, which can only be
accessed by JavaScript running on the browser, and so would not be available in the
src attribute. Any request to the server should include this secret in its headers to
prove it is authentic.
The $http service has this solution built-in, in order to protect against such an
attack. You must arrange for the server to set a token in the session cookie called
XSRF-TOKEN, on the first GET request by the application. This token must be unique
for this session.
In the client application, the $http service will extract this token from the cookie,
and then attach it as a header (called X-XSRF-TOKEN) to every HTTP request it
makes. The server must check the token on each request, and then block access if it
is not valid. The AngularJS team recommends that the token is a digest of your site's
authentication cookie with salt for added security.
Adding client-side security support
The rest of this chapter will look at what we should do in our AngularJS application
running in the browser to provide security and give a consistent experience for the
user, when dealing with authentication and authorization.
Out of the box, AngularJS does not provide functionality to deal with authentication
and authorization. In our sample application, we developed services and directives
that can be used in our templates and controllers to display security-related
information, handle authorization failures, and manage logging in and logging out.