Rails beginner
Rails beginner

Reputation: 14504

Rails 3 devise 401 unauthorized ajax call

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 %>

Upvotes: 3

Views: 6687

Answers (3)

montrealmike
montrealmike

Reputation: 11631

Another way if you only have access to the url (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 

Upvotes: 0

Travis Todd
Travis Todd

Reputation: 236

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: https://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 https://stackoverflow.com/users/1052893/chau-hong-linh for the answer.

Upvotes: 14

Rails beginner
Rails beginner

Reputation: 14504

It was not devise giving the 401 authorized error, but CSRF token.

Just disabled it for my action:

protect_from_forgery :except => :rate

Upvotes: 1

Related Questions