问题描述
我有一个在Cake PHP 3.8.13和CakeDC Users 8.5.1上运行的CakePHP应用程序。
我目前能够使用用户名字段登录,但是我想使用电子邮件字段进行身份验证。我已经按照https://github.com/CakeDC/users/blob/master/Docs/Documentation/Configuration.md#using-the-users-email-to-login上的说明进行操作,但是系统仍在尝试使用用户名字段。如果我在src / Template / Plugin / CakeDC / Users / Users / login.ctp中将电子邮件更改为用户名,则可以使用用户名登录。
src / Application.PHP
<?PHP
namespace App;
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Http\Middleware\SecurityHeadersMiddleware;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Cake\Http\Middleware\EncryptedCookieMiddleware;
class Application extends BaseApplication
{
/**
* {@inheritDoc}
*/
public function bootstrap()
{
// Call parent to load bootstrap from files.
parent::bootstrap();
$this->addplugin('AuditStash');
if (PHP_SAPI === 'cli') {
try {
$this->addplugin('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
$this->addplugin('Migrations');
}
/*
* Only try to load DebugKit in development mode
* Debug Kit should not be installed on a production system
*/
if (Configure::read('debug')) {
$this->addplugin(\DebugKit\Plugin::class);
}
$this->addplugin(\CakeDC\Users\Plugin::class);
Configure::write('Users.config',['users']);
$identifiers = Configure::read('Auth.Identifiers');
$identifiers['Authentication.Password']['fields']['username'] = 'email';
Configure::write('Auth.Identifiers',$identifiers);
}
/**
* Setup the middleware queue your application will use.
*
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
* @return \Cake\Http\MiddlewareQueue The updated middleware queue.
*/
public function middleware($middlewareQueue)
{
$securityHeaders = new SecurityHeadersMiddleware();
$securityHeaders
->setCrossDomainPolicy()
->setReferrerPolicy()
->setXFrameOptions()
->setXssprotection()
->noopen()
->noSniff();
$middlewareQueue
// Add security headers
->add($securityHeaders)
// Catch any exceptions in the lower layers,// and make an error page/response
->add(ErrorHandlerMiddleware::class)
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => Configure::read('Asset.cacheTime')
]))
// Add routing middleware.
// Routes collection cache enabled by default,to disable route caching
// pass null as cacheConfig,example: `new RoutingMiddleware($this)`
// you might want to disable this cache in case your routing is extremely simple
->add(new RoutingMiddleware($this,'_cake_routes_'));
$cookies = new EncryptedCookieMiddleware(
// Names of cookies to protect
['remember_me','csrftoken'],Configure::read('Security.cookieKey')
);
$middlewareQueue->add($cookies);
return $middlewareQueue;
}
}
<?PHP
return [
// Table used to manage users
'table' => 'Users',// Controller used to manage users plugin features & actions
'controller' => 'Users',// configure Auth component
'auth' => true,// Password Hasher
'passwordHasher' => '\Cake\Auth\DefaultPasswordHasher',// token expiration,1 hour
'Token' => ['expiration' => 3600],'Email' => [
// determines if the user should include email
'required' => true,// determines if registration workflow includes email validation
'validate' => true,],'Registration' => [
// determines if the register is enabled
'active' => false,// determines if the reCaptcha is enabled for registration
'reCaptcha' => true,// allow a logged in user to access the registration form
'allowLoggedIn' => false,//ensure user is active (confirmed email) to reset his password
'ensureActive' => false,// default role name used in registration
'defaultRole' => 'user','reCaptcha' => [
// reCaptcha key goes here
'key' => null,// reCaptcha secret
'secret' => null,// use reCaptcha in registration
'registration' => false,// use reCaptcha in login,valid values are false,true
'login' => false,'Tos' => [
// determines if the user should include tos accepted
'required' => true,'Social' => [
// enable social login
'login' => false,// enable social login
'authenticator' => 'CakeDC/Users.social','GoogleAuthenticator' => [
// enable Google Authenticator
'login' => false,'issuer' => null,// The number of digits the resulting codes will be
'digits' => 6,// The number of seconds a code will be valid
'period' => 30,// The algorithm used
'algorithm' => 'sha1',// QR-code provider (more on this later)
'qrcodeprovider' => null,// Random Number Generator provider (more on this later)
'rngprovider' => null
],'Profile' => [
// Allow view other users profiles
'viewOthers' => false,'route' => ['plugin' => 'CakeDC/Users','controller' => '\Users','action' => 'profile'],'Key' => [
'Session' => [
// session key to store the social auth data
'social' => 'Users.social',// userId key used in reset password workflow
'resetPasswordUserId' => 'Users.resetPasswordUserId',// form key to store the social auth data
'Form' => [
'social' => 'social'
],'Data' => [
// data key to store the users email
'email' => 'email',// data key to store email coming from social networks
'socialEmail' => 'info.email',// data key to check if the remember me option is enabled
'rememberMe' => 'remember_me',// Avatar placeholder
'Avatar' => ['placeholder' => 'CakeDC/Users.avatar_placeholder.png'],'RememberMe' => [
// configure Remember Me component
'active' => false,'checked' => true,'Cookie' => [
'name' => 'remember_me','Config' => [
'expires' => '1 month','httpOnly' => true,]
]
],];
src /模板/插件/CakeDC/Users/Users/login.ctp
<?PHP
use Cake\Core\Configure;
?>
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __d('CakeDC/Users','Please enter your username and password') ?></legend>
<?= $this->Form->control('email',['required' => true]) ?>
<?= $this->Form->control('password',['required' => true]) ?>
</fieldset>
<?= $this->Form->button(__d('CakeDC/Users','Login')); ?>
<?= $this->Form->end() ?>
</div>
解决方法
添加此代码
$identifiers = Configure::read('Auth.Identifiers');
$identifiers['Authentication.Password']['fields']['username'] = 'email';
Configure::write('Auth.Identifiers',$identifiers);
转到您在Application中的pluginBootstrap()
函数,或确保在config / users.php文件中正确更新了标识符配置,因此该插件将能够在内部读取它并配置身份验证。