Trongate Docs
switch to dark modeswitch to dark mode
»
»
How To Attach Tokens To Requests

How To Attach Tokens To Requests

Attaching A Token To An HTTP Header

Within the JavaScript community, it's considered a good practice to attach security tokens onto the header sections of your HTTP requests.  We can attach a Trongate security token to the header of our HTTP requests like so:

​setRequestHeader("trongateToken", token)

Just To Let You Know
The code above assumes that we have a token variable declared in JavaScript.

Passing Tokens From PHP To JavaScript

Sometimes, it's necessary to pass Trongate security tokens from PHP to JavaScript.  This process starts at the controller file level.  So, inside a controller, we can fetch a Trongate security token with:

$this->module('trongate_tokens');
$token = $this->trongate_tokens->_attempt_get_valid_token();

We can then pass our fetched token into a view file as part of a $data array.  Doing so, means that the token can be accessed - using PHP - from inside of view files or template files.  For example:

//assuming that this a controller file...
function display() {
    $this->module('trongate_tokens');
    $data['token'] = $this->trongate_tokens->_attempt_get_valid_token();
    $this->template('members', $data);
}

Don't forget, PHP can easily output our token from inside any view file, or template file, with:

<?= $token ?>

Let's also remember that it's acceptable and normal to have JavaScript code inside HTML.  The screenshot below shows an example of this,

JavaScript code inside a view file

All of this means that it's possible to take a token value from the controller and to pass that value onto an HTTP request header that is being created by JavaScript.  In the screenshot below (which is from a view file) we have an example of some JavaScript code that invokes an HTTP POST request.  On line 7, you can see that PHP is being mixed in with JavaScript to assist in establishing a 'baseUrl' value in JavaScript.  On line 8, PHP is being used to establish a 'token' variable, in JavaScript.

mixing PHP with JavaScript

Now that you know how to attach Trongate security tokens onto your HTTP requests, let's explore the six different API authorization mechanisms that are available with the Trongate framework.




HELP & SUPPORT

If you have a question or a comment relating to anything you've see here, please goto the Help Bar.

 
×