Skip to content
intermediate Phase 71 · Security Fundamentals

Authentication in Magento

45m
2 problems
Topic Progress 0%

Admin Login Authentication

Admin Login Flow

Magento uses session-based authentication for admin users with multi-factor authentication support.

// app/code/Vendor/Module/Model/Auth.php
namespace Vendor\Module\Model;

use Magento\Backend\Model\Auth;
use Magento\User\Model\UserFactory;

class CustomAuth extends Auth
{
    private $userFactory;

    public function __construct(
        UserFactory $userFactory
    ) {
        $this->userFactory = $userFactory;
    }

    public function login($username, $password)
    {
        $user = $this->userFactory->create()->load($username, 'username');
        
        if (!$user->getId()) {
            throw new \Exception('Invalid username');
        }

        if ($this->verifyPassword($password, $user->getPassword())) {
            $this->setUser($user);
            $this->processLogin();
            return true;
        }

        return false;
    }
}

Authentication Configuration

<!-- app/code/Vendor/Module/etc/adminhtml/system.xml -->
<config>
    <section id="admin">
        <group id="security">
            <field id="session_lifetime" translate="label" type="text">
                <label>Admin Session Lifetime (seconds)</label>
            </field>
            <field id="max_password_lifetime" translate="label" type="text">
                <label>Maximum Password Lifetime</label>
            </field>
        </group>
    </section>
</config>

Key Points

  • Admin sessions expire based on configured lifetime
  • Failed login attempts are logged and can trigger lockout
  • Password policies enforce complexity requirements
  • Session data is stored in the database by default

API Token Authentication

REST API Tokens

Magento supports token-based authentication for REST API access.

# Get admin token
curl -X POST "https://magento.example.com/rest/V1/integration/admin/token" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "admin123"
  }'

# Response: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Using API Tokens

# Use token in requests
curl -X GET "https://magento.example.com/rest/V1/products" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Integration Tokens

// Create integration with API access
use Magento\Integration\Model\IntegrationFactory;

class IntegrationTokenManager
{
    private $integrationFactory;

    public function createIntegration($name, $apiResources)
    {
        $integration = $this->integrationFactory->create();
        $integration->setName($name);
        $integration->setConsumerId($this->createConsumer($apiResources));
        $integration->setStatus(1);
        $integration->save();

        return $integration;
    }
}

Key Points

  • Admin tokens expire after 4 hours by default
  • Consumer tokens have restricted resource access
  • Tokens should be stored securely, never in version control
  • Use environment variables for token storage

Session Management

Session Configuration

// app/etc/env.php
return [
    'session' => [
        'save' => 'db',           // 'db', 'redis', or 'memcached'
        'save_path' => '/var/session',
        'session_cache_limiter' => 'private_no_cache',
    ],
];

Redis Session Storage

// app/etc/env.php
return [
    'session' => [
        'save' => 'redis',
        'redis' => [
            'host' => '127.0.0.1',
            'port' => '6379',
            'password' => '',
            'timeout' => '2.5',
            'persistent_identifier' => '',
            'database' => '0',
            'compression_threshold' => '2048',
        ],
    ],
];

Session Security

// Security headers for session protection
use Magento\Framework\Controller\Result\RedirectFactory;

class SecureSession
{
    public function setSecurityHeaders()
    {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header('X-XSS-Protection: 1; mode=block');
    }
}

Key Points

  • Redis/Memcached recommended for high-traffic stores
  • Session lifetime configurable per store view
  • Session hijacking prevented with secure cookies
  • Regenerate session ID after login

Password Hashing

Magento Password Hashing

Magento uses bcrypt with configurable work factors.

use Magento\Framework\Encryption\EncryptorInterface;

class PasswordManager
{
    private $encryptor;

    public function __construct(EncryptorInterface $encryptor)
    {
        $this->encryptor = $encryptor;
    }

    public function hashPassword($password)
    {
        // Uses bcrypt with work factor 12
        return $this->encryptor->getHash($password);
    }

    public function verifyPassword($password, $hash)
    {
        return $this->encryptor->validateHash($password, $hash);
    }
}

Password Policy Configuration

<!-- app/code/Vendor/Module/etc/adminhtml/system.xml -->
<field id="password_policy" translate="label" type="text">
    <label>Password Policy</label>
    <comment><![CDATA[
        Minimum 8 characters, at least one uppercase, one lowercase,
        one number, one special character
    ]]></comment>
</field>

Custom Hash Algorithm

// Override default hashing (not recommended)
namespace Vendor\Module\Model\Encryption;

use Magento\Framework\Encryption\CryptInterface;

class CustomCrypt implements CryptInterface
{
    public function hash($data)
    {
        return password_hash($data, PASSWORD_ARGON2ID);
    }
}

Key Points

  • Bcrypt work factor increases with hardware improvements
  • Passwords are never stored in plain text
  • Hash rehashing happens automatically on login if needed
  • Password reset tokens expire after 24 hours

Practice Problems

0 / 2 solved
Implement Custom Authentication

Create a custom authentication plugin that adds IP-based access control to admin login.

Solution
<?php
namespace Vendor\Module\Plugin;

class AuthPlugin
{
    private $allowedIps = ['192.168.1.0/24'];

    public function beforeLogin(
        \Magento\Backend\Model\Auth $subject,
        $username,
        $password
    ) {
        $request = $this->request;
        $ip = $request->getServerValue('REMOTE_ADDR');
        
        if (!$this->isIpAllowed($ip)) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('Access denied from your IP address')
            );
        }
    }
}
Token Security Audit

Review and improve the security of API token handling in a Magento integration.

Solution
// Security improvements:
// 1. Store in env vars, not code
// 2. Always use HTTPS
// 3. Implement refresh token flow
// 4. Add token revocation endpoint
// 5. Log token usage

Quiz

1. How does Magento authenticate admin users by default?

Question 1 options

2. What is the default expiration for admin REST API tokens?

Question 2 options

3. Which session storage is recommended for production?

Question 3 options

4. What hashing algorithm does Magento use by default?

Question 4 options

Flashcards

Question

Magento admin auth method?

Answer

Session-based with form_key CSRF protection

Question

Default API token expiration?

Answer

4 hours for admin tokens

Question

Recommended session storage?

Answer

Redis or Memcached for production

Question

Password hashing algorithm?

Answer

bcrypt with work factor 12

Revision Notes

Key Takeaways

  • 1. Admin uses session + form_key for CSRF protection
  • 2. API tokens expire in 4 hours by default
  • 3. Use Redis/Memcached for session storage in production
  • 4. bcrypt hashing with configurable work factor

Interview Tips

  • Explain the difference between admin and API authentication
  • Discuss session security best practices
  • Know how password hashing works in Magento

Cheat Sheet

Magento Auth

  • Admin: Session + form_key
  • API: Bearer token (4hr expiry)
  • Sessions: Redis recommended
  • Passwords: bcrypt (work factor 12)
  • MFA: Available for admin