REST服务的Codeigniter身份验证密钥 [英] Codeigniter auth key for REST service

查看:101
本文介绍了REST服务的Codeigniter身份验证密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Phil Sturgeon Rest Server编写一个简单的RESTful服务。我想通过使用此库提供的API密钥来保护我的方法。

I'm writing a simple RESTful service, using Phil Sturgeon Rest Server. I want to protect my methods by using the API key provided with this library.

不幸的是,这没有得到很好的记录,我有点迷失了。

Unfortunately, this is not very well documented and I'm a bit lost.

我想对用户(电子邮件/密码)进行身份验证,然后生成一个身份验证密钥以发送其他所有请求。但是似乎我已经需要auth密钥才能生成一个。创建虚拟密钥似乎并不十分安全。抱歉,这是一个愚蠢的问题,但是最佳做法是什么?

I want to authenticate users (email/password), then generate an auth key to send on every other requests. But it seems that I already need the auth key to generate one ... Create a dummy key does not seem very secure. Sorry if it is a dumb question, but what should be the best practice?

推荐答案

如果您熟悉其他API,我会注意到一个常见的模式。我推荐一种身份验证方法,用户通过该方法传递其电子邮件和密码,这将返回生成的唯一身份验证密钥。 auth密钥就像一个会话ID,考虑cookie的工作方式。然后,所有其他API方法都应检查$ this-> post('auth'),然后在处理每个请求之前,需要将其与会话处理程序(即数据库或会话)进行比较。

If you are familiar with other APIs you'll notice a common pattern. I recommend an authenticate method where the user passes their email and password, which will return a generated unique auth key. The auth key would be like a session id, think of how cookies work. Then all the other API methods should check $this->post('auth') and you need to compare this with your session handler (i.e. database or sessions), before you process each request.

好像有很多代码,对吧?

Seems like a lot of code huh? Nope.

所有模型都应具有重载的构造函数:

All your models should have an overloaded constructor:

class MyAPIController extends Rest_controller
{
    public function __construct()
    {
        parent::__construct();

        if(!authCheck($this->post('auth'))){
            returnFailedResponse();
            exit();
        }
}

然后正常地编写您的API,例如Phil Sturgeon的网站。
http://net.tutsplus.com/tutorials / php / working-with-restful-services-in-codeigniter-2 /

Then write you API normally, like in the examples on Phil Sturgeon's website. http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

制作一个具有authCheck的模型以测试auth密钥是否有效,并为returnFailedResponse创建方法以返回未经授权的401。

Make a model that has authCheck to test that the auth key is valid, and make a method for returnFailedResponse to return a 401 Unauthorized.

在另一个控制器中,将其称为 Auth,使用上述构造函数。

In another controller, lets call it 'Auth', use the above contructor.

现在,每次对api的调用都应为Auth设置标头。例如‘Auth:12m34k23b’。

Now every call to your api should set a header for the Auth. Ex. 'Auth: 12m34k23b'.

这篇关于REST服务的Codeigniter身份验证密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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