PHP version 5
Author: Neuman Vong (neuman@twilio.com)
Author: Anant Narayanan (anant@php.net)
Ejemplo n.º 1
1
 public function muestra()
 {
     //$decoded =  JWT::decode($jwt, $this->clave, 'HS256');
     $clave = "beimarhuarachi";
     $user = array('nombre' => 'beimar', 'apellido' => 'huarachi');
     $jwt = JWT::encode($user, $clave, 'HS256');
     echo $jwt;
     echo "Login";
     $ahora = Carbon::now('America/La_Paz');
     $otra = Carbon::now('America/Halifax');
     $hoydia = Carbon::now();
     echo $ahora;
     echo "<br>";
     echo $hoydia;
     echo "<br>";
     echo $otra;
     echo "<br>";
     echo new Carbon('2015-12-12');
     $Y2K = Carbon::create(2000, 1, 1, 0, 0, 0);
     echo "<br>";
     echo $Y2K;
     echo "<br>";
     echo Carbon::parse('2015-02-12 12:00:12');
     //Es para obtener los datos de cualquier peticion(EL CLIENTE TIENE QUE ENVIAR LOS DATOS EN FORMATO JSON)
     //SI NOS ENVIA EN FORMATO DE FORMULARIO EL ACCESO SERIA DIRECTO
     //$entityBody = file_get_contents('php://input');
     //$objeto = json_decode($entityBody);
 }
Ejemplo n.º 2
1
 /**
  * Inicialización de la petición
  * ****************************************
  * Aqui debe ir la autenticación de la API
  * ****************************************
  */
 protected final function initialize()
 {
     $router = Router::get();
     // Habilitando CORS para hacer funcional el RESTful
     header('Access-Control-Allow-Origin: *');
     header('Access-Control-Allow-Credentials: true');
     // Habilitar todos los headers que recibe (Authorization sobre todo para manejar JWT)
     $requestHeaders = $this->getHeaders();
     $request = array_keys($requestHeaders);
     header("Access-Control-Allow-Headers: " . implode(',', $request) . ',Authorization');
     // Verificar los accesos y validez de token
     // TODO: Implementar un limit a la consultas de getAll() por seguridad cuando la vista sea pública
     if (!($this->publicView && ($router['method'] == 'GET' || $router['method'] == 'OPTIONS'))) {
         // Precendia del Token
         if (!empty($requestHeaders['Authorization'])) {
             $token = $requestHeaders['Authorization'];
             $this->me = JWT::decode(str_replace('Bearer ', '', $token), TOKEN);
             $now = time();
             // Verificamos que este activo
             if ($now >= $this->me->exp) {
                 $this->setCode(403);
                 die('Error 403 - Acceso Denegado');
             }
         } else {
             $this->setCode(403);
             die('Error 403 - Acceso Denegado');
         }
     }
 }
Ejemplo n.º 3
0
 public static function from_token($token, $secret)
 {
     $vector = explode(".", $token);
     if (count($vector) == 3) {
         $js = json_decode(base64_decode($vector[0]), true);
         $p = $vector[0] . "." . $vector[1];
         if ($vector[2] == hash_hmac($js["alg"], $p, $secret)) {
             $jwt = new JWT();
             $jwt->setHeader($js["alg"]);
             $jwt->setPayload(base64_decode($vector[1]));
         }
     }
     return $jwt;
 }
 public function execute()
 {
     $user = $this->getUser();
     if ($user->isBlocked()) {
         $this->dieUsageMsg('blockedtext');
     }
     if (!$user->isLoggedIn()) {
         $this->dieUsage('Must be logged in', 'token-impossible');
     }
     // Do not fatal out
     if (!class_exists('JWT')) {
         $this->dieUsage('JWT missing', 'token-impossible');
     }
     $config = $this->getConfig()->get('ContentTranslationCXServerAuth');
     $algorithm = $config['algorithm'];
     $key = $config['key'];
     if ($key === '') {
         $this->dieUsage('Key not configured', 'token-impossible');
     }
     $exp = time() + $config['age'];
     $token = array('sub' => $user->getName(), 'iat' => time(), 'exp' => $exp);
     $jwt = JWT::encode($token, $key, $algorithm);
     $this->getResult()->addValue(null, 'jwt', $jwt);
     $this->getResult()->addValue(null, 'exp', $exp);
 }
Ejemplo n.º 5
0
 function testKIDChooser()
 {
     $keys = array('1' => 'my_key', '2' => 'my_key2');
     $msg = JWT::encode('abc', $keys['1'], 'HS256', '1');
     $decoded = JWT::decode($msg, $keys, true);
     $this->assertEquals($decoded, 'abc');
 }
Ejemplo n.º 6
0
 public function login()
 {
     // check ajax request
     if ($this->input->is_ajax_request()) {
         // check post parameter
         if (!$this->input->post("username") || !$this->input->post("password")) {
             echo json_encode(array("code" => 2, "response" => "Data insufficient"));
         }
         $uname = $this->input->post("username");
         $password = $this->input->post("password");
         // check login
         $user = $this->Login_mdl->login($uname, $password);
         // $sid=$this->Login_mdl->addsession($user->user_id,$user->user_name,$user->db_pass);
         if ($user !== false) {
             $chksesstbl = $this->Login_mdl->check_active_user($user->user_id);
             if ($chksesstbl) {
                 $this->Login_mdl->reset_active_session($user->user_id);
             }
             $sessionid = session_id();
             $sid = $this->Login_mdl->add_new_session($user->user_id, $sessionid);
             $user->iat = time();
             $user->exp = time() + 28800000;
             //8 hr extend; default 5000
             $user->sid = $sid;
             //encdoe token
             $jwt = JWT::encode($user, SECRECT_KEY);
             echo json_encode(array("data" => $user, 'token' => $jwt, "status" => array("code" => 0, 'success' => true, 'msg' => $sessionid)));
         } else {
             echo json_encode(array("data" => '', 'token' => '', "status" => array("code" => 0, 'success' => false, 'msg' => '')));
         }
     }
 }
Ejemplo n.º 7
0
    /**
     * $scopes: should be an array with the follow structure:
     *
     *          'scope' => [
     *              'actions' => ['action1', 'action2']
     *          ],
     *          'scope2' => [
     *              'actions' => ['action1', 'action2']
     *          ]
     */
    public static function encode($client_id, $client_secret, $scopes = null, $custom_payload = null, $lifetime = 36000) {

            $time = time();

            $payload = array(
                "iat" => $time,
            );

            if ($scopes) {
                $payload["scopes"] = $scopes;
            }

            if ($scopes) {
                $custom_payload = array_merge($custom_payload, $payload);
            }

            $jti = md5(json_encode($payload));

            $payload['jti'] = $jti;
            $payload["exp"] = $time + $lifetime;
            $payload["aud"] = $client_id;

            $secret = base64_decode(strtr($client_secret, '-_', '+/'));

            $jwt = \JWT::encode($payload, $secret);

            return $jwt;


    }
Ejemplo n.º 8
0
 /**
  * Converts and signs a PHP object or array into a JWT string.
  *
  * @param object|array $payload PHP object or array
  * @param string|null  $alg     The signing algorithm. Supported
  *                              algorithms are 'HS256', 'HS384' and 'HS512'
  *
  * @return string      A signed JWT
  */
 public function encode($payload, $alg = null)
 {
     if (empty($alg)) {
         $alg = $this->alg;
     }
     return \JWT::encode($payload, $this->key, $alg);
 }
Ejemplo n.º 9
0
/**
 * @description Valida que el rol del usuario sea el correcto
 * @param $requerido
 */
function validateRol($requerido)
{
    global $jwt_enabled;
    if ($jwt_enabled == false) {
        return;
    }
    $requestHeaders = apache_request_headers();
    $authorizationHeader = isset($requestHeaders['Authorization']) ? $requestHeaders['Authorization'] : null;
    //    echo print_r(apache_request_headers());
    if ($authorizationHeader == null) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
    // // validate the token
    $pre_token = str_replace('Bearer ', '', $authorizationHeader);
    $token = str_replace('"', '', $pre_token);
    global $secret;
    global $decoded_token;
    $decoded_token = JWT::decode($token, $secret, true);
    $rol = $decoded_token->data->rol;
    if ($rol > $requerido) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
}
Ejemplo n.º 10
0
 /**
  * Most of the logic for ID token validation is in AuthTest -
  * this is just a general check to ensure we verify a valid
  * id token if one exists.
  */
 public function testValidateIdToken()
 {
     $this->checkToken();
     $client = $this->getClient();
     $token = $client->getAccessToken();
     if ($client->isAccessTokenExpired()) {
         $token = $client->fetchAccessTokenWithRefreshToken();
     }
     $segments = explode('.', $token['id_token']);
     $this->assertEquals(3, count($segments));
     // Extract the client ID in this case as it wont be set on the test client.
     $data = json_decode(JWT::urlSafeB64Decode($segments[1]));
     $verify = new Google_AccessToken_Verify();
     $payload = $verify->verifyIdToken($token['id_token'], $data->aud);
     $this->assertTrue(isset($payload['sub']));
     $this->assertTrue(strlen($payload['sub']) > 0);
     // TODO: Need to be smart about testing/disabling the
     // caching for this test to make sense. Not sure how to do that
     // at the moment.
     $client = $this->getClient();
     $data = json_decode(JWT::urlSafeB64Decode($segments[1]));
     $verify = new Google_AccessToken_Verify();
     $payload = $verify->verifyIdToken($token['id_token'], $data->aud);
     $this->assertTrue(isset($payload['sub']));
     $this->assertTrue(strlen($payload['sub']) > 0);
 }
Ejemplo n.º 11
0
 /**
  * @access  public
  * @param   array|object $data     An object or array of data you wish
  *                                 to associate with the token. It will
  *                                 be available as the variable "auth" in
  *                                 the Firebase rules engine.
  * @param   object       $options  Optional. An associative array with
  *                                 the developer supplied options for this
  *                                 token. The following keys are recognized:
  *
  *                                   'admin': Set to true if you want this
  *                                   token to bypass all security rules.
  *                                   Defaults to false.
  *
  *                                   'debug': Set to true if you want to
  *                                   enable debug output from your security
  *                                   rules.
  *
  *                                   'expires': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time at which the token
  *                                   should expire.
  *
  *                                   'notBefore': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time before which the
  *                                   should be rejected by the server.
  *                                   
  *
  * @return  string       A Firebase auth token.
  */
 public function createToken($data, $options = null)
 {
     $funcName = 'Services_FirebaseTokenGenerator->createToken';
     // If $data is JSONifiable, let it pass.
     $json = json_encode($data);
     if (function_exists("json_last_error") && ($errno = json_last_error())) {
         $this->handleJSONError($errno);
     } else {
         if ($json === "null" && $data !== null) {
             throw new UnexpectedValueException("Data is not valid JSON");
         } else {
             if (empty($data) && empty($options)) {
                 throw new Exception($funcName + ": data is empty and no options are set.  This token will have no effect on Firebase.");
             }
         }
     }
     $claims = array();
     if (is_array($options)) {
         $claims = $this->_processOptions($options);
     }
     $claims["d"] = $data;
     $claims["v"] = $this->version;
     $claims["iat"] = time();
     return JWT::encode($claims, $this->secret, "HS256");
 }
Ejemplo n.º 12
0
function checkSecurity()
{
    $requestHeaders = apache_request_headers();
    $authorizationHeader = $requestHeaders['Authorization'];
    //echo print_r(apache_request_headers());
    if ($authorizationHeader == null) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
    // // validate the token
    $pre_token = str_replace('Bearer ', '', $authorizationHeader);
    $token = str_replace('"', '', $pre_token);
    global $secret;
    global $decoded_token;
    try {
        $decoded_token = JWT::decode($token, base64_decode(strtr($secret, '-_', '+/')), false);
    } catch (UnexpectedValueException $ex) {
        header('HTTP/1.0 401 Unauthorized');
        echo "Invalid token";
        exit;
    }
    global $serverName;
    // // validate that this token was made for us
    if ($decoded_token->aud != $serverName) {
        header('HTTP/1.0 401 Unauthorized');
        echo "Invalid token";
        exit;
    }
}
Ejemplo n.º 13
0
 public static function login(Cart66Account $account)
 {
     $name = $account->firstName . ' ' . $account->lastName;
     $email = $account->email;
     $externalId = $account->id;
     $organization = Cart66Setting::getValue('zendesk_organization');
     $key = Cart66Setting::getValue('zendesk_token');
     $prefix = Cart66Setting::getValue('zendesk_prefix');
     if (Cart66Setting::getValue('zendesk_jwt')) {
         $now = time();
         $token = array("jti" => md5($now . rand()), "iat" => $now, "name" => $name, "email" => $email);
         include_once CART66_PATH . "/pro/models/JWT.php";
         $jwt = JWT::encode($token, $key);
         // Redirect
         header("Location: https://" . $prefix . ".zendesk.com/access/jwt?jwt=" . $jwt);
         exit;
     } else {
         /* Build the message */
         $ts = isset($_GET['timestamp']) ? $_GET['timestamp'] : time();
         $message = $name . '|' . $email . '|' . $externalId . '|' . $organization . '|||' . $key . '|' . $ts;
         $hash = MD5($message);
         $remoteAuthUrl = 'http://' . $prefix . '.zendesk.com/access/remoteauth/';
         $arguments = array('name' => $name, 'email' => $email, 'external_id' => $externalId, 'organization' => $organization, 'timestamp' => $ts, 'hash' => $hash);
         $url = add_query_arg($arguments, $remoteAuthUrl);
         header("Location: " . $url);
         exit;
     }
 }
Ejemplo n.º 14
0
 public static function getToken($user)
 {
     //@todo, check to see if we have a token stored for this user
     $key = Settings::get('hash_salt');
     $token = array("uid" => $user->id(), "mail" => $user->getEmail());
     return \JWT::encode($token, $key);
 }
Ejemplo n.º 15
0
 /**
  * Verifies an id token and returns the authenticated apiLoginTicket.
  * Throws an exception if the id token is not valid.
  * The audience parameter can be used to control which id tokens are
  * accepted.  By default, the id token must have been issued to this OAuth2 client.
  *
  * @param $audience
  * @return array the token payload, if successful
  */
 public function verifyIdToken($idToken, $audience = null)
 {
     if (empty($idToken)) {
         throw new LogicException('id_token cannot be null');
     }
     // Check signature
     $certs = $this->getFederatedSignonCerts();
     foreach ($certs as $cert) {
         $modulus = new BigInteger(JWT::urlsafeB64Decode($cert['n']), 256);
         $exponent = new BigInteger(JWT::urlsafeB64Decode($cert['e']), 256);
         $rsa = new RSA();
         $rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
         try {
             $payload = JWT::decode($idToken, $rsa->getPublicKey(), array('RS256'));
             if (property_exists($payload, 'aud')) {
                 if ($audience && $payload->aud != $audience) {
                     return false;
                 }
             }
             // support HTTP and HTTPS issuers
             // @see https://developers.google.com/identity/sign-in/web/backend-auth
             $issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS);
             if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) {
                 return false;
             }
             return (array) $payload;
         } catch (ExpiredException $e) {
             return false;
         } catch (DomainException $e) {
             // continue
         }
     }
     return false;
 }
Ejemplo n.º 16
0
 function loginset($id)
 {
     $userinfo = $this->User_data->userinfo($id);
     //读取用户数据
     //多说账号
     $token = array("short_name" => 'zustmanager', "user_key" => $userinfo['student_id'], "name" => $userinfo['username']);
     $duoshuoToken = JWT::encode($token, '97c1b8a2ce9f394b034232572c086196');
     $cookie = array('name' => 'duoshuo_token', 'value' => $duoshuoToken, 'expire' => '86500', 'domain' => '', 'path' => '/', 'secure' => FALSE);
     $this->input->set_cookie($cookie);
     $userinfo_session = array('username' => $userinfo['username'], 'student_id' => $userinfo['student_id'], 'head_img' => $userinfo['head_img'], 'major' => $userinfo['major'], 'classnum' => $userinfo['classnum'], 'email' => $userinfo['email'], 'qq' => $userinfo['qq']);
     $this->session->set_userdata($userinfo_session);
     //将用户数据写入session
     $logindate = array('status' => "1", 'lastLoginTime' => date("Y-m-d H:i:s"));
     $this->db->from('user')->where('student_id', $id)->update('user', $logindate);
     //更新用户登陆时间
     $log = array('student_id' => $userinfo['student_id'], 'username' => $userinfo['username'], 'events' => '登陆', 'time' => date("Y-m-d H:i:s"));
     $this->db->insert('log', $log);
     //记录事件 登陆
     /*      print_r($userinfo);//用户数据调出 调试用
     						echo "<hr>";
     						echo $this->session->userdata('username');
     						echo "<hr>";
     						echo "查询到此人";
     						echo date("Y-m-d H:i:s");*/
     $cookie = array('name' => 'zust_login', 'value' => $userinfo['student_id'] . '&' . $userinfo['password'], 'expire' => '86500', 'domain' => '', 'path' => '/', 'secure' => FALSE);
     $this->input->set_cookie($cookie);
     redirect(base_url('user/profile'));
 }
Ejemplo n.º 17
0
 /**
  * @param      $token
  * @param null $expire
  *
  * @return null
  */
 public static function check($token, $expire = null)
 {
     $salt = \Config::get('schauth::config.token.salt');
     // token decode
     $userToken = \JWT::decode($token, $salt, array('HS256'));
     // check token data
     if (empty($userToken->time) || empty($userToken->id)) {
         return null;
     }
     if (!empty($userToken->expAt)) {
         // check token expire at
         if ($userToken->expAt < time()) {
             return null;
         }
     } else {
         if ($expire === null) {
             $expire = \Config::get('schauth::config.expire.token_web');
             if ($expire < 60) {
                 $expire = 60;
             }
         }
         // check token expire
         if ($userToken->time + $expire < time()) {
             return null;
         }
     }
     return $userToken;
 }
Ejemplo n.º 18
0
 public static function getUsuario()
 {
     $headers = apache_request_headers();
     $token = explode(" ", $headers["Authorization"]);
     $usuario = JWT::decode(trim($token[1], '"'), "complejodeportivo", 'HS256');
     return $usuario;
 }
Ejemplo n.º 19
0
 public function login()
 {
     $res = new stdClass();
     $res->success = FALSE;
     $data = new stdClass();
     parse_str(file_get_contents("php://input"), $data);
     $data = (object) $data;
     $this->load->model('sp_model');
     $where = 'userName="******"';
     $arr = $this->sp_model->where('jwt_user', $where, 'id', 'asc');
     if (count($arr) == 1) {
         if (Password::validate_password($data->password, $arr[0]->password)) {
             $res->success = true;
             $token = array();
             $token['id'] = $arr[0]->id;
             $res->access_token = JWT::encode($token, $this->config->item('jwt_key'));
             $res->id = $arr[0]->id;
         } else {
             $res->error = 'Invalid user name or password.';
             http_response_code(401);
         }
     } else {
         $res->error = 'Invalid user name or password.';
         http_response_code(401);
     }
     $this->load->view('json', array('output' => $res));
 }
Ejemplo n.º 20
0
 /**
  * @access  public
  * @param   array|object $data     An object or array of data you wish
  *                                 to associate with the token. It will
  *                                 be available as the variable "auth" in
  *                                 the Firebase rules engine.
  * @param   object       $options  Optional. An associative array with
  *                                 the developer supplied options for this
  *                                 token. The following keys are recognized:
  *
  *                                   'admin': Set to true if you want this
  *                                   token to bypass all security rules.
  *                                   Defaults to false.
  *
  *                                   'debug': Set to true if you want to
  *                                   enable debug output from your security
  *                                   rules.
  *
  *                                   'expires': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time at which the token
  *                                   should expire.
  *
  *                                   'notBefore': Set to a number (seconds
  *                                   since epoch) or a DateTime object that
  *                                   specifies the time before which the
  *                                   should be rejected by the server.
  *
  *
  * @return  string       A Firebase auth token.
  */
 public function createToken($data, $options = null)
 {
     $funcName = 'Services_FirebaseTokenGenerator->createToken';
     // If $data is JSONifiable, let it pass.
     $json = json_encode($data);
     if (function_exists("json_last_error") && ($errno = json_last_error())) {
         $this->handleJSONError($errno);
     } else {
         if ($json === "null" && $data !== null) {
             throw new UnexpectedValueException("Data is not valid JSON");
         } else {
             if (empty($data) && empty($options)) {
                 throw new Exception($funcName . ": data is empty and no options are set.  This token will have no effect on Firebase.");
             }
         }
     }
     $claims = array();
     if (is_array($options)) {
         $claims = $this->_processOptions($options);
     }
     $this->_validateData($funcName, $data, isset($claims['admin']) && $claims["admin"] == true);
     $claims["d"] = $data;
     $claims["v"] = $this->version;
     $claims["iat"] = time();
     $token = JWT::encode($claims, $this->secret, "HS256");
     if (strlen($token) > 1024) {
         throw new Exception($funcName . ": generated token is too large.  Token cannot be larger than 1024 bytes.");
     }
     return $token;
 }
Ejemplo n.º 21
0
 public function login()
 {
     if ($this->input->is_ajax_request()) {
         if (!$this->input->post("email") || !$this->input->post("password")) {
             echo json_encode(array("code" => 2, "response" => "Datos insuficientes"));
         }
         $email = $this->input->post("email");
         $password = sha1($this->input->post("password"));
         $this->load->model("auth_model");
         //$user = $this->auth_model->login($email, $password);
         $this->db->select('id, email');
         $this->db->from('accounts');
         $this->db->where('email', $email);
         $this->db->where('password', $password);
         $user = $this->db->get()->row();
         if ($user) {
             $user->iat = time();
             $user->exp = time() + 20;
             $jwt = JWT::encode($user, 'appTokenKey');
             echo json_encode(array("code" => 0, "response" => array("token" => $jwt)));
         } else {
             echo json_encode(array("response" => array("errorLogin" => 'Usuario o contrasena incorrectos.')));
         }
     } else {
         show_404();
     }
 }
Ejemplo n.º 22
0
function userId()
{
    $token = explode(' ', Request::header('Authorization'))[1];
    $payloadObject = JWT::decode($token, Config::get('secrets.TOKEN_SECRET'));
    $payload = json_decode(json_encode($payloadObject), true);
    return $payload['sub'];
}
Ejemplo n.º 23
0
 function __construct($getWSDL = false, $debug = false, $params = null)
 {
     $tenantTokens = array();
     $config = @(include 'config.php');
     if ($config) {
         $this->wsdlLoc = $config['defaultwsdl'];
         $this->clientId = $config['clientid'];
         $this->clientSecret = $config['clientsecret'];
         $this->appsignature = $config['appsignature'];
     } else {
         if ($params && array_key_exists('defaultwsdl', $params)) {
             $this->wsdlLoc = $params['defaultwsdl'];
         } else {
             $this->wsdlLoc = "https://webservice.exacttarget.com/etframework.wsdl";
         }
         if ($params && array_key_exists('clientid', $params)) {
             $this->clientId = $params['clientid'];
         }
         if ($params && array_key_exists('clientsecret', $params)) {
             $this->clientSecret = $params['clientsecret'];
         }
         if ($params && array_key_exists('appsignature', $params)) {
             $this->appsignature = $params['appsignature'];
         }
     }
     $this->debugSOAP = $debug;
     if (!property_exists($this, 'clientId') || is_null($this->clientId) || !property_exists($this, 'clientSecret') || is_null($this->clientSecret)) {
         throw new Exception('clientid or clientsecret is null: Must be provided in config file or passed when instantiating ET_Client');
     }
     if ($getWSDL) {
         $this->CreateWSDL($this->wsdlLoc);
     }
     if ($params && array_key_exists('jwt', $params)) {
         if (!property_exists($this, 'appsignature') || is_null($this->appsignature)) {
             throw new Exception('Unable to utilize JWT for SSO without appsignature: Must be provided in config file or passed when instantiating ET_Client');
         }
         $decodedJWT = JWT::decode($params['jwt'], $this->appsignature);
         $dv = new DateInterval('PT' . $decodedJWT->request->user->expiresIn . 'S');
         $newexpTime = new DateTime();
         $this->setAuthToken($this->tenantKey, $decodedJWT->request->user->oauthToken, $newexpTime->add($dv));
         $this->setInternalAuthToken($this->tenantKey, $decodedJWT->request->user->internalOauthToken);
         $this->setRefreshToken($this->tenantKey, $decodedJWT->request->user->refreshToken);
         $this->packageName = $decodedJWT->request->application->package;
     }
     $this->refreshToken();
     try {
         $url = "https://www.exacttargetapis.com/platform/v1/endpoints/soap?access_token=" . $this->getAuthToken($this->tenantKey);
         $endpointResponse = restGet($url);
         $endpointObject = json_decode($endpointResponse->body);
         if ($endpointResponse && property_exists($endpointObject, "url")) {
             $this->endpoint = $endpointObject->url;
         } else {
             throw new Exception('Unable to determine stack using /platform/v1/endpoints/:' . $endpointResponse->body);
         }
     } catch (Exception $e) {
         throw new Exception('Unable to determine stack using /platform/v1/endpoints/: ' . $e->getMessage());
     }
     parent::__construct($this->LocalWsdlPath(), array('trace' => 1, 'exceptions' => 0));
     parent::__setLocation($this->endpoint);
 }
Ejemplo n.º 24
0
 /**
  * Used by the Zendesk single sign on functionality to authenticate users.
  * Only works for admin panel users, not for customers.
  */
 public function authenticateAction()
 {
     if (!Mage::getStoreConfig('zendesk/sso/enabled')) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Single sign-on disabled.'));
         $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl());
     }
     $domain = Mage::getStoreConfig('zendesk/general/domain');
     $token = Mage::getStoreConfig('zendesk/sso/token');
     if (!Zend_Validate::is($domain, 'NotEmpty')) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Zendesk domain not set. Please add this to the settings page.'));
         $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl());
     }
     if (!Zend_Validate::is($token, 'NotEmpty')) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__('Zendesk SSO token not set. Please add this to the settings page.'));
         $this->_redirect(Mage::getSingleton('admin/session')->getUser()->getStartupPageUrl());
     }
     $now = time();
     $jti = md5($now . rand());
     $user = Mage::getSingleton('admin/session')->getUser();
     $name = $user->getName();
     $email = $user->getEmail();
     $externalId = $user->getId();
     $payload = array("iat" => $now, "jti" => $jti, "name" => $name, "email" => $email, "external_id" => $externalId);
     Mage::log('Admin JWT: ' . var_export($payload, true), null, 'zendesk.log');
     $jwt = JWT::encode($payload, $token);
     $url = "http://" . $domain . "/access/jwt?jwt=" . $jwt;
     Mage::log('Admin URL: ' . $url, null, 'zendesk.log');
     $this->_redirectUrl($url);
 }
