1

I'm considering building a security service in PHP that would hold user credential information , the most important of them would be tokens of logged in users. This service would be accessed by some kind of an API (REST, SOAP, whatever) by another API (an external user connects through a website API which checks credentials in another API - the one we're considering now).

There is a possibility to store tokens (and other information) in RDBMS. But this solution doesn't seem clean to me (tokens will remain in the database even if they're already expired, I would have to implement a mechanism for clearing expired sessions, etc). I was thinking about using native PHP session management ($_SESSION). Is that possible? Does anyone have experience with doing such things?

I thought of following problems:

  • when a PHP-based website is deployed on www server, users access the URL via browser and their native sessions are created using browser cookies. If there was one webpage API that would connect to security API, would there be only one session object all the time? Is it configurable?
  • How precisely sessions are created and how can I affect the mechanism (e.g. not to base it on cookies)?
4

1 回答 1

1

我的建议是使用数据库。

让我从解释会话的一般概念开始。会话可以看作是服务器端的 cookie。$_SESSION 变量存储的位置由 PHP 的 session.save_path 配置决定。通常这是 Linux/Unix 系统上的 /tmp。会话具有与其关联的客户端的会话参数。当发出 session_start 或类似的东西时,服务器将根据客户端提供的会话参数检索文件/会话。由于这些只是存储的文件,因此服务器可以读取其他客户端的会话。

这让我想到了你描述的第二个问题。如果我是正确的,你想要一些关于某个用户会话的 api 请求信息。根据第一段,您希望了解会话的目的不是将其用作某种全局存储。当然这是可能的。您可以让外部 API 包含会话参数,或者您可以手动读取会话文件,但对我来说,这些似乎是肮脏的修复。这不是构建会话的目的。

吸引您使用会话的唯一另一件事是会话的自动超时。但是,您可以在使用数据库时轻松实现这个简单的逻辑。您应该做的是在数据库中注册用户最后一次活动的时间。当 API 请求用户的数据时,您可以简单地检查当前时间 - 上次活动时间是否低于某个阈值。如果不是这种情况,则会话已过期,同时您可以从表中删除会话。这与会话内部使用的通用方法或多或少相同,它不需要常规的 cronjobs(尽管它们仍然可以用于清理数据库)来删除会话。

所以不要害怕使用数据库来存储数据,毕竟它们是构建(和优化)来做这件事的。

于 2013-07-01T09:37:59.227 回答