gpt4 book ai didi

ruby-on-rails - 让 ng-token-auth 与 devise_token_auth 一起工作

转载 作者:行者123 更新时间:2023-12-03 09:26:28 27 4
gpt4 key购买 nike

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

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

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

以下是一些片段:

    .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"}}

应用 Controller 顶部:
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 侧用户的一些默认模型。

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)

如果有人能提供一些见解,那将是美妙的。我很高兴根据需要发布更多片段。

最佳答案

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

为此,我们在 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

关于ruby-on-rails - 让 ng-token-auth 与 devise_token_auth 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28711175/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com