No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
MVC-L: controllers, models, templates

user_token in OpenCart: links, AJAX and admin security in 3.0 and 4.1

How user_token works in the OpenCart admin: where it is generated, how to build links and AJAX requests correctly in 3.0 and 4.1, and why a module without it redirects you to the login page.

12 min read OC 3.0 OC 4.1

user_token in OpenCart is a random string that the core generates when you log in to the admin, stores in the session, and requires in the user_token parameter of every admin panel request. If the token is missing from the URL or doesn't match the session token, the controllerCode that receives a request and prepares data. More in the glossary → doesn't run and the user is redirected to the login page. For this reason, every link, redirect, or AJAX request in your module must carry the token. Otherwise, "the module logs me out of the admin" is the most common complaint from beginner developers.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What is user_token and where does it appear?

The token is created at the moment of successful admin login. The login controller generates a random 32-character string: in OpenCart 3.0 this is done by the token() function, and in OpenCart 4.1 by oc_token(). The string is stored in the session as $this->session->data['user_token']. After that, the user is redirected to the dashboard, and &user_token=... is already in the address bar.

Then, on every request to admin/index.php, the startup login check controller runs. It looks at three things:

  • whether the user is logged in ($this->user->isLogged(), that is, whether user_id is in the session);
  • whether user_token is present in the GET parameters of the request;
  • whether it matches the value in the session.

If at least one condition is not met, the requested route is replaced with the login page. Exceptions are made only for a few service routes: the login itself, password recovery, and password reset. For more on how a request reaches the startup controllers, see the article on the request path from index.php to the controller, which shows where this check happens.

Historical note: in OpenCart 2.x the parameter was simply called token. In 3.0 it was renamed to user_token. That is why old modules that use 'token=' . $this->session->data['token'] don't work in 3.0 and 4.1 without rewriting. When porting, this line is the first to break.

The token lives as long as the session does. After logging out of the admin or when the session expires, it becomes invalid, and a new one is generated at the next login. For how sessions work and where they are stored, see the article on session and cache drivers.

sequenceDiagram
    participant B as Browser
    participant L as startup/login
    participant S as Session
    participant C as Module controller
    B->>L: GET admin/index.php?route=...&user_token=abc
    L->>S: user_id and user_token?
    S-->>L: user_token = abc
    alt Token matches
        L->>C: Run the route
        C-->>B: HTML or JSON
    else Token is missing or different
        L-->>B: Login page
    end

Never build admin URLs by concatenating strings like 'index.php?route=...'. Use $this->url->link() and always pass the token from the session, not from $this->request->get. The session value is guaranteed to exist if the controller received control at all. The GET parameter formally exists too, but the habit of taking the token from the request sooner or later leads to "Undefined index" errors in methods that are called differently, such as through events or child controllers.

OpenCart 3.0

The third argument of true historically means an SSL link. In 3.0 it is always passed. Methods in a route are separated by a slash: extension/module/mymodule/save.

Example

class ControllerExtensionModuleMymodule extends Controller {
    public function index() {
        $this->load->language('extension/module/mymodule');

        $data['action'] = $this->url->link('extension/module/mymodule', 'user_token=' . $this->session->data['user_token'], true);
        $data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);

        // для JS у шаблоні
        $data['user_token'] = $this->session->data['user_token'];

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('extension/module/mymodule', $data));
    }
}

OpenCart 4.1

The SSL parameter has been removed. ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → live in their own folders (extension/назва_розширення/module/...), and the method is separated by a dot: .save. The core automatically replaces the old | separator with a dot. For details on route syntax, see the article on route= routing in 3.0 and 4.1.

Example

namespace Opencart\Admin\Controller\Extension\Mymodule\Module;

class Mymodule extends \Opencart\System\Engine\Controller {
    public function index(): void {
        $this->load->language('extension/mymodule/module/mymodule');

        $data['save'] = $this->url->link('extension/mymodule/module/mymodule.save', 'user_token=' . $this->session->data['user_token']);
        $data['back'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module');
        $data['user_token'] = $this->session->data['user_token'];

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('extension/mymodule/module/mymodule', $data));
    }
}

The same applies to redirects. A $this->response->redirect() redirect in 3.0 without the token in the URL will send the user to the login page, even if they have just successfully saved a form. The general structure of an admin controller is covered in the article on controllers, data, and child controllers.

The «Extensions → Modules» list: the «Edit» buttons lead to the module controller with user_token in the address
The «Extensions → Modules» list: the «Edit» buttons lead to the module controller with user_token in the address · OpenCart 4.1.0.4

How do you pass user_token in an AJAX request?

An AJAX request from the admin is a regular HTTP request to admin/index.php, and the login check for it is exactly the same. Therefore the token must be in the request URL. The session cookie alone is not enough. There are two approaches: pass the token to the template as a separate variable, or generate the full URL in the controller.

Option 1: user_token variable in Twig

Example (OpenCart 3.0; in 4.1 the route will be extension/mymodule/module/mymodule.stats)

<script>
$('#button-stats').on('click', function () {
    $.ajax({
        url: 'index.php?route=extension/module/mymodule/stats&user_token={{ user_token }}',
        dataType: 'json',
        success: function (json) {
            if (json['error']) {
                alert(json['error']);
            }
            if (json['total']) {
                $('#stats-total').text(json['total']);
            }
        }
    });
});
</script>

This is exactly how autocomplete works in the core's standard forms: product, category, and manufacturerA product brand. Manufacturers have their own pages. More in the glossary → search. The relative URL index.php?... works because the page is already open in the admin/ catalog.

Option 2: a ready-made URL from the controller and the &amp; trap

The url->link() method returns a link where ampersands are escaped as &amp;. This is correct for the href attributeA product characteristic that does not affect the price: material, weight, power. It is set in "Catalog → Attributes" and displayed on the "Specification" tab. More in the glossary → in HTML. But if you insert such a string into JavaScript, the browser will send a parameter named amp;user_token. The server won't see the token and will return the login page.

In 4.1, the url->link() method has a third argument $js. If you pass true, the method returns a URL with & without escaping, specifically for use in JavaScript:

$data['stats_url'] = $this->url->link('extension/mymodule/module/mymodule.stats', 'user_token=' . $this->session->data['user_token'], true);

In 3.0, the third argument means SSL, so the escaping has to be replaced manually before output into JS:

Example

var statsUrl = '{{ stats_url|replace({'&amp;': '&'}) }}';

Or do the replacement in the controller using str_replace('&amp;', '&', ...). For more on variables and filters in templates, see the article on Twig in OpenCart.

Forms in OpenCart 4.1

In 4.1, settings forms are usually submitted via AJAX: the data-oc-toggle="ajax" attribute is on <form>, and action="{{ save }}" contains the URL with the token. The save() method returns JSON. If you forget the token in action, the Save button won't save anything. And an error parsing JSON will appear in the browser console, because the login page HTML was returned instead.

Why does the module redirect to the login page: common mistakes

The symptom is almost always the same: after a click or save, the user sees the login form, even though they were working in the admin a second ago. In AJAX this shows up as SyntaxError: Unexpected token '<' in the console: an HTML page came back instead of JSON. Check these in order.

  1. The token was not added to the link. This is most often forgotten for the "Cancel" link, pagination, sorting in lists, and delete buttons.
  2. The old token parameter. Code carried over from 2.x generates &token=... and reads $this->session->data['token'], which doesn't exist in 3.0 or 4.1.
  3. Double escaping of &amp; in a URL inserted into JavaScript (see the previous section).
  4. Wrong method separator in 4.1. The token is present, but the route isn't found. In 4.1 the method is separated by a dot; if you use a slash (extension/x/module/x/save), the core will look for a nonexistent controller and return an error. The | separator is automatically replaced with a dot.
  5. Token in POST instead of GET. The check looks specifically at $this->request->get, so a token in the body of a POST request won't help. It must be in the URL query string, even for POST.
  6. The session was lost. Different domains or protocols for the admin (with www and without, http/https), an incorrect HTTP_SERVER in admin/config.php, or a problematic session driver. The token is in the URL, but the session is new, so there's nothing to compare it against.
  7. Calling an admin route from outside. Cron, a payment systemA service that accepts cards: LiqPay, WayForPay, Monobank, and others. The commission depends on the contract. More in the glossary → webhook, or a delivery service has no admin session. Such handlers should be placed in the catalog/ directory, and in 4.1, for recurring tasks, there is "Extensions → Cron Jobs" (route marketplace/cron).

For the difference between the admin and catalog applications, and why webhooks cannot be attached to the admin, see the article on two applications on one core.

