當前位置: 首頁>>代碼示例>>PHP>>正文


PHP JWT\JWT類代碼示例

本文整理匯總了PHP中Firebase\JWT\JWT的典型用法代碼示例。如果您正苦於以下問題:PHP JWT類的具體用法?PHP JWT怎麽用?PHP JWT使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了JWT類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: authorize

 public function authorize(HeaderInterface $authHeader)
 {
     list($jwt) = sscanf($authHeader->toString(), 'Authorization: Bearer %s');
     if ($jwt) {
         try {
             /*
              * decode the jwt using the key from config
              */
             $secretKey = base64_decode($this->config->get('jwt')->get('key'));
             $this->token = JWT::decode($jwt, $secretKey, [$this->config->get('jwt')->get('algorithm')]);
             $this->isAuthorized = true;
             $this->response = Response::createMessage("10");
         } catch (Exception $e) {
             /*
              * the token was not able to be decoded.
              * this is likely because the signature was not able to be verified (tampered token)
              */
             $this->isAuthorized = false;
             $this->response = Response::createMessage("03");
             $this->response["data"] = $jwt;
         }
     } else {
         /*
          * No token was able to be extracted from the authorization header
          */
         $this->isAuthorized = false;
         $this->response = Response::createMessage("01");
     }
 }
開發者ID:kbokdia,項目名稱:DemoProject,代碼行數:29,代碼來源:Request.php

示例2: handle

 /**
  * Execute the job.
  *
  * @param JWT $jwt
  * @param Carbon $carbon
  * @return String
  */
 public function handle(JWT $jwt, Carbon $carbon)
 {
     $token = $jwt->decode($this->token, env('APP_KEY'), ['HS256']);
     $date = $carbon->createFromTimestamp($token->timestamp);
     $today = $carbon->now();
     /**
      * if the difference is grater than 30 days, then request login again
      */
     return $date->diffInDays($today) > 30;
 }
開發者ID:SkysoulDesign,項目名稱:mirage.dev,代碼行數:17,代碼來源:CheckTokenJob.php

示例3: handle

 /**
  * Execute the job.
  *
  * @param JWT $jwt
  * @param Carbon $carbon
  * @return String
  */
 public function handle(JWT $jwt, Carbon $carbon)
 {
     $timestamp = $carbon->now()->timestamp;
     $data = collect($this->user->toArray())->only('id')->merge(compact('timestamp'));
     $token = $jwt->encode($data, env('APP_KEY'));
     /**
      * Save token on the user model
      */
     if ($this->saveToken) {
         $this->user->setAttribute('api_token', $token);
         $this->user->save();
     }
     return $token;
 }
開發者ID:SkysoulDesign,項目名稱:mirage.dev,代碼行數:21,代碼來源:GenerateTokenJob.php

示例4: login

 /**
  * @Route("/login")
  * @Method({"PUT"})
  */
 public function login(Request $request)
 {
     $email = $request->request->get('email');
     $password = $request->request->get('password');
     $customer = $this->getCustomerManager()->getRepo()->findOneByEmail($email);
     if (!$customer) {
         return $this->fail();
     }
     $em = $this->getDoctrine()->getManager();
     if ($customer->verifyPassword($password)) {
         $expire = new \DateTime('now');
         $expire->modify('+20 minute');
         $token = new Token($expire);
         if ($customer->getToken()) {
             $em->remove($customer->getToken());
         }
         $customer->setToken($token);
         $em->persist($token);
         $em->persist($customer);
         $em->flush();
         $key = $this->container->getParameter('jwt_key');
         $payload = array('type' => 'customer', 'user_id' => $customer->getId(), 'token_id' => $token->getId(), 'expires' => $token->getExpires());
         return $this->respondJson(array('jwt' => JWT::encode($payload, $key)));
     }
     return $this->fail();
 }
開發者ID:brobo,項目名稱:mumshoppe,代碼行數:30,代碼來源:CustomerController.php

示例5: Exception

 function login_post()
 {
     $email = '';
     $password = '';
     try {
         $entityBody = file_get_contents('php://input');
         $arrayObject = (array) json_decode($entityBody);
         if (!isset($arrayObject['email']) || !isset($arrayObject['password'])) {
             throw new Exception();
         }
         $email = $arrayObject['email'];
         $password = $arrayObject['password'];
         if ($email == '') {
             throw new Exception();
         }
         if ($password == '') {
             throw new Exception();
         }
     } catch (Exception $e) {
         $this->response(array('message' => 'Invalid request data'), self::HTTP_BAD_REQUEST);
     }
     $this->load->model('Model_users');
     $user = $this->Model_users->get_by(array('email' => $email, 'password' => sha1($password)));
     if ($user == NULL) {
         $this->response(array('message' => 'User not found'), self::HTTP_BAD_REQUEST);
     }
     $unixTime = new DateTime();
     $unixTime = $unixTime->getTimestamp();
     $token = array("uid" => $user->id, "name" => $user->name, "email" => $user->email, "iat" => $unixTime);
     $jwt = JWT::encode($token, "JWT_KEY");
     $this->response(array('id' => (int) $user->id, 'name' => $user->name, 'token' => $jwt), self::HTTP_OK);
 }
開發者ID:vitalsaude,項目名稱:api,代碼行數:32,代碼來源:Auth.php

示例6: get_cookie_data

 protected function get_cookie_data($authCookie = null)
 {
     if ($authCookie) {
         /*
          * Extract the jwt from the Bearer
          */
         list($jwt) = sscanf($authCookie, 'Bearer %s');
         if ($jwt) {
             try {
                 /*
                  * decode the jwt using the key from config
                  */
                 $secretKey = base64_decode(ForumSettings::get('jwt_token'));
                 $token = JWT::decode($jwt, $secretKey, [ForumSettings::get('jwt_algorithm')]);
                 return $token;
             } catch (\Firebase\JWT\ExpiredException $e) {
                 // TODO: (Optionnal) add flash message to say token has expired
                 return false;
             } catch (\Firebase\JWT\SignatureInvalidException $e) {
                 // If token secret has changed (config.php file removed then regenerated)
                 return false;
             }
         } else {
             // Token is not present (or invalid) in cookie
             return false;
         }
     } else {
         // Auth cookie is not present in headers
         return false;
     }
 }
開發者ID:featherbb,項目名稱:featherbb,代碼行數:31,代碼來源:Auth.php

示例7: registerAction

 public function registerAction()
 {
     $email = $this->post_data['email'];
     $password = $this->post_data['password'];
     if ($email == NULL || $password == NULL) {
         return $this->fail('Email and password not empty', Response::HTTP_BAD_REQUEST);
     }
     $user = User::where('email', '=', $email)->first();
     if ($user) {
         return $this->fail('Email already exists ', Response::HTTP_BAD_REQUEST);
     } else {
         $user = new User();
         $user->username = $this->post_data['username'];
         $user->password = md5($this->post_data['password']);
         $user->email = $this->post_data['email'];
         $user->status = 1;
         $user->save();
         if ($user->password == md5($password) && $user->status == 1) {
             $secret = $this->app['config.app.secret'];
             $token = array('user_id' => $user->id);
             $encoded_token = JWT::encode($token, $secret, 'HS256');
             return $this->json(['mess' => 'Thành công', 'user_id' => $user->id, 'token' => $encoded_token]);
         } else {
             return $this->fail('Database error', Response::HTTP_BAD_REQUEST);
         }
     }
 }
開發者ID:anhnt0212,項目名稱:rest-sifoni,代碼行數:27,代碼來源:AuthController.php

示例8: showAction

 public function showAction(Request $request, $token)
 {
     try {
         $token = JWT::decode($token, $this->keyStorage, $this->allowedAlgorithms);
     } catch (\UnexpectedValueException $exception) {
         throw new NotFoundHttpException('Resource not found', $exception);
     } catch (\Exception $exception) {
         throw new BadRequestHttpException('Invalid token', $exception);
     }
     if (!isset($token->sdef) || !is_array($token->sdef) || count($token->sdef) !== 3) {
         throw new BadRequestHttpException('sdef should be a sub-definition identifier.');
     }
     list($sbas_id, $record_id, $subdef) = $token->sdef;
     try {
         $databox = $this->findDataboxById($sbas_id);
         $record = $databox->get_record($record_id);
         $subDefinition = $record->get_subdef($subdef);
         $permalink = $subDefinition->get_permalink();
     } catch (\Exception $exception) {
         throw new NotFoundHttpException('Media was not found', $exception);
     }
     $subRequest = Request::create((string) $permalink->get_url(), 'GET', [], $request->cookies->all(), [], $request->server->all());
     if ($request->query->has('download')) {
         $subRequest->query->set('download', $request->query->get('download'));
     }
     $response = $this->app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
     // Remove Caption link header as it contains permalink token.
     $response->headers->remove('link');
     return $response;
 }
開發者ID:luisbrito,項目名稱:Phraseanet,代碼行數:30,代碼來源:MediaAccessorController.php

示例9: buildToken

 protected function buildToken(array $values = array(), $secretKey = 'ilios.jwt.key.secret')
 {
     $now = new DateTime();
     $default = array('iss' => 'ilios', 'aud' => 'ilios', 'iat' => $now->format('U'), 'exp' => $now->modify('+1 year')->format('U'), 'user_id' => 42);
     $merged = array_merge($default, $values);
     return JWT::encode($merged, $secretKey);
 }
開發者ID:stopfstedt,項目名稱:ilios,代碼行數:7,代碼來源:JsonWebTokenManagerTest.php

