Question

I am developing an application using angularJs, resources and jersey rest api's. And I want to implement xsrf protection in my project. Please suggest a better example. I got one example here, but it uses ColdFusion. http://www.bennadel.com/blog/2568-Preventing-Cross-Site-Request-Forgery-CSRF-XSRF-With-AngularJS-And-ColdFusion.htm

Was it helpful?

Solution

Different from given example, you need to do 2 things:

  1. When the main page gets loaded once the user logs in, you need to set a session cookie with name XSRF-COOKIE. Then AngularJS will do the rest by appending a header to every request as stated in documentation (1)
  2. You need to validate every call to your rest API in back-end (for example with an interceptor) by comparing the token in cookie and the one in header. The logic is described on the page you referenced

(1) To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on the first HTTP GET request. CSRF Protection section in Documentation

OTHER TIPS

Incase this is your code in jsp/ html page which sets the header and token:

<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>

You can configure the csrf headers for all ajax requests as flollows:

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

angular.module("app", [])
.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.common[header] = token;
}]);

And then your http request code will go as follows:

$http({
    url: "loadMyData.htm",
    method: "POST",
}).success(function(data)
{
    console.log(data);
})

create interceptor with below command.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     const cookie = this.cookieService.get('XSRF-TOKEN');
    request = request.clone({
      headers: new HttpHeaders({
        'XSRF-TOKEN': cookie,

      }),
    withCredentials: true
 });
 return next.handle(request);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top