infotechnohelp/cakephp-authentication_advanced

CakePHP 3 认证 API 插件

安装: 366

依赖: 1

建议: 0

安全: 0

星标: 0

分支: 0

类型:cakephp-plugin

dev-master 2019-12-23 16:47 UTC

This package is auto-updated.

Last update: 2024-09-24 03:55:25 UTC


README

实现

composer require infotechnohelp/cakephp-authentication_advanced

1. 添加插件

src/Application.php → bootstrap()

$this->addPlugin('Infotechnohelp/Authentication', ['routes' => true]);

或者使用终端

bin/cake plugin load Infotechnohelp/Authentication -r

2. 添加组件

src/Controller/AppController.php → initialize()

$this->loadComponent('Infotechnohelp/Authentication.Authentication');

3. 设置认证配置

config/bootstrap.php

Configure::write('Infotechnohelp.Authentication', [

'loginAction' => '/',
'loggedInAction' => '/demo-controller/authenticated-action',
'loggedOutAction' => '/?loggedOut',

]);

4. 迁移迁移

bin/cake migrations migrate --plugin Infotechnohelp/Authentication

表: Users, UserRoles

5. 添加用户角色

6. 设置测试用例的 fixtures

composer.json

	...,
    "autoload-dev": {
        "psr-4": {
            "Infotechnohelp\\Authentication\\Test\\": "vendor/infotechnohelp/cakephp-authentication_advanced/tests"
        }
    },
	...

不要忘记刷新自动加载数据

composer dump-autoload

将 fixtures 添加到测试用例

IntegrationTestCase

    public $fixtures = [
        'plugin.Infotechnohelp/Authentication.Users',
        'plugin.Infotechnohelp/Authentication.UserRoles',
    ];

登录用户

$this->session(['Auth' => ['User' => ['id' => 1]]]);

用法

终端

注册新用户

bin/cake Infotechnohelp/Authentication.users register <username> <password> <user_role_id>

在控制器中的用法

默认情况下,所有控制器都将有禁止访问。

为了允许控制器的某个方法

    public function initialize()
    {
        parent::initialize();
        $this->Auth->allow('allowedMethod');
    }

为了允许所有方法

$this->Auth->allow();

API

  • APP/authentication/api/register → username, password, repeat-password (email, user_role_id)

用户可以提供用户名或电子邮件进行登录,认证层将自动检测。

{"data": User entity, "message": null}

{"data":null, "message": message text}

  • APP/authentication/api/login → username or email (automatic detection), password

{"data":User entity, "message": null}

{"data":null, "message": Error message text}

  • APP/authentication/api/logout

{"data":true, "message": null}

认证隧道

  • APP/authentication/login?redirect=
        <form action="[app root]/authentication/login?redirect=[redirect url]" method="post">
            Username: <input name="username" type="text">
            Password: <input name="password" type="password">
            <button type="submit">Log in</button>
        </form>

如果未指定重定向 URL,将使用默认值。Configure::read('Infotechnohelp.Authentication')['loggedInAction']。

用户可以提供用户名或电子邮件进行登录,认证层将自动检测。