示例10: login

 public function login()
 {
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/JWT.php';
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/BeforeValidException.php';
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/ExpiredException.php';
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/SignatureInvalidException.php';
     $decoded = '';
     if (isset($_GET['jwt'])) {
         try {
             $decoded = \Firebase\JWT\JWT::decode($_GET['jwt'], $this->options['secret_token'], ['HS256']);
             $first_name = isset($decoded->first_name) ? $decoded->first_name : '';
             $last_name = isset($decoded->last_name) ? $decoded->last_name : '';
             $display_name = isset($decoded->display_name) ? $decoded->display_name : $first_name . ' ' . $last_name;
             $nicename = isset($decoded->nicename) ? $decoded->nicename : $display_name;
             $role = isset($decoded->role) ? $decoded->role : 'subscriber';
             $nickname = isset($decoded->nickname) ? $decoded->nickname : $username;
             $attrs = ['email' => $decoded->email, 'username' => $decoded->username, 'website' => isset($decoded->website) ? $decoded->website : '', 'nicename' => $nicename, 'display_name' => $display_name, 'first_name' => $first_name, 'last_name' => $last_name, 'role' => $role, 'nickname' => $nickname, 'description' => isset($decoded->description) ? $decoded->description : ''];
             parent::login($attrs);
         } catch (\Exception $e) {
             //var_dump($e);
             wp_redirect('/ssopress/error/');
             exit;
         }
     }
 }
開發者ID:justinoue,項目名稱:SSOPress,代碼行數:25,代碼來源:jwt.php

示例11: encode

 /**
  * @param stdClass $payload
  * @param null $expires - can be +1 day, or +1 week, etc
  *
  * @return String
  */
 public function encode(stdClass $payload, $expires = null) : string
 {
     if (!empty($expires)) {
         $payload->exp = is_numeric($expires) ? time() + $expires : strtotime($expires);
     }
     return JWT::encode($payload, $this->key, 'HS256');
 }
開發者ID:minutephp,項目名稱:framework,代碼行數:13,代碼來源:JwtEx.php

示例12: Decode

 /**
  * Decode un token et le retourne sous forme d'objet.
  * Retourne FALSE si le token est invalide (expiré par exemple)
  * @param bool $jwt
  * @return bool|object
  */
 private static function Decode($jwt = false)
 {
     if ($jwt) {
         try {
             /*
              * decode the jwt using the key from config
              */
             $secretKey = self::$config['token_secret'];
             $token = JWT::decode($jwt, $secretKey, array('HS512'));
             if ($token->exp < time()) {
                 return false;
             } else {
                 return $token;
             }
         } catch (Exception $e) {
             /*
              * the token was not able to be decoded.
              * this is likely because the signature was not able to be verified (tampered token)
              */
             //die($e->getMessage());
             return false;
         }
     } else {
         /*
          * No token was able to be extracted from the authorization header
          */
         return false;
     }
 }
開發者ID:senegalesegirl,項目名稱:CrowdHelp,代碼行數:35,代碼來源:auth.php

示例13: decodeToken

 /**
  * Decodes the token into an Object.
  *
  * @param string $token Raw token to decode
  *
  * @return object decoded token
  */
 public static function decodeToken($token)
 {
     $token = trim($token);
     //Check to ensure token is not empty or invalid
     if ($token === '' || $token === null || empty($token)) {
         throw new JWTException('Invalid Token');
     }
     //Remove Bearer if present
     $token = trim(str_replace('Bearer ', '', $token));
     //Decode token
     try {
         $token = JWT::decode($token, getenv('SECRET_KEY'), ['HS256']);
     } catch (\Exception $e) {
         throw new JWTException('Invalid Token');
     }
     //Ensure JIT is present
     if ($token->jit == null || $token->jit == '') {
         throw new JWTException('Invalid Token');
     }
     //Ensure User Id is present
     if ($token->data->uid == null || $token->data->uid == '') {
         throw new JWTException('Invalid Token');
     }
     return $token;
 }
開發者ID:andela-gjames,項目名稱:Emoji-API,代碼行數:32,代碼來源:Auth.php

示例14: login

 protected function login($user)
 {
     $key = Config::get('custom.JWTkey');
     $token = array("sub" => $user->id, "iss" => "http://leo.app", "iat" => 1356999524, "name" => $user->name);
     $jwt = JWT::encode($token, $key);
     return $jwt;
 }
開發者ID:abhilash698,項目名稱:projectX,代碼行數:7,代碼來源:AuthController.php

示例15: generateAuthHeader

 /**
  * Generate JWT authorization header
  * @return string
  */
 public function generateAuthHeader()
 {
     $time = time();
     $iss = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'cli';
     $signatureData = ['sub' => $this->config['public_key'], 'iat' => $time, 'exp' => $time + $this->config['leeway'], 'iss' => $iss, 'nbf' => $time - $this->config['leeway'], 'jti' => md5($this->config['public_key'] . $time)];
     return JWT::encode($signatureData, $this->config['private_key']);
 }
開發者ID:voov,項目名稱:Billingo-API-Connector,代碼行數:11,代碼來源:Request.php


注:本文中的Firebase\JWT\JWT類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。