Authenticated user making AJAX requests to rails API from jQuery

时间:2022-04-08 20:23:29

I'm building a Rails app and I'm using Devise for authentication. When the user is logged in I need to make an AJAX call to Rails and get data that belongs to the current user as JSON. Also I don't want unauthenticated users and other logged-in users to access the current user's resources.

我正在构建一个Rails应用程序,我正在使用Devise进行身份验证。当用户登录时,我需要对Rails进行AJAX调用,并将属于当前用户的数据作为JSON获取。此外,我不希望未经身份验证的用户和其他登录用户访问当前用户的资源。

I'm using jQuery's $.getJSON() to make the AJAX request by simply specifying the link address like this:

我正在使用jQuery的$ .getJSON()通过简单地指定链接地址来生成AJAX请求:

 $.getJSON('http://localhost:3000/users/1/photos', function(data) { console.log(data); });

So far authetication seems to work in the same manner it worked for the HTTP requests therefore a user can access only his own data via AJAX.

到目前为止,验证似乎与HTTP请求的工作方式相同,因此用户只能通过AJAX访问自己的数据。

I don't have too much experience with AJAX and I don't understand why this does work at all. From where does my rails app know that I'm logged in when I make the AJAX call? I thought I had to create an extra authentication token and use it for authentication or to set the devise session cookie when performing the AJAX call.

我对AJAX没有太多经验,我不明白为什么这样做有用。当我进行AJAX调用时,我的rails应用程序从哪里知道我已登录?我以为我必须创建一个额外的身份验证令牌并将其用于身份验证或在执行AJAX调用时设置设计会话cookie。

Later Edit: From where does my rails app know that I'm logged in when I make the AJAX call?

稍后编辑:当我进行AJAX通话时,我的rails应用程序从哪里知道我已登录?

1 个解决方案

#1


1  

An AJAX request (XMLHttpRequest) will contain the same headers at a standard HTTP request for the same domain. As far as reading the cookie from the header, looking up the session information, and authorizing the request, the behavior will be the same.

AJAX请求(XMLHttpRequest)将在同一域的标准HTTP请求中包含相同的标头。至于从标题中读取cookie,查找会话信息以及授权请求,行为将是相同的。

#1


1  

An AJAX request (XMLHttpRequest) will contain the same headers at a standard HTTP request for the same domain. As far as reading the cookie from the header, looking up the session information, and authorizing the request, the behavior will be the same.

AJAX请求(XMLHttpRequest)将在同一域的标准HTTP请求中包含相同的标头。至于从标题中读取cookie,查找会话信息以及授权请求,行为将是相同的。