简体   繁体   English

PHP API身份验证和会话

[英]PHP API authentication and sessions

I have a PHP application that relies extensively on sessions. 我有一个PHP应用程序,它广泛依赖于会话。 We are now considering building an API for our users. 我们现在正在考虑为用户构建API。 Our initial thoughts are that users will need to authenticate against the api with their email address, password and an API key (unique for each user). 我们最初的想法是,用户需要使用他们的电子邮件地址,密码和API密钥(每个用户都是唯一的)对api进行身份验证。

However, as the current application (including the models) relies on user sessions extensively, I am not sure on the best approach. 但是,由于当前的应用程序(包括模型)广泛依赖于用户会话,我不确定最佳方法。

Assuming that an API request is correctly authenticated, would it be acceptable to: 假设API请求已正确认证,是否可以接受:

  • Start the session for the API call once user is authenticated 用户通过身份验证后,启动API调用会话
  • Run the models and return json/xml to the user 运行模型并将json / xml返回给用户
  • Kill the session 杀掉会话

This means that the session gets instantiated for each API call, and then immediately flushed. 这意味着会话为每个API调用实例化,然后立即刷新。 Is this OK? 这个可以吗? Or should we be considering other alternatives? 或者我们应该考虑其他替代方案?

In my experience of creating APIs, I have found it best that sessions only last for one request and to recreate the session information in each execution cycle. 根据我创建API的经验,我发现最好的会话只持续一个请求并在每个执行周期中重新创建会话信息。

This does obviously introduce an overhead if your session instantiation is significant, however if you're just checking credentials against a database it should be OK. 如果您的会话实例化很重要,这显然会引入开销,但是如果您只是检查数据库的凭据,则应该没问题。 Plus, you should be able to cache any of the heavy lifting in something like APC or memcache based on a user identifier rather than session reducing the work required to recreate a session while ensuring authentication verified in each request. 此外,您应该能够根据用户标识符缓存APC或memcache等任何繁重的工作,而不是减少重新创建会话所需的工作,同时确保在每个请求中验证身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM