ruby-on-rails - 使用 Rails 的身份验证错误 - 设计和 AngularJS

标签 ruby-on-rails authentication devise angularjs

我在 Rails 应用程序中使用 Devise 进行用户身份验证。我尝试在应用程序中使用 AngularJS 而不是默认的 rails 脚手架。问题是当我添加 before_filter :authenticate_user!在 Controller 中然后AngularJS调用更新/保存和删除资源不起作用说未经授权的访问(401)。这是一些代码:

资源:

@app.factory "employeesDB", ($resource) ->
  $resource("/employees/:id", {id: "@id"}, {update: {method: "PUT"}},
    {destroy: {method: "DELETE"}}
  )

保存 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 是包含记录数据的对象,它使用 ng-model 绑定(bind)到 angular。

如果我删除 before_filter :authenticate_user,一切都会完美!从 Controller
class EmployeesController < ApplicationController
  #before_filter :authenticate_user!

仅当我尝试保存/更新/删除记录时才会出现问题,只需阅读它就可以了。

有任何想法吗??在使用 Angular 和 Devise 时,我应该遵循任何特定的指导方针吗?
我是 rails 和 angularJS 的新手,因此将不胜感激详细的解释!
谢谢

最佳答案

您可以将此添加到您的 app.js :

myApp.config([
  "$httpProvider", function($httpProvider) {
    $httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element('meta[name=csrf-token]').attr('content');
  }
]);

它将 CSRF token 添加到所有 Angular 请求中。

编辑:现在 jQuery 独立(使用 jqLite )。

关于ruby-on-rails - 使用 Rails 的身份验证错误 - 设计和 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15290559/

相关文章:

android - PWA 有没有办法访问主机设备的电话号码?

ruby-on-rails - 如何从 Rails 控制台注销设计用户?

ruby-on-rails - 为什么设计将 sign_up 错误重定向到不同的页面?

ruby-on-rails - 如何将设计 REST API 登录与可锁定集成

ruby-on-rails - Rails 5.2 加密凭据未保存

ruby-on-rails - 注销错误: No route matches [GET] "/users/sign_out"

ruby-on-rails - Rails 4 删除按钮将我注销并导致 "Can' t 验证 CSRF token 的真实性”

ruby-on-rails - 设置列默认值是否会损害数据库空间?

authentication - 在多策略场景中设置默认授权策略

authentication - 使用 Websphere Application Server (WAS) 和 LTPA 模拟用户/密码数据源