Rails 3设计401未经授权的ajax通话 [英] Rails 3 devise 401 unauthorized ajax call

查看:174
本文介绍了Rails 3设计401未经授权的ajax通话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似于此问题的问题: jQuery Ajax调用在Rails 3中获得401未经授权的请求



我已经添加了token_authenticatable到我的设计模型。



在我的ajax调用操作中:

  def rate 
params [:kon] [:IP] = request.remote_ip
params [:kon] [:tag_id] = params [:id]
@konkurrencer = Tagrating.new(params [:kon ])
@ konkurrencer.save
@ konkurrencer.tag.rating_score + = params [:kon] [:ratings] .to_i
@ konkurrencer.tag.ratings + = 1
@ konkurrencer.save
render:nothing => true
end

如何验证ajax调用?



如何获取当前用户的令牌密钥。我试过:<%= current_user.token_authentication_key%>

解决方案

p>作者发布这是一个CSRF令牌问题。虽然解决方案已发布,但它并不安全。这个问题提出了一个更好的解决方案: http://stackoverflow.com/a/8175979/696610



我在这里复制:



您应该这样做:


  1. 确保您的布局中有<%= csrf_meta_tag%> / p>


  2. beforeSend 添加到所有ajax请求中,以设置标题如下:







  $。ajax({url:'你的URL here',
type:'POST',
beforeSend:function(xhr){xhr.setRequestHeader('X-CSRF-Token',$('meta [name =csrf-token] ').attr('content'))},
data:'someData ='+ someData,
success:function(response){
$('#someDiv')。html回应);
}
});

信用到 http://stackoverflow.com/users/1052893/chau-hong-linh 作为答案。


I got a problem similar to this question: jQuery Ajax calls in Rails 3 getting 401 Unauthorized Request

I have added token_authenticatable to my devise model.

In my action for the ajax call:

def rate
  params[:kon][:IP] = request.remote_ip
  params[:kon][:tag_id] = params[:id]
  @konkurrencer = Tagrating.new(params[:kon])
  @konkurrencer.save
  @konkurrencer.tag.rating_score += params[:kon][:ratings].to_i
  @konkurrencer.tag.ratings += 1
  @konkurrencer.save
  render :nothing => true
 end

How do I authenticate the ajax call?

How to get the token key for current user. I have tried: <%= current_user.token_authentication_key %>

解决方案

The author posted that this was a CSRF token issue. While the solution posted works, it is not secure. A better solution was proposed in this question: http://stackoverflow.com/a/8175979/696610

I'm copying it here:

You should do this:

  1. Make sure that you have <%= csrf_meta_tag %> in your layout

  2. Add beforeSend to all the ajax request to set the header like below:


$.ajax({ url: 'YOUR URL HERE',
  type: 'POST',
  beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
  data: 'someData=' + someData,
  success: function(response) {
    $('#someDiv').html(response);
  }
});

Credit to http://stackoverflow.com/users/1052893/chau-hong-linh for the answer.

这篇关于Rails 3设计401未经授权的ajax通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