How does working with user_token differ between 3.0 and 4.1?

The idea itself has not changed: the token is generated during login, stored in the session, and checked on every request. What differs is the link syntax and how the admin interacts with the server.

AspectOpenCart 3.0OpenCart 4.1
Parameter nameuser_tokenuser_token
Session keysession->data['user_token']session->data['user_token']
Generationtoken(32)oc_token(32)
Calling url->link()third argument true (SSL)third argument $js: true returns a URL with & without escaping for JS
Route to a methodextension/module/x/saveextension/x/module/x.save
Saving formsmostly a regular POST and redirectmostly AJAX with a JSON response
Consequence of a forgotten tokenvisible immediately: the login page opensoften a "silent" JSON error in the console

The practical consequence for 4.1: since almost everything works through AJAX, a lost token is less visibly obvious. The form seems to have "submitted", but the success notification doesn't appear. Test every button with the console open.

One more detail for 4.1: the admin login form has its own one-time token in the session, separate from user_token. It protects the login form itself. For a module developer this is almost never important, but don't confuse these two values if you are writing your own authorization page or two-factor authentication.

For how the core parses routes with a dot and where to look for the extension controller, see the article on routing in 3.0 and 4.1.

Does user_token protect the admin, and what does it not do?

In essence, user_token is protection against CSRF. A third-party site can make the browser of a logged-in administrator open, for example, a product deletion URL: the browser attaches the session cookie automatically. But the attacker doesn't know the token, so the request will be rejected. Thanks to this, even GET links such as "delete" or "delete extension" cannot be forged from outside.

What the token does not do:

  • It does not replace permission checks. Any logged-in user has a valid token. Therefore, in every method that changes data, always check $this->user->hasPermission('modify', 'маршрут/модуля'), and for viewing, check 'access'. The token answers the question "is this request from our admin?", while permissions answer "is this user allowed to do this?"
  • It is not a password. The token alone gives nothing without the session cookie. But a token combined with a stolen cookie gives full access for as long as the session is alive.
  • It is not hidden. It sits in the address bar, and therefore ends up in browser history, screenshots, copied links, web server logs, and proxy logs. It also ends up in the Referer header if external resources are loaded from the admin page.

Practical habits that reduce risks:

  • log out of the admin using the logout button rather than just closing the tab: this destroys the session along with the token;
  • before sending a link to an admin page to support, remove user_token from it;
  • don't include external images and scripts in admin templates without need, and where possible configure the Referrer-Policy header on the server;
  • work with the admin only over HTTPS, so the token and cookie are not transmitted in plain text.

For more on protecting the panel (renaming the directory, IP restrictions, two-factor authentication), see the blog: OpenCart admin security and protection against hacking.

Summary

  • user_token is generated during login, stored in $this->session->data['user_token'], and checked on every admin request together with the fact of authorization.
  • Build all links and redirects through $this->url->link() with the token from the session. In 3.0 add true; in 4.1 use a dot for methods.
  • In AJAX the token must be in the URL (the GET part), not in the POST body. Make sure &amp; doesn't end up in JavaScript.
  • Modules from 2.x with the token parameter must be rewritten for user_token.
  • The token protects against CSRF, but does not replace hasPermission() and must not leave the boundaries of the admin.

Next, it's worth understanding how the controller forms JSON responses and processes the request. The article on Request and Response in OpenCart will help. Other topics on controllers, models, and templates are collected on the section page MVC-L: controllers, models, templates.

FAQ

Can you disable the user_token check in the admin?
Technically it is possible only by editing the core or modifying the startup controller, but this would expose the admin to CSRF attacks. It is better to fix the links in the module than to remove the protection.
Does the user_token change if you open the admin in several tabs?
No. Tabs of the same browser share one session, so the token is the same in all of them. A new token appears only after a new login.
What happens if two administrators work under the same user account?
Each browser has its own session and its own token, so they will not interfere with each other. However, for security and logs, it is better to create separate users.
How do you call an admin method of a module from cron or an external script?
You can't: without an administrator session the request will not pass the check. Move the logic into a controller in catalog or into a model and call it from there, and in 4.1 you can register a scheduled task.
Why is the user_token variable empty in a 3.0 template?
Most likely, the controller did not pass it into the $data array. Add $data['user_token'] = $this->session->data['user_token']; before calling load->view.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.