Admin URL Customization
Changing Admin URL
// bin/magento setup:config:set --backend-frontname="my-admin"
// Or via env.php:
return [
'backend' => [
'frontName' => 'my-admin-' . md5('unique-salt'),
],
];
Admin URL Security
// Verify admin URL in request
use Magento\Backend\Model\Url\Plugin\BackendUrl;
class AdminUrlSecurity
{
public function beforeGetBackendUrl(
BackendUrl $subject,
$routePath = null,
$params = []
) {
// Log admin URL access attempts
$this->logger->info('Admin URL accessed', [
'ip' => $this->request->getServerValue('REMOTE_ADDR'),
'url' => $this->request->getRequestUri(),
]);
}
}
Route Configuration
<!-- app/code/Vendor/Module/etc/adminhtml/routes.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="vendor_module" frontName="custom_admin_route">
<module name="Vendor_Module" />
</route>
</router>
</config>
Key Points
- Use unpredictable admin URLs (not just /admin)
- Consider using HTTPS-only for admin
- Monitor failed login attempts
- Rotate admin URL periodically for high-security environments
IP Whitelisting
Apache/Nginx IP Restriction
# .htaccess for admin directory
<Directory "pub/admin">
Order Deny,Allow
Deny from All
Allow from 192.168.1.0/24
Allow from 10.0.0.1
</Directory>
# nginx.conf
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
proxy_pass http://magento;
}
Magento-Level IP Whitelisting
namespace Vendor\Module\Plugin;
class IpWhitelist
{
private $allowedIps = ['192.168.1.0/24', '10.0.0.1'];
public function beforeDispatch(
\Magento\Framework\App\Action\Action $subject,
\Magento\Framework\App\RequestInterface $request
) {
if (!$this->isAdminRoute($request)) {
return;
}
$clientIp = $request->getServerValue('REMOTE_ADDR');
if (!$this->isIpAllowed($clientIp)) {
throw new \Magento\Framework\Exception\LocalizedException(
__('Access denied from your IP address')
);
}
}
private function isIpAllowed($ip)
{
foreach ($this->allowedIps as $allowed) {
if ($this->ipInCidr($ip, $allowed)) {
return true;
}
}
return false;
}
}
Key Points
- Layer IP restrictions: network + application level
- Use CIDR notation for IP ranges
- Maintain a whitelist of allowed IPs
- Log denied access attempts for monitoring
Two-Factor Authentication (2FA)
Magento 2FA Configuration
// Enable 2FA for admin users
use Magento\TwoFactorAuth\Model\TfaInterface;
class TwoFactorSetup
{
private $tfa;
public function enable2fa($userId)
{
$provider = $this->tfa->getProvider('totp');
$secret = $provider->generateSecret();
$this->saveUserSecret($userId, $secret);
return $provider->getQrCodeUrl($secret);
}
public function verify2fa($userId, $code)
{
$secret = $this->getUserSecret($userId);
$provider = $this->tfa->getProvider('totp');
return $provider->verify($secret, $code);
}
}
2FA Provider Options
// Available 2FA providers in Magento:
// 1. TOTP (Google Authenticator, Authy)
// 2. U2F (YubiKey)
// 3. Email OTP
// 4. Duo Security
// Configure via admin:
// Stores > Configuration > Security > Two-Factor Auth
// Force 2FA for all admins
$connection->update('admin_user', ['tfa_enabled' => 1]);
Backup Codes
// Generate backup codes
public function generateBackupCodes($userId)
{
$codes = [];
for ($i = 0; $i < 10; $i++) {
$codes[] = bin2hex(random_bytes(4));
}
$hashedCodes = array_map(function($code) {
return password_hash($code, PASSWORD_BCRYPT);
}, $codes);
$this->saveBackupCodes($userId, $hashedCodes);
return $codes; // Show to user once
}
Key Points
- 2FA significantly reduces account compromise risk
- TOTP (time-based) is most common implementation
- Backup codes prevent lockout
- Consider mandatory 2FA for admin users
Admin Security Settings
Session Security
// app/etc/env.php
return [
'admin' => [
'security' => [
'session_lifetime' => 900, // 15 minutes
'password_lifetime' => 90, // 90 days
'password_lockout_attempts' => 5, // Lock after 5 failures
'password_lockout_period' => 15, // Lock for 15 minutes
'session_maxlifetime_web' => 480, // 8 hours for web
'session_maxlifetime_admin' => 240, // 4 hours for admin
],
],
];
Password Policy
// Enforce strong passwords
use Magento\User\Model\User\Validation as UserValidation;
class StrongPassword
{
public function validate($password)
{
$errors = [];
if (strlen($password) < 12) {
$errors[] = 'Password must be at least 12 characters';
}
if (!preg_match('/[A-Z]/', $password)) {
$errors[] = 'Password must contain uppercase letter';
}
if (!preg_match('/[a-z]/', $password)) {
$errors[] = 'Password must contain lowercase letter';
}
if (!preg_match('/[0-9]/', $password)) {
$errors[] = 'Password must contain number';
}
if (!preg_match('/[^A-Za-z0-9]/', $password)) {
$errors[] = 'Password must contain special character';
}
return $errors;
}
}
Security Headers
// Force security headers for admin
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval';";
Key Points
- Short session lifetimes for admin
- Strong password policies (12+ characters)
- Account lockout after failed attempts
- Security headers prevent common attacks
Practice Problems
0 / 1 solved
IP Whitelist Plugin
Create a plugin that restricts admin access to specific IP ranges.
Solution
<?php
namespace Vendor\Module\Plugin;
class AdminIpRestriction
{
private $allowedIps = ['192.168.1.0/24', '10.0.0.1'];
private $logger;
public function beforeDispatch(
\Magento\Framework\App\Action\Action $subject,
\Magento\Framework\App\RequestInterface $request
) {
$fullActionName = $request->getFullActionName();
if (strpos($fullActionName, 'adminhtml_') !== 0) {
return;
}
$ip = $request->getServerValue('REMOTE_ADDR');
if (!$this->isIpAllowed($ip)) {
$this->logger->warning('Admin access denied', ['ip' => $ip]);
throw new \Magento\Framework\Exception\LocalizedException(
__('Access denied')
);
}
}
private function isIpAllowed($ip) {
foreach ($this->allowedIps as $allowed) {
if (strpos($allowed, '/') !== false) {
if ($this->ipInCidr($ip, $allowed)) {
return true;
}
} elseif ($ip === $allowed) {
return true;
}
}
return false;
}
} Quiz
1. What is the recommended admin session lifetime?
2. Which 2FA method uses Google Authenticator?
3. Why customize the admin URL?
4. What happens after 5 failed login attempts?
Flashcards
Question
Admin URL security?
Click to reveal answer
Answer
Use unpredictable URLs, not /admin
Question
2FA recommended?
Click to reveal answer
Answer
Yes, TOTP with Google Authenticator/Authy
Question
Admin session lifetime?
Click to reveal answer
Answer
15-30 minutes for security
Question
Password policy?
Click to reveal answer
Answer
12+ chars, uppercase, lowercase, number, special
Revision Notes
Key Takeaways
- 1. Use unpredictable admin URLs (not /admin)
- 2. Implement IP whitelisting at network and application level
- 3. Enable 2FA for all admin users
- 4. Short session lifetimes and strong password policies
Interview Tips
- • Explain layers of admin security
- • Discuss 2FA implementation options
- • Know how to configure security settings
Cheat Sheet
Admin Security
- URL: custom, unpredictable
- IP: whitelist allowed ranges
- 2FA: TOTP (Google Authenticator)
- Session: 15-30 min lifetime
- Password: 12+ chars, complex