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. 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, that is, whether->user ->isLogged() user_idis in the session); - whether
user_tokenis 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 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
How do you correctly build links with user_token in a controller?
Never build admin URLs by concatenating strings like 'index.php?route=...'. Use $this and always pass the token from the session, not from $this. 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/.
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/), 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 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.

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/)
<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 & trap
The url->link() method returns a link where ampersands are escaped as &. 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({'&': '&'}) }}';
Or do the replacement in the controller using str_replace('&', '&', ...). 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.
- The token was not added to the link. This is most often forgotten for the "Cancel" link, pagination, sorting in lists, and delete buttons.
- The old
tokenparameter. Code carried over from 2.x generates&token=...and reads$this, which doesn't exist in 3.0 or 4.1.->session ->data['token'] - Double escaping of
&in a URL inserted into JavaScript (see the previous section). - 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/), the core will look for a nonexistent controller and return an error. Thex/ module/ x/ save |separator is automatically replaced with a dot. - Token in POST instead of GET. The check looks specifically at
$this, so a token in the body of a POST request won't help. It must be in the URL query string, even for POST.->request ->get - The session was lost. Different domains or protocols for the admin (with
wwwand without, http/https), an incorrectHTTP_SERVERinadmin/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. - 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" (routemarketplace/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.
| Aspect | OpenCart 3.0 | OpenCart 4.1 |
|---|---|---|
| Parameter name | user_token | user_token |
| Session key | session | session |
| Generation | token(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 method | extension/ | extension/ |
| Saving forms | mostly a regular POST and redirect | mostly AJAX with a JSON response |
| Consequence of a forgotten token | visible immediately: the login page opens | often 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, and for viewing, check->user ->hasPermission('modify', 'маршрут/ модуля') '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
Refererheader 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_tokenfrom it; - don't include external images and scripts in admin templates without need, and where possible configure the
Referrer-Policyheader 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_tokenis generated during login, stored in$this, and checked on every admin request together with the fact of authorization.->session ->data['user_token'] - Build all links and redirects through
$thiswith the token from the session. In 3.0 add->url ->link() 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
&doesn't end up in JavaScript. - Modules from 2.x with the
tokenparameter must be rewritten foruser_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.