Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

felipebmfaria

Json Web Token - ZENDESK

Recommended Posts

Estou precisando de autenticar o login enviando um jwt para o Zendesk. Estou seguindo a documentação, mas ainda não consegui fazer funcionar o envio do json web token.


Depois de tentar logar recebo a mensagem de class JWT not found.


Alguém já implementou algo parecido?


O código que estou usando:


$key = "{key}";
$subdomain = "{subdomain}";
$now = time();
$token = array(
"jti" => md5($now . rand()),
"iat" => $now,
"name" => $user->name,
"email" => $user->email
);
$jwt = JWT::encode($token, $key);
$location = "https://" . $subdomain . ".zendesk.com/access/jwt?jwt=" . $jwt;
if(isset($_GET["return_to"])) {
$location .= "&return_to=" . urlencode($_GET["return_to"]);
}


Compartilhar este post


Link para o post
Compartilhar em outros sites

Consegui resolver.

 

verifica_login.php

 

include_once "JWT.php";
 
// Verifica se a senha do usuário está correta
if ( crypt( $dados_usuario['senha'], $fetch_usuario['user_password'] ) === $fetch_usuario['user_password'] ) {
// O usuário está logado
$_SESSION['logado']       = true;
$_SESSION['nome_usuario'] = $fetch_usuario['user_name'];
$_SESSION['usuario']      = $fetch_usuario['user'];
$_SESSION['user_id']      = $fetch_usuario['user_id'];
 
$key       = "key";
$subdomain = "subdomain";
$now       = time();
$token     = array(
 "jti"   => md5($now . rand()),
 "iat"   => $now,
 "name"  => $_SESSION['nome_usuario'],
 "email" => $_SESSION['usuario']
);
$jwt = JWT::encode($token, $key);
$location = "https://" . $subdomain . ".zendesk.com/access/jwt?jwt=" . $jwt;
header("Location: " . $location);
}

 

JWT.php

 

<?php
/**
 * JSON Web Token implementation, based on this spec:
 * http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
 *
 * PHP version 5
 *
 * @category Authentication
 * @package  Authentication_JWT
 * @author   Neuman Vong <neuman@twilio.com>
 * @author   Anant Narayanan <anant@php.net>
 * @license  http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
 * @link     https://github.com/firebase/php-jwt
 */
