PHP API 身份验证和会话 [英] PHP API authentication and sessions

查看:36
本文介绍了PHP API 身份验证和会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个广泛依赖会话的 PHP 应用程序.我们现在正在考虑为我们的用户构建一个 API.我们最初的想法是,用户需要使用他们的电子邮件地址、密码和 API 密钥(每个用户唯一)对 API 进行身份验证.

I have a PHP application that relies extensively on sessions. We are now considering building an API for our users. 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).

然而,由于当前的应用程序(包括模型)广泛依赖于用户会话,我不确定最佳方法.

However, as the current application (including the models) relies on user sessions extensively, I am not sure on the best approach.

假设 API 请求经过正确验证,是否可以接受:

Assuming that an API request is correctly authenticated, would it be acceptable to:

  • 在用户通过身份验证后启动 API 调用会话
  • 运行模型并将 json/xml 返回给用户
  • 终止会话

这意味着每次 API 调用都会实例化会话,然后立即刷新.这个可以吗?或者我们应该考虑其他选择吗?

This means that the session gets instantiated for each API call, and then immediately flushed. Is this OK? Or should we be considering other alternatives?

推荐答案

根据我创建 API 的经验,我发现会话最好只持续一个请求,并在每个执行周期重新创建会话信息.

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.

如果您的会话实例化很重要,这显然会引入开销,但是如果您只是根据数据库检查凭据,它应该没问题.此外,您应该能够基于用户标识符而不是会话在 APC 或内存缓存之类的东西中缓存任何繁重的工作,从而减少重新创建会话所需的工作,同时确保在每个请求中验证身份验证.

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.

这篇关于PHP API 身份验证和会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