获取ng-token-auth以使用devise_token_auth

时间:2015-02-25 04:34:02

标签: ruby-on-rails angularjs devise ionic

我有一个Rails和Ionic项目。后端使用devise_token_auth Gem和前端ng-token-auth;这些应该是“无缝地”工作。

我已经完成了注册和登录的所有工作,它返回一个有效的响应对象。但是,在我使用$ state.go('app.somepage')之后的任何进一步请求都会导致401 Unauthorized响应。

我觉得我实际上并没有将令牌存储在任何地方。有人可以帮忙吗?

以下是一些片段:

    .controller('LoginCtrl',['$scope', '$auth', '$state', function($scope, $auth, $state) {
    $scope.loginForm = {}
    $scope.handleLoginBtnClick = function() {
      console.log($scope.loginForm);
      $auth.submitLogin($scope.loginForm)
          .then(function(resp) {
            $state.go('app.feed');
          })
          .catch(function(resp) {
            console.log(resp.errors);
          });
    };

州定义:

    .state('app', {
  url: "/app",
  abstract: true,
  templateUrl: "templates/menu.html",
  controller: 'AppCtrl',
  resolve: {
    auth: function($auth) {
      return $auth.validateUser();
    }
  }

})

资源:

factory('Post', ['railsResourceFactory', 'apiUrl', function (railsResourceFactory, apiUrl) {
    return railsResourceFactory({
        url: apiUrl + '/posts',
        name: 'post'
    });
}]).

在PostsCtrl中:

  $scope.loadFeed = function() {
    Post.query().then(function (posts) {
      $scope.posts = posts;
    }, function (error) {
      console.log( 'Did not get posts!'); ### THIS FIRES
    }).finally(function() {
      // Stop the ion-refresher from spinning
      $scope.$broadcast('scroll.refreshComplete');
    });
  };

登录回复对象:

{"data":{"id":1,"provider":"email","uid":"1234","phone":null,"name":"Admin","image":null,"username":"admin"}}

ApplicationController的顶部:

class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken

  before_filter :add_allow_credentials_headers
  before_filter :cors_preflight_check
  after_filter :cors_set_access_control_headers
  before_action :configure_permitted_parameters, if: :devise_controller?

  ..yadayada...

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :phone
    devise_parameter_sanitizer.for(:sign_up) << :username
    devise_parameter_sanitizer.for(:sign_up) << :session

    devise_parameter_sanitizer.for(:sign_in) << :phone
    devise_parameter_sanitizer.for(:sign_in) << :username
    devise_parameter_sanitizer.for(:sign_in) << :session
  end

还有一些用户在导轨端的默认型号。

Rails日志:

Started GET "/posts" for 192.168.83.26 at 2015-02-24 23:29:02 -0500
Processing by PostsController#index as JSON
  Parameters: {"post"=>{}}
Filter chain halted as :authenticate_user! rendered or redirected
Completed 401 Unauthorized in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)

如果有人能提供一些很棒的见解。我很乐意根据需要发布更多片段。

7 个答案:

答案 0 :(得分:8)

事实证明,解决方案相当简单。似乎在每个人提供的大多数示例中,他们忽略了允许access-token以及所有其他CORS标头。

我们在config.ru

的底部使用了rack-cors
require 'rack/cors'
use Rack::Cors do

  # allow all origins in development
  allow do
    origins '*'
    resource '*',
             :headers => :any,
             :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
             :methods => [:get, :post, :delete, :put, :options]
  end
end

然后在ApplicationController.rb中:

  before_filter :add_allow_credentials_headers
  skip_before_filter :verify_authenticity_token
  before_filter :cors_preflight_check
  after_filter :cors_set_access_control_headers


  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
    headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
    headers['Access-Control-Max-Age'] = '1728000'
  end

  def cors_preflight_check
    if request.method == 'OPTIONS'
      headers['Access-Control-Allow-Origin'] = '*'
      headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
      headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token'
      headers['Access-Control-Max-Age'] = '1728000'

      render :text => '', :content_type => 'text/plain'
    end
  end

  def add_allow_credentials_headers
    # https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#section_5
    #
    # Because we want our front-end to send cookies to allow the API to be authenticated
    # (using 'withCredentials' in the XMLHttpRequest), we need to add some headers so
    # the browser will not reject the response
    response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'
    response.headers['Access-Control-Allow-Credentials'] = 'true'
  end

答案 1 :(得分:3)

此信息可能与您相关。

jwako/ionic_rails_sample

答案 2 :(得分:2)

至于我的情况,我使用cookie来存储令牌。每当我们在Angular应用程序中执行$auth方法时,某些方法将尝试转到您在Rails路由器中定义的设计路由,并匹配/验证存储在任何标头请求中的令牌。 (每当您尝试执行http请求时,如果您要通过uid {{1}进行验证,请使用浏览器检查员检查您的请求标头(如果它们包含auth_tokenGET } {(https://github.com/lynndylanhurley/devise_token_auth#usage-tldr))

由于您没有提及您的路线,我们可以假设/validate_token

/auth提供的$http请求应包含要在Rails的设计中进行身份验证的令牌,并在我们执行$auth时将其捕获并存储到浏览器的cookie中。< / p>

以下是我之前项目中如何运作的示例。

$auth.submitLogin()

并将令牌格式设置为这样(或根据需要自定义)

app.factory('authInterceptor', ['$q', 'ipCookie', '$location',  function($q, ipCookie, $location) {
  return {
    request: function(config) {
      config.headers = config.headers || {};
      if (ipCookie('access-token')) {
        config.headers['Access-Token'] = ipCookie('access-token');
        config.headers['Client'] = ipCookie('client');
        config.headers['Expiry'] = ipCookie('expiry');
        config.headers['Uid'] = ipCookie('uid');
      }
      return config;
    },
    responseError: function(response) {
      if (response.status === 401) {
        $location.path('/login');
        ipCookie.remove('access-token');
      }
      return $q.reject(response);
    }
  };
}])

不要忘记将$authProvider.configure({ tokenValidationPath: '/auth/validate_token', signOutUrl: '/auth/sign_out', confirmationSuccessUrl: window.location.href, emailSignInPath: '/auth/sign_in', storage: 'cookies', tokenFormat: { "access-token": "{{ token }}", "token-type": "Bearer", "client": "{{ clientId }}", "expiry": "{{ expiry }}", "uid": "{{ uid }}" } }); (查找ipCookie而不是angular-cookie)注入Interceptor,因为这是ng-token-auth用于cookie管理的cookie库。

如果我不够清楚,请在下面评论问题。 :d

答案 3 :(得分:1)

也许为时已晚,

但问题是因为你不能在cookie上使用auth(仅限Android)。因此,您可以尝试使用localStorage保存会话信息(在iOS和Android上)

e.g

.config(function($authProvider) {
  $authProvider.configure({
    apiUrl: 'http://myprivateapidomain/api',
    storage: 'localStorage'
  });
})

您可以在文档的特定问题中阅读更多内容:https://github.com/lynndylanhurley/ng-token-auth/issues/93

答案 4 :(得分:1)

有点晚,但对于那些可能尝试在Ionic App中使用ng-token-auth的人来说,我所做的就是将其设置为(在我的情况下)是将下一个配置设置为我的模块:

app.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.defaults.withCredentials = true;

  }]);

(我没有在我的http请求中发送任何cookie)

答案 5 :(得分:0)

您是否尝试为$ authProvider添加配置。此示例位于https://github.com/lynndylanhurley/devise_token_auth的自述文件中。

angular.module('myApp', ['ng-token-auth'])
  .config(function($authProvider) {
    $authProvider.configure({
      apiUrl: 'http://api.example.com'
      authProviderPaths: {
        github: '/auth/github' // <-- note that this is different than what was set with github
      }
    });
  });

答案 6 :(得分:0)

我怀疑您尝试登录的用户无效。发生这种情况时,授权标头为空,并且在响应中不会发回任何访问令牌。

这发生在这里:https://github.com/lynndylanhurley/devise_token_auth/blob/0d4de71/app/controllers/devise_token_auth/concerns/set_user_by_token.rb#L53