class JWT
{
    /**
     * Decodes a JWT string into a PHP object.
     *
     * @param string      $jwt    The JWT
     * @param string|null $key    The secret key
     * @param bool        $verify Don't skip verification process 
     *
     * @return object      The JWT's payload as a PHP object
     * @throws UnexpectedValueException Provided JWT was invalid
     * @throws DomainException          Algorithm was not provided
     * 
     * @uses jsonDecode
     * @uses urlsafeB64Decode
     */
    public static function decode($jwt, $key = null, $verify = true)
    {
        $tks = explode('.', $jwt);
        if (count($tks) != 3) {
            throw new UnexpectedValueException('Wrong number of segments');
        }
        list($headb64, $bodyb64, $cryptob64) = $tks;
        if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
            throw new UnexpectedValueException('Invalid segment encoding');
        }
        if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) {
            throw new UnexpectedValueException('Invalid segment encoding');
        }
        $sig = JWT::urlsafeB64Decode($cryptob64);
        if ($verify) {
            if (empty($header->alg)) {
                throw new DomainException('Empty algorithm');
            }
            if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) {
                throw new UnexpectedValueException('Signature verification failed');
            }
        }
        return $payload;
    }
    /**
     * Converts and signs a PHP object or array into a JWT string.
     *
     * @param object|array $payload PHP object or array
     * @param string       $key     The secret key
     * @param string       $algo    The signing algorithm. Supported
     *                              algorithms are 'HS256', 'HS384' and 'HS512'
     *
     * @return string      A signed JWT
     * @uses jsonEncode
     * @uses urlsafeB64Encode
     */
    public static function encode($payload, $key, $algo = 'HS256')
    {
        $header = array('typ' => 'JWT', 'alg' => $algo);
        $segments = array();
        $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
        $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
        $signing_input = implode('.', $segments);
        $signature = JWT::sign($signing_input, $key, $algo);
        $segments[] = JWT::urlsafeB64Encode($signature);
        return implode('.', $segments);
    }
    /**
     * Sign a string with a given key and algorithm.
     *
     * @param string $msg    The message to sign
     * @param string $key    The secret key
     * @param string $method The signing algorithm. Supported
     *                       algorithms are 'HS256', 'HS384' and 'HS512'
     *
     * @return string          An encrypted message
     * @throws DomainException Unsupported algorithm was specified
     */
    public static function sign($msg, $key, $method = 'HS256')
    {
        $methods = array(
            'HS256' => 'sha256',
            'HS384' => 'sha384',
            'HS512' => 'sha512',
        );
        if (empty($methods[$method])) {
            throw new DomainException('Algorithm not supported');
        }
        return hash_hmac($methods[$method], $msg, $key, true);
    }
    /**
     * Decode a JSON string into a PHP object.
     *
     * @param string $input JSON string
     *
     * @return object          Object representation of JSON string
     * @throws DomainException Provided string was invalid JSON
     */
    public static function jsonDecode($input)
    {
        $obj = json_decode($input);
        if (function_exists('json_last_error') && $errno = json_last_error()) {
            JWT::_handleJsonError($errno);
        } else if ($obj === null && $input !== 'null') {
            throw new DomainException('Null result with non-null input');
        }
        return $obj;
    }
    /**
     * Encode a PHP object into a JSON string.
     *
     * @param object|array $input A PHP object or array
     *
     * @return string          JSON representation of the PHP object or array
     * @throws DomainException Provided object could not be encoded to valid JSON
     */
    public static function jsonEncode($input)
    {
        $json = json_encode($input);
        if (function_exists('json_last_error') && $errno = json_last_error()) {
            JWT::_handleJsonError($errno);
        } else if ($json === 'null' && $input !== null) {
            throw new DomainException('Null result with non-null input');
        }
        return $json;
    }
    /**
     * Decode a string with URL-safe Base64.
     *
     * @param string $input A Base64 encoded string
     *
     * @return string A decoded string
     */
    public static function urlsafeB64Decode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }
    /**
     * Encode a string with URL-safe Base64.
     *
     * @param string $input The string you want encoded
     *
     * @return string The base64 encode of what you passed in
     */
    public static function urlsafeB64Encode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }
    /**
     * Helper method to create a JSON error.
     *
     * @param int $errno An error number from json_last_error()
     *
     * @return void
     */
    private static function _handleJsonError($errno)
    {
        $messages = array(
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
            JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
            JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
        );
        throw new DomainException(
            isset($messages[$errno])
            ? $messages[$errno]
            : 'Unknown JSON error: ' . $errno
        );
    }
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por clovis.sardinha
      Estou em um impasse pois sei pouco de javascript. Estou fazendo um autocomplete com CI4 e Javascript.
      Consigo gerar, através do controllers/model do CI4 um arquivo em json, mas não consigo retorná-lo para o javascript para poder mostrar as opções para consulta. 
      O console.log mostra que estou obtendo o  json() { [native code] }.
      Segue os dois arquivos para ver se alguém me ajuda.
      //arquivo cidade.js async function carregar_cidade(valor) { if (valor.length >= 3) { //console.log("Pesquisar:" + valor); const dados = fetch('Testes/?cidade='+valor, { method: "get", headers: { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest" } }); const resposta = (await dados).json; console.log(resposta); var html = "<ul class='list-group position-fixed'>"; html += "<li class='list-group-item'>" + resposta['cid_nome'] + "</li>"; html += "</ul>"; } } <?php //arquivo Testes.php namespace App\Controllers; use App\Models\CidadeModel; /** NÃO MANDAR PARA O SERVIDOR - APENAS TESTES DE FUNÇÕES E OUTROS ELEMENTOS DO CI4 */ class Testes extends BaseController{ protected $tbCidades; public function __construct(){ $this->tbCidades = new CidadeModel(); } public function index(){ $request = \Config\Services::request(); $client = \Config\Services::curlrequest(); $cidades=[]; if($get=$request->getGet()){ $cities=$get['cidade']; $cidadeFiltrada=$this->tbCidades->getCidByName($cities); $cidades= json_encode($cidadeFiltrada); //dd($cidades); } echo view('Testes/testes'); } public function salvar(){ $request = \Config\Services::request(); if($post=$request->getPost()){ dd($post); } } } <!doctype html> <html lang="pt-br"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Autocomplete</title> </head> <body> <div class="container"> <h1 class="mt-4 mb-4">Formulário</h1> <form class="row g-3"> <div class="col-12"> <label for="cidade" class="form-label">Cidade</label> <input type="text" name="cidade" class="form-control" id="cidade" placeholder="Pesquisar cidade" onkeyup="carregar_cidade(this.value)"> </div> <span ></span> </form> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="assets/js/cidade.js"></script> </body> </html>
    • Por FabianoSouza
      Olá pessoal.
      Eu já utilizo o FOR JSON PATH para retornar o o resultado de uma consulta com JSON. Isso eu já sei fazer.
       
      O que preciso é criar uma função que receba um SELECT como parâmetro e retorne o resultado desse SELECT já formatado como JSON.
      Estou tentando isso, mas sem sucesso.
       
      A function dbo.fn_retornaJsonPath :
      (@String NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN BEGIN IF @String <> NULL SET @String = (SELECT @String AS jsonPath FOR JSON PATH) END BEGIN IF @String IS NULL SET @String = '[]' END RETURN @String END Forma de executar:
      SET @sql = 'SELECT ' SET @sql = @sql + ' dbo.fn_retornaJsonPath ((SELECT TT.tema FROM dbo.tabela AS TT WHERE TT.cd = CTT.id)) AS ''temas'' ' SET @sql = @sql + ' FROM dbo.minhaTab AS CTT ' EXEC(@sql) Mas não está rolando....
    • Por PresleyMenezes
      Olá pessoal, gostaria de saber como copiar o conteúdo de um campo json com muitos pais e filhos e colar em outro campo de pais e filhos do mesmo arquivo json?
       
      agradeço a ajuda de vocês.
      em anexo o arquivo json e o codigo que estou tentando fazer

       

       

       
       
       
       

       

       
    • Por Giovanird
      Olá a todos!
      Tenho uma api  Sala de Aula e dentro dela o id de cada aluno. Em outra api, API ALUNO,  tenho os dados de cada aluno:  nome, foto, endereço.
      Estou fazendo o foreach da api Sala de Aula e preciso também retornar os dados de cada aluno.
      Segue o código que não estou conseguindo desenvolver
      $sala = file_get_contents("https://api/sala?id=987"); $sala = json_decode($sala, true); $sala = $sala['data']; foreach ($sala as $resulsala){ $codigoaluno = $resulsala['idaluno']; $alunos = file_get_contents("https://api/alunos?id=$codigoaluno"); $alunos = json_decode($alunos, true); $alunos = $alunos['data']; foreach ($alunos as $resulalunos){ echo $resulalunos['nome']; echo $resulalunos['foto']; echo $resulalunos['rua']; } }  
    • Por kania
      Tenho a seguinte situação.
      Recebo vários JSONs podendo ou não ser multidimensional, preciso atualizar uma determinada chave deste JSON, o problema é que algumas chaves podem ser duplicadas, bem como seus respectivos valores. Como estou tentando criar uma função genérica para navegar em qualquer JSON e modificar a chave em si, com estas duplicidades de chaves, estou tendo dificuldades em dizer ao código qual é chave que devo alterar.
       
      Arquivo JSON Exemplo
       
      {       "CREDITOR": {         "TAX": {           "TAC": 0.7         },         "ENABLE": "true",         "PRODUCTION": {           "email": "email@dominio.com",           "senha": "12457895",           "BASE_URL": "https://domino.com"         },         "HOMOLOGATION": {           "email": "email@dominio.com",           "senha": "12457895",           "BASE_URL": "https://domino.com"         },         "TARGET_VALUES": 5000000       }     }  
      Converto o JSON para array
       
      $json = json_decode($json_string, true);
      Função que criei até aqui
       
         
      /**      * Encontra a chave correspondente dentro do JSON      *      * @param array $jsonArray - JSON a ser verificado      * @param string $keyFather - chave de entrada      * @param string $keyUpdate - chave que modificar      * @param string $valueUpdate - novo valor da chave      * @return string      *      */     public static function searchKeyJson(array $jsonArray, string $keyFather, string $keyUpdate = null, $valueUpdate = null)     {         foreach ($jsonArray as $key => $value) {             if ($key == $keyFather && $keyUpdate == null) {                 $jsonArray[$key] =  $valueUpdate;                 return $jsonArray;             }             if ($key == $keyFather && $keyUpdate != null) {                 $jsonArray[$keyFather][$keyUpdate] = $valueUpdate;                 return $jsonArray;             }             if (is_array($value)) {                 if (($result = self::searchKeyJson($value, $keyFather, $keyUpdate, $valueUpdate)) !== false) {                     if ($keyUpdate == null) {                         return $result;                     } else {                         return $result;                     }                 }             }         }         return false;     }
      Até modifico o valor, mais no final para salvar, ele não monta o JSON como original, ele caba ignorando a chave inicial no JSON de exmeplo "CREDITOR": {}
       
      Retorno da função (notem que esta forma do padrão da original)
       
      => [          "TAX" => [            "TAC" => 0.7,          ],          "ENABLE" => "true",          "PRODUCTION" => [            "email" => "teste",            "senha" => "12457895",            "BASE_URL" => "https://domino.com",          ],          "HOMOLOGATION" => [            "email" => "email@dominio.com",            "senha" => "12457895",            "BASE_URL" => "https://domino.com",          ],          "TARGET_VALUES" => 5000000,        ]  
      Se eu percorrer o array e tentar modificar a chave em questão, ele muda todas as as chaves que tiverem no JSON porque tem duplicidade.
      Como posso resolver isto com uma função global que sirva para qualquer padrão de JSON que eu tiver?
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.