Ejemplo n.º 25
0
 public function getAll()
 {
     // Token para probar el área con seguridad
     $test = array('iat' => time(), 'exp' => time() + LIFETIME, 'security' => 'Security Test');
     $jwt = JWT::encode($test, TOKEN);
     $this->data = array('mensaje' => 'Hola mundo!!!', 'token' => $jwt);
 }
 public function confirmation()
 {
     App::uses('JWT', 'Vendor');
     $server_security_key = Configure::read('Security.key');
     $token = urldecode($this->request->query['token']);
     $token_info = JWT::decode($token, '$server_security_key');
     if ($this->request->is('post')) {
         $actionButton = isset($this->request->data['confirm']) ? 'confirm' : 'cancel';
         switch ($actionButton) {
             case 'cancel':
                 $this->set('sucess_msg', 'You chose not to submit the survey at this time.  Resume the survey at your convenience by following the link sent to your e-mail by Planit.');
                 break;
             case 'confirm':
                 $timestamp = date('Y-m-d G:i:s');
                 $this->Answer->create();
                 $this->Answer->updateAll(array('Answer.submission_date' => "'" . $timestamp . "'"), array('Answer.user_id' => $token_info->userid, 'survey_id' => $token_info->surveyid));
                 $this->set('sucess_msg', 'Your survey data have been sent to Planit.  Thank you for providing your time in completing the survey.');
                 //$this->Session->setFlash('You have completed the survey.  Thank you.', 'default', array(), 'processing_msg_success');
                 break;
         }
     } else {
         $action = $this->request->query['action'];
         switch ($action) {
             case "save":
                 $this->set('action', 'save');
                 break;
             case "submit":
                 $this->set('action', 'submit');
                 break;
         }
     }
     $this->set('tokeninfo', $token_info);
 }
 public static function validateIdToken($id_token, $settings, $antiforgery_id)
 {
     $jwt = NULL;
     $lastException = NULL;
     // TODO: cache the keys
     $discovery = json_decode(file_get_contents($settings->jwks_uri));
     if ($discovery->keys == NULL) {
         throw new DomainException('jwks_uri does not contain the keys attribute');
     }
     foreach ($discovery->keys as $key) {
         try {
             if ($key->x5c == NULL) {
                 throw new DomainException('key does not contain the x5c attribute');
             }
             $key_der = $key->x5c[0];
             // Per section 4.7 of the current JWK draft [1], the 'x5c' property will be the DER-encoded value
             // of the X.509 certificate. PHP's openssl functions all require a PEM-encoded value.
             $key_pem = chunk_split($key_der, 64, "\n");
             $key_pem = "-----BEGIN CERTIFICATE-----\n" . $key_pem . "-----END CERTIFICATE-----\n";
             // This throws exception if the id_token cannot be validated.
             $jwt = JWT::decode($id_token, $key_pem, self::$allowed_algorithms);
             break;
         } catch (Exception $e) {
             $lastException = $e;
         }
     }
     if ($jwt == NULL) {
         throw $lastException;
     }
     if ($jwt->nonce != $antiforgery_id) {
         throw new DomainException(sprintf('Nonce mismatch. Expecting %s', $antiforgery_id));
     }
     return $jwt;
 }
Ejemplo n.º 28
0
function validatetoken($redirectpage)
{
    // get oauth token from cookie
    // if not present redirect to $redirectpage
    // if found check that token is valid by decoding it
    if (isset($_COOKIE["access_token"])) {
        $secretkeyfile = 'oauth.txt';
        $secret = "";
        // read oauth shared secret from local file
        if (is_file($secretkeyfile)) {
            $lines = file($secretkeyfile);
            foreach ($lines as $line) {
                $secret = base64_decode($line);
                break;
            }
        } else {
            error_log("validatetoken: file not found: " . $secretkeyfile);
            die("internal error - token validation");
        }
        include_once 'JWT.php';
        $access_token = $_COOKIE["access_token"];
        try {
            $jwt = JWT::decode($access_token, $secret, true);
            return $jwt;
        } catch (Exception $e) {
            $msg = $e->getMessage();
            echo 'Token validation error: ', $msg, "\n";
            error_log("validatetoken: invalid token : " . $msg);
        }
    }
    setcookie("access_token", "", time() - 3600);
    redirect($redirectpage);
}
Ejemplo n.º 29
-1
 function is_authenticated($user)
 {
     $CI =& get_instance();
     $CI->load->library('JWT');
     $CI->input->get_request_header('Authorization');
     return JWT::encode($token, JWT_TOKEN_SECRET);
 }
Ejemplo n.º 30
-17
function verifyToken()
{
    if (AUTH_TURNED_OFF) {
        return true;
    }
    $CI = get_instance();
    if ($CI->input->get_request_header('Authorization')) {
        $tokenHeader = $CI->input->get_request_header('Authorization', TRUE);
        try {
            $token = JWT::decode($tokenHeader, JWT_KEY);
        } catch (Exception $e) {
            return false;
        }
    } else {
        $token = null;
    }
    if ($token->time != "Permanent") {
        $loginTime = new DateTime($token->time);
        $nowTime = new DateTime(date("Y-m-d H:i:s", time()));
        $interval = $loginTime->diff($nowTime);
        $hoursDifference = $interval->h + $interval->days * 24;
        // $minutesDifference = $interval->i + ($hoursDifference * 60);
        if ($hoursDifference >= 48) {
            return false;
        }
    }
    if ($token !== null && $token !== false && $token->privilegeSet !== "Reset") {
        return $token->privilegeSet;
    } else {
        return false;
    }
}