• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP JWT\JWT类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Firebase\JWT\JWT的典型用法代码示例。如果您正苦于以下问题:PHP JWT类的具体用法?PHP JWT怎么用?PHP JWT使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了JWT类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: get_profile_hmac

 private function get_profile_hmac($account)
 {
     $key = $this->apiSecret;
     $payload = array("account" => $account, "apiUniqueId" => $this->apiKey, "created" => date("DATE_W3C"));
     $jwt = JWT::encode($payload, $key);
     return $jwt;
 }
开发者ID:molekilla,项目名称:auth2factor-sdk,代码行数:7,代码来源:a2f_curl.php


示例17: connect

 public function connect(Application $app)
 {
     $books = $app['controllers_factory'];
     $books->before(function (Request $request) use($app) {
         // Strip out the bearer
         $rawHeader = $request->headers->get('Authorization');
         if ($rawHeader) {
             if (strpos($rawHeader, 'Bearer ') === false) {
                 return new JsonResponse(array('message' => 'Unauthorized'), 401);
             }
             $jwt = str_replace('Bearer ', '', $rawHeader);
             $secretKey = base64_decode($app['secret']);
             try {
                 $token = JWT::decode($jwt, $secretKey, [$app['algorithm']]);
             } catch (Exception $e) {
                 return new JsonResponse(array('message' => 'Unauthorized'), 401);
             }
         } else {
             return new JsonResponse(array('message' => 'Bad Request'), 400);
         }
     });
     $books->get('/', 'MyApp\\Controller\\BookController::index');
     $books->post('/', 'MyApp\\Controller\\BookController::store');
     $books->get('/{id}', 'MyApp\\Controller\\BookController::show');
     $books->get('/edit/{id}', 'MyApp\\Controller\\BookController::edit');
     $books->put('/{id}', 'MyApp\\Controller\\BookController::update');
     $books->delete('/{id}', 'MyApp\\Controller\\BookController::destroy');
     return $books;
 }
开发者ID:valix,项目名称:silex-rest-jwt-skeleton,代码行数:29,代码来源:Book.php


示例18: testGetToken

 public function testGetToken()
 {
     $mockPlugin = new MockPlugin();
     $mockPlugin->addResponse(new Response(200, array(), json_encode(array('data' => array('access_token' => 'hi', 'expires_in' => 1, 'refresh_token' => 'refresh')))));
     $client = new Client();
     $client->addSubscriber($mockPlugin);
     $flow = new ClientCredentials(array('client_id' => 'clientid', 'client_secret' => 'clientsecret', 'shared_secret' => 'sharedsecret'), $client);
     $token = $flow->getToken();
     $request = $mockPlugin->getReceivedRequests()[0];
     $postFields = $request->getPostFields();
     $jwt = JWT::decode($postFields['client_assertion'], 'sharedsecret', array('HS512'));
     $this->assertEquals('POST', $request->getMethod());
     $this->assertEquals('clientid', $postFields['client_id']);
     $this->assertEquals('clientsecret', $postFields['client_secret']);
     $this->assertEquals('client_credentials', $postFields['grant_type']);
     $this->assertEquals('urn:params:oauth:client-assertion-type:jwt-bearer', $postFields['client_assertion_type']);
     $this->assertEquals('clientid', $jwt->iss);
     $this->assertEquals('clientid', $jwt->sub);
     $this->assertEquals('https://api.careerbuilder.com/oauth/token', $jwt->aud);
     $this->assertEquals(time() + 180, $jwt->exp);
     $this->assertEquals('hi', "{$token}");
     $this->assertEquals(true, $token->getRefreshToken());
     // TODO
     $this->assertEquals(time() + 1, $token->getExpiresAt());
 }
开发者ID:careerbuilder,项目名称:php-oauth,代码行数:25,代码来源:ClientCredentialsTest.php


示例19: handle

 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $jwt = $request->header('x-auth-jwt');
     $key = 'fad';
     //env('JWT_KEY');
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     /*
     	
     /*
      		NOTE: This will now be an object instead of an associative array. To get
      		an associative array, you will need to cast it as such:
     */
     //$decoded_array = (array) $jwt;
     /**
      * You can add a leeway to account for when there is a clock skew times between
      * the signing and verifying servers. It is recommended that this leeway should
      * not be bigger than a few minutes.
      *
      * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
      */
     //JWT::$leeway = 60; // $leeway in seconds
     //$decoded = JWT::decode($jwt, $key, array('HS256'));
     return $next($request);
     //$res = $next($request);
     //echo "after http request!";
     //return $res;
 }
开发者ID:xzungshao,项目名称:lar5-one,代码行数:34,代码来源:JwtMiddleware.php


示例20: ValidateToken

 function ValidateToken()
 {
     try {
         $headers = getallheaders();
         if (!isset($headers['Authorization'])) {
             return;
         }
         $tokenObject = explode(' ', $headers['Authorization']);
         if (count($tokenObject) != 2) {
             return;
         }
         $tokenValue = $tokenObject[1];
         if ($tokenValue == NULL || $tokenValue == '') {
             return;
         }
         JWT::$leeway = 60 * 60 * 24;
         //24 hours
         $decoded = JWT::decode($tokenValue, "JWT_KEY", array('HS256'));
         if (empty($decoded)) {
             return;
         }
         $decoded_array = (array) $decoded;
         if (empty($decoded_array)) {
             return;
         }
         self::$token = $tokenValue;
         self::$userId = $decoded_array['uid'];
         self::$isAuthorized = TRUE;
     } catch (UnexpectedValueException $e) {
         return;
     } catch (Exception $e) {
         return;
     }
 }
开发者ID:vitalsaude,项目名称:api,代码行数:34,代码来源:JWT_Controller.php



注:本文中的Firebase\JWT\JWT类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP Controllers\Controller类代码示例发布时间:2022-05-23
下一篇:
PHP Graph\Graph类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap