【问题标题】:Authentication error using Rails - Devise and AngularJS使用 Rails 的身份验证错误 - 设计和 AngularJS
【发布时间】:2013-02-23 19:04:19
【问题描述】:

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

资源:

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

保存动作:

  $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 绑定到 Angular。

如果我删除 before_filter 一切都会完美:authenticate_user!来自控制器

class EmployeesController < ApplicationController
  #before_filter :authenticate_user!

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

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

【问题讨论】:

  • 您是否尝试将 withCredentials 参数传递给您的 $httpProvider 默认值? app.config(['$httpProvider', function($httpProvider) {$httpProvider.defaults.withCredentials = true;}]);?
  • 添加了以下内容,可惜没用。我遇到了同样的问题。@app = angular.module("Mathra", ["ngResource"]).config(['$httpProvider', ($httpProvider) -> $httpProvider.defaults.withCredentials = true ])跨度>

标签: ruby-on-rails authentication devise angularjs


【解决方案1】:

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

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

向所有 Angular 请求添加 CSRF 令牌。

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

【讨论】:

    【解决方案2】:

    我发现我必须使用 CSRF 令牌。

    http://ngmodules.org/modules/ng-rails-csrf

    【讨论】:

      猜你喜欢
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多