Ruby on rails 让ng token auth与Desive_token_auth一起工作
我有一个Rails和Ionic项目。后端使用design_token_auth Gem,前端使用ng token auth;它们应该“无缝地”工作 我已经完成了注册和登录的所有工作,这将返回一个有效的响应对象。无论如何,在我使用$state.go('app.somepage')之后,任何进一步的请求都会导致401个未经授权的响应 我感觉到我实际上并没有把代币存储在任何地方。有人能帮忙吗 以下是一些片段:Ruby on rails 让ng token auth与Desive_token_auth一起工作,ruby-on-rails,angularjs,devise,ionic,Ruby On Rails,Angularjs,Devise,Ionic,我有一个Rails和Ionic项目。后端使用design_token_auth Gem,前端使用ng token auth;它们应该“无缝地”工作 我已经完成了注册和登录的所有工作,这将返回一个有效的响应对象。无论如何,在我使用$state.go('app.somepage')之后,任何进一步的请求都会导致401个未经授权的响应 我感觉到我实际上并没有把代币存储在任何地方。有人能帮忙吗 以下是一些片段: .controller('LoginCtrl',['$scope', '$auth'
.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'
});
}]).
在后SCTRL中:
$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"}}
应用程序控制器顶部:
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
如果有人能提供一些见解,那就太好了。我很乐意根据需要发布更多的代码片段。您是否尝试为$authProvider添加配置。本例在的自述文件中
angular.module('myApp',['ng-token-auth'])
.config(函数($authProvider){
$authProvider.configure({
apiUrl:'http://api.example.com'
AuthProviderPath:{
github:'/auth/github'/在我的例子中,我使用cookies来存储令牌。每当我们在Angular应用程序中使用$auth
方法时,其中一些方法将尝试转到您在Rails路由器中定义的设计路由,并匹配/验证存储在任何标头请求中的令牌。(每次尝试执行http请求时!如果请求头包含uid
或auth\u令牌
(如果要通过GET
/validate\u令牌
())进行验证,请使用浏览器检查器签出请求头。)
由于您没有提到您的路线,我们可以假定/auth
由$auth
提供的$http
请求应该包含要通过Rails设计验证的令牌,并在执行$auth.submitLogin()
时捕获并存储到浏览器的cookie中
下面是关于它如何在我以前的项目中工作的示例
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);
}
};
}])
并将令牌格式设置为如下所示(或根据需要自定义)
不要忘记将ipCookie
(查找angular cookie
,而不是angular cookie
)注入到拦截器,因为这是ng token auth用于cookie管理的cookie库
如果我说得不够清楚,请在下面用问题进行评论。:D此信息可能与您有关
我怀疑您尝试登录的用户无效。发生这种情况时,授权标头为空,并且响应中没有返回访问令牌
这种情况发生在这里:事实证明,解决方案相当简单。似乎在每个人提供的大多数示例中,他们都忽略了允许访问令牌
,以及所有其他CORS头
为此,我们在config.ru
的底部使用了机架COR:
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
也许太晚了
但问题是,你不能在cookies(只有Android)上拥有身份验证。因此,你可以尝试使用localStorage保存会话信息(在iOS和Android上)
e、 g
您可以在特定版本的文档中阅读更多内容:有点晚,但对于任何可能尝试在Ionic应用程序中使用ng token auth的人来说,我所做的是将下一个配置设置到我的模块:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);
(我在http请求中没有发送任何cookie)是的,谢谢,身份验证最初是有效的,但随后无法转化为后续页面请求。我还没有阅读您的全部问题,但我与Lynn Dylan Hurley的库一起写了一篇关于Rails/Angular身份验证的完整文章。此外,我也不知道您问题的答案,但在您的情况下,我会做的只是旋转起来一个空白的新项目,并遵循我的教程,看看它是否有效。然后,如果教程有效,看看你的项目和教程之间有什么不同。这个项目进展如何?我正在做一些非常类似的事情,有问题,你有开源吗?没有,但如果你阅读我下面选择的答案,这应该会给你一个线索。我不允许打开代码的源代码:(谢谢,这样做了。此外,我们使用本地存储来存储令牌,这同样有效。我可以验证此解决方案是否有效。我也使用本地存储。我不确定为什么没有投票,或者基本文档中没有包含此内容。这是我必须拥有的,我认为我们没有做任何异常的事情。同意。我不知道知道在没有这个的情况下如何工作。虽然我只需要allow
块,但没有ApplicationController的东西。此外,如果您使用Rails,允许块可以放在application.rb而不是config.ru中。谢谢。我发现这对很多人来说都是个问题。我选择了自己的答案,因为它实际上是解决方案,我认为你最后的评论是相关的。我们使用了jack-hammer方法。谢谢你在config.ru中的提示。嗨,伙计们,我遇到了完全相同的问题(ionic,无访问令牌头)这些解决方案没有任何帮助。任何想法都将受到极大的赞赏!我们最初是这样做的,但它没有解决问题。它只允许我们存储一些会话信息并假装进行了身份验证。无论如何,令牌的整个思想正是使用会话数据。这是一个不同的解决方案,适用于不同的应用程序问题
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
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
.config(function($authProvider) {
$authProvider.configure({
apiUrl: 'http://myprivateapidomain/api',
storage: 'localStorage'
});
})
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);