I am using Devise for user authentication in a Rails application. I tried to use AngularJS instead of the default rails scaffolding in an application. The problem is that when I add the before_filter :authenticate_user! in the controller then AngularJS calls to update/save and delete a resource does not work saying Unauthorized Access (401). Here is some of the code:
The resource:
@app.factory "employeesDB", ($resource) ->
$resource("/employees/:id", {id: "@id"}, {update: {method: "PUT"}},
{destroy: {method: "DELETE"}}
)
The save action:
$scope.saveEmpl = ->
$scope.em = new Object if !$scope.em
employeesDB.save({}, $scope.em, (resource) ->
$scope.employees.push(resource)
, (response) ->
console.log("Failed")
)
$scope.em is the object containing the data for the record and it is bind to angular using ng-model.
Everything works perfect if I remove the before_filter :authenticate_user! from the controller
class EmployeesController < ApplicationController
#before_filter :authenticate_user!
The problem occurs only when I try to save/update/delete the record, just reading it works OK.
Any ideas?? Are there any specific guidlines I should follow when using Angular and Devise? I am newbie to rails and angularJS so a detailed explanation will be greatly appreciated! Thanks
You can add this to your app.js
:
myApp.config([
"$httpProvider", function($httpProvider) {
$httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element('meta[name=csrf-token]').attr('content');
}
]);
Which add CSRF token to all Angular requests.
EDIT: Now jQuery independent (use jqLite).
I found out that I had to use the CSRF token.
http://ngmodules.org/modules/ng-rails-csrf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With