Welcome Guest, Not a member yet? Register   Sign In
How to include token in API rest
#4
Lightbulb 
(This post was last modified: 07-08-2017, 04:31 AM by arisroyo. Edit Reason: Change constant for generated key )

Here my example Angel

1. I create Libraries Jsonwebtokens.php and put it on /application/libraries
2. Download https://github.com/firebase/php-jwt and put on /application/third_party/firebase-jwt
3. Here how I used it

Example:

PHP Code:
$this->load->library('jsonwebtokens');
$data = array('email' => $email);
$token $this->jsonwebtokens->generate_jswt($data,'P30D'); 

Jsonwebtokens.php
PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

use \
Firebase\JWT\JWT;

class 
Jsonwebtokens {

public function 
init() {
include 
APPPATH 'third_party/firebase-jwt/JWT.php';
}

public function 
 generate_jswt($data = array(), $validity 'P30D') {

$CI =& get_instance();

$this->init();
$jwt '';

$date = new DateTime();
$timeStart $date->getTimestamp();
$date->add(new DateInterval($validity));
$timeEnd $date->getTimestamp();

/*
* iss – Issuer application.
* iat – timestamp of token issuing.
* nbf – Timestamp of when the token should start being considered valid.
* exp – Timestamp of when the token should cease to be valid.
* data – Array of data
*/

try {

$token = array(
"iss" => "MyApplicationName.com",
"aud" => "MyApplication Name",
"iat" => $timeStart,
"nbf" => $timeStart,
"exp" => $timeEnd,
"data" => $data);

$jwt JWT::encode($token"MyGeneratedKey","HS256");

} catch (
Exception $ex) {
log_message('error',$ex->getMessage());
} finally {
return 
$jwt;
}


}

public function 
 validate_jswt($token) {

$this->init();

$jwt null;

try {
$jwt JWT::decode($token"MyGeneratedKey",array("HS256"));
} catch (
Exception $ex) {
log_message('error',$ex->getMessage());
} finally {
return 
$jwt;
}

}

There are those who tell lies with meaning behind them and those meaning less lies!
Reply


Messages In This Thread
How to include token in API rest - by avasquez - 07-04-2017, 07:53 AM
RE: How to include token in API rest - by rtenny - 07-05-2017, 01:24 AM
RE: How to include token in API rest - by arisroyo - 07-07-2017, 12:41 AM



Theme © iAndrew 2016 - Forum software by © MyBB