Handling CSRF / XSRF Tokens with Angular Interface and Drupal 7 Brand

I am going to create a new AngularJS interface for the Drupal 7 site. This uses the Services module with session-based authentication across two domains using CORS. I can authenticate with Drupal, get the user object and session data, and then get the CSRF token from the services module. I'm having trouble setting all this up in the header so that subsequent requests are authenticated. I understand the general concept, but new to both AngularJS and preventing CSRF attacks.

From what I compiled by reading about this setting with AngularJS and RubyOnRails, there may be inconsistencies between the platforms regarding what the token is designated and how it is processed. A number of suggestions are also presented on how to set this token in the header. However, I had trouble finding a convincing example of how to get these platforms to speak the same language.

The only thing I do with my $ httpProvider in app.js:

delete $httpProvider.defaults.headers.common['X-Requested-With']; 

Controller controller login .js:

  .controller('LoginCtrl', ['$scope', '$http', '$cookies', 'SessionService', function($scope, $http, $cookies, SessionService) { $scope.login = function(user) { //set login url and variables var url = 'http://mywebsite.com/service/default/user/login.json'; var postDataString = 'name=' + encodeURIComponent(user.username) + '&pass=' + encodeURIComponent(user.password); $http({ method: 'POST', url: url, data : postDataString, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (data, status, headers, config) { var sessId = data.sessid; var sessName = data.session_name; $cookies[sessName] = sessId; var xsrfUrl = 'http://mywebsite.com/services/session/token'; $http({ method: 'GET', url: xsrfUrl }).success(function (data, status, headers, config) { $cookies["XSRF-TOKEN"] = data; SessionService.setUserAuthenticated(true); }).error(function (data, status, headers, config) { console.log('error loading xsrf/csrf'); }); }).error(function (data, status, headers, config) { if(data) { console.log(data); var msgText = data.join("\n"); alert(msgText); } else { alert('Unable to login'); } }); }; 
+4
source share
4 answers

The decision is about how cookies should be set and then transmitted through subsequent requests. Attempting to install them manually did not go well, but the solution was simpler than I expected. For each call to $ http, the following parameters must be specified:

 withCredentials: true 

Another change I made is to use the term CSRF instead of XSRF so that it matches Drupal. I did not use the built-in functions of AngularJS CSRF.

+3
source
  addItem: function(data) { return $http.post('api/programs/'+$stateParams.id+'/workouts', {item:data},{ headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-CSRF-Token': $('meta[name="xxtkn"]').attr('content') } }); } 

since it was the year of this topic! not sure if I am still facing the same problem, but for those who come looking for answers, here's how I deal with this! Note that the headers {} part I define a new header and call it the X-CSRF token and capture the value from the DOM (serveride) generated by html or php. It is also not recommended to request the csrf token from the server. A Cuz attacker could also somehow request this. Because you save it as a cookie. Attacker can steal cookies! No need to save it in a cookie! send the token with the header and read it on the server to match it!

and for multitasking the same page. I use the same token for the entire session. Only regenerate upon entering the system, logging off and changing the basic settings of the site or user.

+2
source

There is a large library called callse ng-drupal-7-services . If you use this in your project, it solves authentication / re-authentication and the file / node creates an aut field, and you can fokuse on the imported material in your project.

So, authentication is solved like this:

 function login(loginData) { //UserResource ahndles all requeste of the services 3.x user resource. return UserResource .login(loginData) .success(function (responseData, status, headers, config) { setAuthenticationHeaders(responseData.token); setLastConnectTime(Date.now()); setConnectionState((responseData.user.uid === 0)?false:true) setCookies(responseData.sessid, responseData.session_name); setCurrentUser(responseData.user); AuthenticationChannel.pubLoginConfirmed(responseData); }) .error(function (responseError, status, headers, config) { AuthenticationChannel.pubLoginFailed(responseError); }); }; (function() { 'use strict'; AuthenticationHttpInterceptor.$inject = [ '$injector']; function AuthenticationHttpInterceptor($injector) { var intercepter = { request : doRequestCongiguration, }; return intercepter; function doRequestCongiguration (config) { var tokenHeaders = null; // Need to manually retrieve dependencies with $injector.invoke // because Authentication depends on $http, which doesn't exist during the // configuration phase (when we are setting up interceptors). // Using $injector.invoke ensures that we are provided with the // dependencies after they have been created. $injector.invoke(['AuthenticationService', function (AuthenticationService) { tokenHeaders = AuthenticationService.getAuthenticationHeaders(); }]); //add headers_______________________ //add Authorisation and X-CSRF-TOKEN if given if (tokenHeaders) { angular.extend(config.headers, tokenHeaders); } //add flags_________________________________________________ //add withCredentials to every request //needed because we send cookies in our request headers config.withCredentials = true; return config; }; 

There is a kind of kitchen sink for this project: Drupal-API-Explorer

+2
source

Yes, each platform has its own convention, naming its tokens.

Here is a small team hoping to facilitate its use on different platforms. This will allow you to use set names and can be used in all queries. It also works for cross-domain requests.

https://github.com/pasupulaphani/angular-csrf-cross-domain

0
source

Source: https://habr.com/ru/post/1494126/


All Articles