Rails 3 develop 401 unauthorized ajax call

I am having a problem similar to this question: jQuery Ajax causes in Rails 3 to receive 401 unauthorized requests

I have added token_authenticatable to my development model.

In my Activity for 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 an ajax call?

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

+3


source to share


3 answers


The author posted that this is a CSRF token issue. Although the solution has been posted, it is not secure. A better solution has been suggested in this question: fooobar.com/questions/30960 / ...

I copy it here:

You must do this:

  • Make sure in your layout <%= csrf_meta_tag %>

  • Add beforeSend

    to the whole 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);
  }
});

      

Confirm answer https://stackoverflow.com/users/1052893/chau-hong-linh .

+14


source


It didn't develop 401 authorized errors, but CSRF token.

Just turned it off for my action:



protect_from_forgery :except => :rate

      

+1


source


Another way if you only have access to the url (let's say you are using a plugin)

  var csrf_token = $('meta[name=csrf-token]').attr('content');
  var csrf_param = $('meta[name=csrf-param]').attr('content');
  var params;
  if (csrf_param !== undefined && csrf_token !== undefined) {
    params = csrf_param + "=" + encodeURIComponent(csrf_token);
  }

  var url = "/your/path?" + params 

      

0


source







All Articles