您好,欢迎访问一九零五行业门户网

使用 Symfony 安全组件进行用户身份验证

在本文中,您将了解如何使用 symfony 安全组件在 php 中设置用户身份验证。除了身份验证之外,我还将向您展示如何使用其基于角色的授权,您可以根据需要进行扩展。
symfony 安全组件
symfony 安全组件允许您轻松设置身份验证、基于角色的授权、csrf 令牌等安全功能。事实上,它又分为四个子组件,您可以根据需要进行选择。
安全组件具有以下子组件:
symfony/安全核心symfony/security-httpsymfony/security-csrfsymfony/security-acl在本文中,我们将探讨 symfony/security-core 组件提供的身份验证功能。
像往常一样,我们将从安装和配置说明开始,然后探索一些实际示例来演示关键概念。
安装和配置在本节中,我们将安装 symfony 安全组件。我假设您已经在系统上安装了 composer — 我们需要它来安装 packagist 上提供的安全组件。
因此,请继续使用以下命令安装安全组件。
$composer require symfony/security
在我们的示例中,我们将从 mysql 数据库加载用户,因此我们还需要一个数据库抽象层。让我们安装最流行的数据库抽象层之一:doctrine dbal。
$composer require doctrine/dbal
这应该创建了 composer.json 文件,它应该如下所示:
{ require: { symfony/security: ^4.1, doctrine/dbal: ^2.7 }}
让我们将 composer.json 文件修改为如下所示。
{ require: { symfony/security: ^4.1, doctrine/dbal: ^2.7 }, autoload: { psr-4: { sfauth\\: src }, classmap: [src] }}
由于我们添加了新的 classmap 条目,让我们继续通过运行以下命令来更新 composer 自动加载器。
$composer dump -o
现在,您可以使用 sfauth 命名空间来自动加载 src 目录下的类。
这就是安装部分,但是你应该如何使用它呢?事实上,只需将 composer 创建的 autoload.php 文件包含在您的应用程序中即可,如以下代码片段所示。
<?phprequire_once './vendor/autoload.php';// application code?>
现实世界的例子首先,让我们了解一下 symfony 安全组件提供的常规身份验证流程。
第一件事是检索用户凭据并创建未经身份验证的令牌。接下来,我们会将未经身份验证的令牌传递给身份验证管理器进行验证。身份验证管理器可能包含不同的身份验证提供程序,其中之一将用于对当前用户请求进行身份验证。如何对用户进行身份验证的逻辑在身份验证提供程序中定义。身份验证提供商联系用户提供商以检索用户。用户提供商有责任从相应的后端加载用户。用户提供程序尝试使用身份验证提供程序提供的凭据加载用户。大多数情况下,用户提供程序返回实现 userinterface 接口的用户对象。如果找到用户,身份验证提供程序会返回未经身份验证的令牌,您可以存储此令牌以供后续请求使用。在我们的示例中,我们要将用户凭据与 mysql 数据库进行匹配,因此我们需要创建数据库用户提供程序。我们还将创建处理身份验证逻辑的数据库身份验证提供程序。最后,我们将创建 user 类,它实现 userinterface 接口。
用户类在本节中,我们将创建 user 类,它代表身份验证过程中的用户实体。
继续创建包含以下内容的 src/user/user.php 文件。
<?phpnamespace sfauth\user;use symfony\component\security\core\user\userinterface;class user implements userinterface{ private $username; private $password; private $roles; public function __construct(string $username, string $password, string $roles) { if (empty($username)) { throw new \invalidargumentexception('no username provided.'); } $this->username = $username; $this->password = $password; $this->roles = $roles; } public function getusername() { return $this->username; } public function getpassword() { return $this->password; } public function getroles() { return explode(,, $this->roles); } public function getsalt() { return ''; } public function erasecredentials() {}}
重要的是 user 类必须实现 symfony security userinterface 接口。除此之外,这里没有任何异常。
数据库提供程序类从后端加载用户是用户提供者的责任。在本节中,我们将创建数据库用户提供程序,它从 mysql 数据库加载用户。
让我们创建包含以下内容的 src/user/databaseuserprovider.php 文件。
<?phpnamespace sfauth\user;use symfony\component\security\core\user\userproviderinterface;use symfony\component\security\core\user\userinterface;use symfony\component\security\core\exception\usernamenotfoundexception;use symfony\component\security\core\exception\unsupporteduserexception;use doctrine\dbal\connection;use sfauth\user\user;class databaseuserprovider implements userproviderinterface{ private $connection; public function __construct(connection $connection) { $this->connection = $connection; } public function loaduserbyusername($username) { return $this->getuser($username); } private function getuser($username) { $sql = select * from sf_users where username = :name; $stmt = $this->connection->prepare($sql); $stmt->bindvalue(name, $username); $stmt->execute(); $row = $stmt->fetch(); if (!$row['username']) { $exception = new usernamenotfoundexception(sprintf('username %s not found in the database.', $row['username'])); $exception->setusername($username); throw $exception; } else { return new user($row['username'], $row['password'], $row['roles']); } } public function refreshuser(userinterface $user) { if (!$user instanceof user) { throw new unsupporteduserexception(sprintf('instances of %s are not supported.', get_class($user))); } return $this->getuser($user->getusername()); } public function supportsclass($class) { return 'sfauth\user\user' === $class; }}
用户提供者必须实现 userproviderinterface 接口。我们使用 dbal 学说来执行与数据库相关的操作。由于我们已经实现了 userproviderinterface 接口,因此我们必须实现 loaduserbyusername、refreshuser 和 supportsclass 方法。loaduserbyusername 方法应通过用户名加载用户,这是在 getuser 方法中完成的。如果找到用户,我们返回对应的sfauth\user\user对象,该对象实现了userinterface接口。
另一方面, refreshuser 方法通过从数据库获取最新信息来刷新提供的 user 对象。
最后,supportsclass 方法检查 databaseuserprovider 提供程序是否支持提供的用户类。
数据库身份验证提供程序类最后,我们需要实现用户身份验证提供程序,它定义身份验证逻辑 - 如何对用户进行身份验证。在我们的例子中,我们需要将用户凭据与 mysql 数据库进行匹配,因此我们需要相应地定义身份验证逻辑。
继续创建包含以下内容的 src/user/databaseauthenticationprovider.php 文件。
<?phpnamespace sfauth\user;use symfony\component\security\core\authentication\provider\userauthenticationprovider;use symfony\component\security\core\user\userproviderinterface;use symfony\component\security\core\user\usercheckerinterface;use symfony\component\security\core\exception\usernamenotfoundexception;use symfony\component\security\core\exception\authenticationserviceexception;use symfony\component\security\core\authentication\token\usernamepasswordtoken;use symfony\component\security\core\user\userinterface;use symfony\component\security\core\exception\authenticationexception;class databaseauthenticationprovider extends userauthenticationprovider{ private $userprovider; public function __construct(userproviderinterface $userprovider, usercheckerinterface $userchecker, string $providerkey, bool $hideusernotfoundexceptions = true) { parent::__construct($userchecker, $providerkey, $hideusernotfoundexceptions); $this->userprovider = $userprovider; } protected function retrieveuser($username, usernamepasswordtoken $token) { $user = $token->getuser(); if ($user instanceof userinterface) { return $user; } try { $user = $this->userprovider->loaduserbyusername($username); if (!$user instanceof userinterface) { throw new authenticationserviceexception('the user provider must return a userinterface object.'); } return $user; } catch (usernamenotfoundexception $e) { $e->setusername($username); throw $e; } catch (\exception $e) { $e = new authenticationserviceexception($e->getmessage(), 0, $e); $e->settoken($token); throw $e; } } protected function checkauthentication(userinterface $user, usernamepasswordtoken $token) { $currentuser = $token->getuser(); if ($currentuser instanceof userinterface) { if ($currentuser->getpassword() !== $user->getpassword()) { throw new authenticationexception('credentials were changed from another session.'); } } else { $password = $token->getcredentials(); if (empty($password)) { throw new authenticationexception('password can not be empty.'); } if ($user->getpassword() != md5($password)) { throw new authenticationexception('password is invalid.'); } } }}
databaseauthenticationprovider 身份验证提供程序扩展了 userauthenticationprovider 抽象类。因此,我们需要实现 retrieveuser 和 checkauthentication 抽象方法。
retrieveuser 方法的作用是从相应的用户提供程序加载用户。在我们的例子中,它将使用 databaseuserprovider 用户提供程序从 mysql 数据库加载用户。
另一方面,checkauthentication 方法执行必要的检查以验证当前用户的身份。请注意,我使用 md5 方法进行密码加密。当然,您应该使用更安全的加密方法来存储用户密码。
整体工作原理到目前为止,我们已经创建了身份验证所需的所有元素。在本节中,我们将了解如何将它们组合在一起来设置身份验证功能。
继续创建 db_auth.php 文件并使用以下内容填充它。
<?phprequire_once './vendor/autoload.php';use sfauth\user\databaseuserprovider;use symfony\component\security\core\user\userchecker;use sfauth\user\databaseauthenticationprovider;use symfony\component\security\core\authentication\authenticationprovidermanager;use symfony\component\security\core\authentication\token\usernamepasswordtoken;use symfony\component\security\core\exception\authenticationexception;// init doctrine db connection$doctrineconnection = \doctrine\dbal\drivermanager::getconnection( array('url' => 'mysql://{username}:{password}@{hostname}/{database_name}'), new \doctrine\dbal\configuration());// init our custom db user provider$userprovider = new databaseuserprovider($doctrineconnection);// we'll use default userchecker, it's used to check additional checks like account lock/expired etc.// you can implement your own by implementing usercheckerinterface interface$userchecker = new userchecker();// init our custom db authentication provider$dbprovider = new databaseauthenticationprovider( $userprovider, $userchecker, 'frontend');// init authentication provider manager$authenticationmanager = new authenticationprovidermanager(array($dbprovider));try { // init un/pw, usually you'll get these from the $_post variable, submitted by the end user $username = 'admin'; $password = 'admin'; // get unauthenticated token $unauthenticatedtoken = new usernamepasswordtoken( $username, $password, 'frontend' ); // authenticate user & get authenticated token $authenticatedtoken = $authenticationmanager->authenticate($unauthenticatedtoken); // we have got the authenticated token (user is logged in now), it can be stored in a session for later use echo $authenticatedtoken; echo \n;} catch (authenticationexception $e) { echo $e->getmessage(); echo \n;}
回想一下本文开头讨论的身份验证流程 - 上面的代码反映了该顺序。
第一件事是检索用户凭据并创建未经身份验证的令牌。
$unauthenticatedtoken = new usernamepasswordtoken( $username, $password, 'frontend');
接下来,我们将该令牌传递给身份验证管理器进行验证。
// authenticate user & get authenticated token$authenticatedtoken = $authenticationmanager->authenticate($unauthenticatedtoken);
当调用authenticate方法时,幕后会发生很多事情。
首先,身份验证管理器选择适当的身份验证提供程序。在我们的例子中,它是 databaseauthenticationprovider 身份验证提供程序,将选择它进行身份验证。
接下来,它通过 databaseuserprovider 用户提供程序中的用户名检索用户。最后,checkauthentication 方法执行必要的检查以验证当前用户请求。
如果您希望测试 db_auth.php 脚本,则需要在 mysql 数据库中创建 sf_users 表。
create table `sf_users` ( `id` int(11) not null auto_increment, `username` varchar(255) not null, `password` varchar(255) not null, `roles` enum('registered','moderator','admin') default null, primary key (`id`)) engine=innodb;insert into `sf_users` values (1,'admin','21232f297a57a5a743894a0e4a801fc3','admin');
继续运行 db_auth.php 脚本,看看效果如何。成功完成后,您应该会收到一个经过身份验证的令牌,如以下代码片段所示。
$php db_auth.phpusernamepasswordtoken(user=admin, authenticated=true, roles=admin)
用户通过身份验证后,您可以将经过身份验证的令牌存储在会话中以供后续请求使用。
至此,我们就完成了简单的身份验证演示!
结论今天,我们研究了 symfony 安全组件,它允许您在 php 应用程序中集成安全功能。具体来说,我们讨论了 symfony/security-core 子组件提供的身份验证功能,并且我向您展示了如何在您自己的应用程序中实现此功能的示例。
请随意使用下面的提要发表您的想法!
以上就是使用 symfony 安全组件进行用户身份验证的详细内容。
其它类似信息

推荐信息