Category Archives: Angular-js

Implementing CSRF protection with Angular-js

After 2 articles on the security, I continue with the set up of the CSRF protection using Spring security.

The main idea behind is to prevent some one else to create (forge) a request without our authorization. Imagine that a page uses JavaScript to send something like, if you are connected to your bank in another tab browser, the request could be successful…
To avoid that, for each request, the server sends a unique identifier (Spring uses a UUID) and it must be part of the request you send back to the server.

Fortunately, Angular provides a support for CSRF protection. Following the documentation, the server needs to provide a cookie named XSRF-TOKEN and Angular will send its value in a header named X-XSRF-TOKEN. On the server side, Spring then verifies that the value from the header is the expected one and continue the process, otherwise, it sends an error.

But to make them working together, we need to make some adjustments.
I use the same pet store application I used in my previous article and it is still available on github.

Let’s go to the code!
First of all, on the server side, Spring provides the identifier as a request attribute, because in a standard Spring-MVC application, it is very simple to add it in an HTML form using expression language. But with our SOA approach, we are just sending data, therefore we need to put it in the cookie we send to the browser. To do that, I defined a filter which just take the CSRF token and set a cookie:

public class CsrfInjectorFilter extends OncePerRequestFilter {

	private static final String XSRF_TOKEN = "XSRF-TOKEN";
	private static final Logger LOG = LoggerFactory.getLogger(CsrfInjectorFilter.class);

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {

		CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
		if (csrfToken != null) {
			Cookie cookie = new Cookie(XSRF_TOKEN, csrfToken.getToken());
			//mandatory to avoid duplicate cookies in browser
		}else {
			LOG.debug("No csrf token found!!");
		chain.doFilter(request, response);

Note: I choose to define the cookie name as Angular expects it, but it also possible to define its name on the client side (using $httpProvider.defaults.xsrfCookieName) and keeping the web service ignore who is the client.

There is also one important thing you must absolutely do (I spent half of a day with that!), you have to set a path to your cookie! Otherwise, for some reasons, the browser does not replace the cookie when it is changed, and it simply manage several cookies with the same name, resulting in CSRF errors on the server side. I tested this issue with Firefox and Chrome.
On the other side, I need to configure Angular to return the header as expected by Spring, this is done in the app.js file:

petstoreApp.config(['$httpProvider', function($httpProvider){
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';

We can see that the code is very straightforward.

Angular-js and Restful web services access

Following my previous article about the integration of Spring Security with web services, I will now explain how I integrate it with an Angular-js project.
For that purpose, I am a little bit lazy and I use a project I already written instead of building a completely new one.

The project is a “funny” pet-store based on Spring boot (I like it definitely!), using an H2 database and Flyway to restore its content at each start.
The full project is available on Github.

The web services are defined with Spring MVC in the

public class PetController {
	private PetService petService;
	@RequestMapping(value = "/pet/all", method = RequestMethod.GET)
	public Collection<JsonPet> findAll() {
	@Transactional(propagation= Propagation.SUPPORTS)
	@RequestMapping(value = "/pet/{id}", method = RequestMethod.GET)
	public JsonPet find(@PathVariable("id") final Integer id) {

	@Transactional(propagation= Propagation.REQUIRED)
	@RequestMapping(value = "/pet", method = RequestMethod.POST, consumes = {"application/json" })
	public @ResponseBody JsonPet save(@RequestBody final JsonPet jsonPet) {

The PetService is the class responsible of business processes (mainly access data here).

We can see that there are 3 actions available to:

  • display the list of pets in the store
  • display the detail of a pet
  • create a “new” pet in the store

The attributes of the requestMapping annotation seem explicit, for example, with @RequestMapping(value = “/pet”, method = RequestMethod.POST, consumes = {“application/json” }), I express that the method can be reach with /pet URL, by using the POST method and it needs json.
Based on Spring, the conversion from Json to Java Object (and the opposite) is totally hidden (it relies on Jackson API) and it avoid this burden to the developer (meaning me, here!).

Now that the landscape is set, let’s have a look at the security configuration (it should be familiar to whose who read my previous article):

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	  withUser("admin").password("password").roles("ADMIN", "USER").and().

protected void configure(HttpSecurity http) throws Exception { 
	.antMatchers(HttpMethod.GET, "/pet/**").access("hasRole('USER')")
	.antMatchers(HttpMethod.POST, "/pet/**").access("hasRole('ADMIN')");
	FormLoginConfigurer formLogin = http.formLogin();

I started with the users definition with their roles.
And after that, Y can see how I restricted access to the features, as previously, I disabled the CSRF protection but I will come back to it in a next article.

Now, if a unauthenticated user tries to access the protected resources, he will receive an HTTP 401 error. Let’s see how I deal with it on the client side (Angular-js).
The web pages are located in

The idea is to have the generic process to intercept the right HTTP code when the user needs to be authenticated, and redirect him automatically to the login page .
The application is based on the single page principle, for that purpose, I use the ngRoute module, it is configured in the app.js file:

  function($routeProvider) {
      when('/pets', {
	      templateUrl: 'partials/pet-list.html',
	      controller: 'PetListCtrl'
      when('/pets/new', {
    	  templateUrl: 'partials/pet-new.html',
    	  controller: 'PetNewCtrl'
      when('/pets/:petId', {
          templateUrl: 'partials/pet-detail.html',
          controller: 'PetDetailCtrl'
      when('/login', {
          templateUrl: 'partials/login.html',
          controller: 'LoginCtrl'
        redirectTo: '/pets'

As expected, we can find our 3 pages related to the web services features and another one to ask credentials to users. This one will be used when redirecting unauthenticated users.
For that purpose, the application is configured with an Angular-js interceptor. All the requests sent or received can be manipulated by interceptor, this is very useful for common purposes like error management or authentication, and it is exactly the way I use it (still in the app.js file):

petstoreApp.factory('errorInterceptor', ['$q', '$location', '$window', '$injector', function($q, $location, $window, $injector) {
	var authSrv;
	var popupSrv;
	var errorInterceptor = {
			'responseError' : function(rejection) {
				var status = rejection.status;
				if ({
					if (status == 401) {//Unauthenticated, redirect to login page
					} else if (status == 418) {//undefined error->HTTP code 418 ( I'm a teapot) is responsibility of the caller
						return $q.reject(rejection);
					} else{
						popupSrv = popupSrv || $injector.get('popUpSrv');
						popupSrv.alert("Erreur: " ("\r\n___________________________________\r\n\r\nErreur compl├Ęte:\r\n" +''));
				} else {
					popupSrv = popupSrv || $injector.get('popUpSrv');
					popupSrv.alert("Erreur inconnue( http status: "+status+")");
				return $q.reject(rejection);
	return errorInterceptor;
petstoreApp.config(['$httpProvider', function($httpProvider) {  

The interceptor is in charge of managing the HTTP 401 code by redirecting to the login form, and also of the display of a generic message error.
For more information about interceptors and their usage, you can directly have a look at the official site.

And now, it works! The web site can access resources protected with Spring security. In the real world, I should display the new pet button only for admin users, it means that I should also provide a service indicate which actions are available for a user.

For those who missed the point, the sources of the project are available here.