我在我的rails应用程序中使用devise进行身份验证 我正在构建一个与我的rails api联系的ember js应用程序 我的devise.rb
Devise.setup do |config|
config.mailer = "Devise::Mailer"
require 'devise/orm/active_record'
config.case_insensitive_keys = [ :email ]
config.http_authenticatable = [:token]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth, :token_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.confirmation_keys = [ :email ]
config.sign_out_via = :delete
end
和我的会话控制器
module Api
class SessionsController < Devise::SessionsController
def create
unless params[:email] && params[:password]
return invalid_params('You need to provide both email and password')
end
res = User.find_for_database_authentication(email: params[:email])
if res && res.valid_password?(params[:password])
user = res
end
unless user
unless params[:email] && params[:password]
return invalid_params('invalid email or password')
else
return invalid_params('You need to provide both email and password')
end
else
sign_in user,:store=>false
user = warden.authenticate!
user.ensure_authentication_token!
render json: current_user ,serializer: UserSerializer ,status: 201
end
end
def destroy
signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
render json: {}, status: :accepted
end
protected
def invalid_params(errorMessage)
warden.custom_failure!
render json: { errorMessage: errorMessage }, status: 403
end
end
end
当我使用我的ember应用程序对sessions / sign_in进行身份验证并且json返回current_user credintials
时,每件事情都能正常工作但在我的个人资料控制器中,我有过滤器
module Api
class ProfilesController < ApplicationController
before_filter :auth_only?
respond_to :json
def index
@profiles =Profile.all
respond_with(@profiles)
end
end
end
在我的应用程序控制器中
def auth_only?
unless user_signed_in?
render json: {},status: 401
end
end
当我尝试在我的ember应用程序中获取profiles.json时出现的问题...它给了我未经授权的401
我的auth.js in ember
$.ajaxSetup({
beforeSend: function(xhr, options) {
var encoded_auth_token, header;
if (Remon.Auth.get('auth_token')) {
encoded_auth_token = Base64.encode64(Remon.Auth.get('auth_token') + ":X");
header = "Basic " + encoded_auth_token;
xhr.setRequestHeader('Authorization', header);
}else{
console.log("not auth");
}
},
error: function(xhr) {
if (xhr.status === 401) {
console.log("unauth");
}
if (xhr.status === 404) {
console.log("wrong");
}
}
});
我正在使用设计2.1.2和ember 1.4
同样在我的请求标题中没有找到授权标题,尽管我设置它也是通过Remon.Auth.get(“auth_token”)从控制台获取它