Fetching Tokens
The Trongate framework provides a robust mechanism for fetching and validating user tokens, which is crucial for implementing secure authentication and authorization in your applications. This page explores the _attempt_get_valid_token() method - a key component of Trongate's token management system.
The Mechanics Of Token Retrieval
When an end user is allocated with a 'Trongate token', the important details pertaining to the token are stored on the trongate_tokens
database table.
Upon subsequent visits to the application, the _attempt_get_valid_token() may be used to retrieve and validate user tokens.
The _attempt_get_valid_token() is a versatile function that can adapt to various authentication scenarios.
Method Signature
public function _attempt_get_valid_token($user_levels = null): string|bool
Parameters
Parameter | Type | Description | Default | Required |
---|---|---|---|---|
$user_levels |
int|array|null | User levels to filter tokens | null |
No |
Return Value
The method returns either a string (the valid token) or a boolean false if no valid token is found.
Token Retrieval Process
The method searches for tokens in the following locations, in order of priority:
- HTTP headers (
$_SERVER['HTTP_TRONGATETOKEN']
) - Cookies (
$_COOKIE['trongatetoken']
) - Session (
$_SESSION['trongatetoken']
)
Usage Examples
Example 1: Fetching Any Valid Token
To retrieve a valid token for any user level:
$this->module('trongate_tokens');
$token = $this->trongate_tokens->_attempt_get_valid_token(); // Any user level
Example 2: Fetching Token for Specific User Level
To fetch a token for users with an 'admin' user level (assuming 'admin' has an ID of 1 in the 'trongate_user_levels' table):
$this->module('trongate_tokens');
$token = $this->trongate_tokens->_attempt_get_valid_token(1); // admin only
Example 3: Fetching Token for Multiple User Levels
To retrieve a token for users with either 'admin' or 'member' user levels (assuming IDs 1 and 2 respectively):
$this->module('trongate_tokens');
$token = $this->trongate_tokens->_attempt_get_valid_token([1, 2]); // admin or member
By understanding and implementing these token fetching techniques, developers can ensure secure and efficient authentication and authorization in their Trongate applications.