hunomina/http-auth-router-php

适用于 PHP 7.1 或更高版本的 Http Auth Router

1.2.0 2019-10-04 08:04 UTC

This package is auto-updated.

Last update: 2024-09-04 19:48:42 UTC


README

Build Status codecov

描述 : 实现适用于 PHP7.1 或更高版本的 Http Router 类,带有认证。

这个库主要由 8 个类组成。

AuthRouter

AuthRouter 类继承自 hunomina\Routing\Router 类。

因此,它可以通过调用 request(string $method, string $url) 方法来处理请求,该方法必须返回路由操作响应。

阅读 此文档 以了解基本路由系统的工作原理。

可以通过传递路由文件、AuthenticationCheckerInterface 实例和一个类型(json, yaml... 如果需要可以扩展)来实例化此类。

路由文件语法与 hunomina\Routing\Router 路由文件语法相同。

示例 在此处

AuthenticationCheckerInterface

AuthenticationCheckerInterface 有三个方法

  • bool isAuthenticated() : 如果用户连接到您的应用程序,则返回 true。您可以使用任何您想要的:cookies、sessions、headers...
  • ?UserInterface getAuthenticatedUser() : 根据会话、cookie、headers... 返回已认证的用户
  • bool checkAuthorization(?UserInterface $user, SecurityContext $securityContext, string $method, string $url) : 如果根据安全上下文,特定用户可以访问到路由(方法 + url),则返回 true

为了使 AuthRouter 与您的应用程序一起工作,您必须创建一个类,该类实现 AuthenticationCheckerInterface 接口及其方法。

如果需要,您绝对可以添加一些方法。

UserInterface

UserInterface 必须由所有将登录到您的应用程序的用户实体实现。

此接口有两个方法

  • string[] getRoles() : 返回用户的安全上下文角色列表
  • string getUsername() : 返回用于认证用户的用户名

SecurityContext

允许为特定路由定义基于角色的规则。

此类从配置文件中加载安全上下文,检查其有效性,并根据配置文件实例化多个 RoleRule 对象。

然后您可以在 AuthenticationChecker 应用程序实例中使用安全上下文对象来检查用户的权限。

此类是抽象的,您必须实现两个方法

  • void load(): 一旦配置文件验证通过,则加载它并实例化 RoleRule 对象以符合配置
  • bool isSecurityContextValid() : 如果配置文件语法有效,则返回 true

此软件包包含两个内置的 SecurityContext 实现

如果您想添加新的 SecurityConext 类型,您需要创建两个类

  • 一个类扩展 AuthRouter 类,以便能够使用新的 SecurityContext 类型
  • 一个类扩展 SecurityContext 类,以便创建新的配置文件解析器

Role

Role 只是一个带有子角色的名称。

此类有两个属性

  • string $_name : 角色的名称
  • Role[] $_children : 子角色的列表。允许定义角色层次结构

和一个方法

  • bool contains(Role $role) : 如果 Role 实例是 $role 或作为 $role 的子角色,则返回 true

Rule

Rule 有 3 个属性

  • string $_path : 规则必须应用的 url 的伪正则表达式。 "伪正则表达式" 意味着它是一个没有 "/" 转义的正则表达式
  • string[] $_methods : http 方法的列表。限制规则可以匹配的 http 方法
  • Role[] $_roles : 可以使用 $_methods http 方法访问 $_path 的 Role 列表

这三个属性都传递给构造函数。确保所有这些属性都有效(例如,对于 $_path 属性,有效的伪正则表达式)

YamlSecurityContext

YamlSecurityContext 是一个内置的 SecurityContext 实现。

它允许您为应用程序 AuthRouter SecurityContext 使用 Yaml 配置文件。如果您使用此 SecurityContext 类,则必须遵循此简单的配置文件语法

  • 有一个根元素 security
  • 有两个子元素:auth_firewallrole_hierarchy
  • auth_firewall 包含所有应用程序防火墙规则列表。
  • role_hierarchy 包含所有应用程序角色及其层次结构。

每个规则由以下内容组成

  • path : Rule 对象的伪正则表达式。
  • roles : 规则使用的字符串或字符串列表。如果为空,则没有任何东西可以验证规则。
  • methods : 用来匹配规则的可选 http 方法列表

每个角色由以下内容组成

  • 一个键:角色名称
  • 一个值:子角色的字符串或字符串列表

例如 这里(Yaml)

JsonSecurityContext

JsonSecurityContext 同样是一个内置的 SecurityContext 实现。

它允许您为应用程序 AuthRouter SecurityContext 使用 Json 配置文件。

对于这个SecurityContext类,配置文件的语法与YamlSecurityContext相同。

示例在此(Json格式)

示例

更多示例,请查看此处