falco442/slim-token-auth-mvc

此包已被废弃,不再维护。未建议替代包。

用于构建带有令牌认证的REST API的Slim框架骨架

v1.1.1 2016-10-10 16:13 UTC

This package is not auto-updated.

Last update: 2022-08-13 16:35:29 UTC


README

注意:此应用程序处于开发中

Slim Framework 3 带令牌认证

使用此应用程序(由 slim/slim-skeleton 衍生)开发基于令牌认证的REST JSON API应用程序

安装应用程序

在您想要安装新应用程序的目录中运行此命令。

composer create-project falco442/slim-token-auth-mvc [app-name]

您还可以运行此命令以在开发中运行应用程序。

composer start

运行此命令以运行测试套件

composer test

配置

数据库配置

此应用程序使用Laravel提供的ORM Illuminate\Database\Capsule\Manager。(见 api

您可以在 src/settings.php 中配置数据库连接。连接提供者在 src/dependencies.php 中已配置。

CORS

为了使应用程序能够接受CORS(跨域站点请求),我添加了 Tuupola cors-middleware。它已在 src/middleware.php 文件中配置。

设置

修改 settings.php 文件以使应用程序正常工作

return [
    'settings' => [
        '...',
        'determineRouteBeforeAppMiddleware'=>true, //Allows to catch the route from middleware

        'db' => [			// Pass the DB configuration
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'db_test',
            'username' => 'test',
            'password' => 'test',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ],
        'auth'=>[
            'table' => 'users',	// the table in which you can find users to authenticate
            'salt'  => 'asdasdkhkhuilyuhg1i8y9p78olil',	// the custom salt to hash the passwords
            'allowed_routes'=>[
                'POST'=>[
                	'/login', 	// to allow login
                	'/users'	// to allow adding a user
                ]
            ],
            'fields'=>[
                'username'=>'username',		// you can set anything you want.. like 'username' => 'email' if you want to login users by email
                'password'=>'password'		// same thing as above
            ]
        ],
        '...'
    ],
];

使用

控制器

此应用程序已配置了一个基础 Controller 类,作为小型的MVC工作。请参阅 src/Controller/UsersController.php 文件作为示例。

登录

要在用户中登录,请在 routes.php 中放置一个路由,如下所示(我使用 UsersController 作为示例)

$app->any('/login', '\App\Controller\UsersController:login');

这样,UsersControllerlogin 动作将被调用。使用 TokenAuth 类的 authenticate() 方法,如下

public function login($request,$response,$args){
	return $response->withJSON($this->Auth->authenticate($request));
}

在请求体中传递登录字段,如您在 settings 数组中设置的

如果用户存在,authenticate 方法将返回用户数组,否则返回 false。如果一切正常,TokenAuth 将刷新令牌并更新 token_created 字段