コード例 #1
14
ファイル: Request.php プロジェクト: kbokdia/DemoProject
 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");
     }
 }
コード例 #2
1
ファイル: JwtMiddleware.php プロジェクト: xzungshao/lar5-one
 /**
  * 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;
 }
コード例 #3
1
ファイル: jwt.php プロジェクト: justinoue/SSOPress
 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;
         }
     }
 }
コード例 #4
1
 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());
 }
コード例 #5
1
 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;
 }
コード例 #6
1
ファイル: Auth.php プロジェクト: featherbb/featherbb
 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;
     }
 }
コード例 #7
1
ファイル: Auth.php プロジェクト: andela-gjames/Emoji-API
 /**
  * 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;
 }
コード例 #8
1
 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;
 }
コード例 #9
1
ファイル: auth.php プロジェクト: senegalesegirl/CrowdHelp
 /**
  * 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;
     }
 }
コード例 #10
1
 /**
  * @inheritdoc
  */
 public function decode($jwt)
 {
     $payload = JWT::decode($jwt, $this->getSigningKey(), [self::SIGNING_ALGORITHM]);
     $userId = isset($payload->{self::CLAIM_USER_ID}) === true ? $payload->{self::CLAIM_USER_ID} : null;
     $user = $userId !== null ? User::find($userId) : null;
     return $user;
 }
コード例 #11
1
 public function facebook(Request $request)
 {
     $accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';
     $graphApiUrl = 'https://graph.facebook.com/v2.5/me';
     $params = ['code' => $request->input('code'), 'client_id' => $request->input('clientId'), 'redirect_uri' => $request->input('redirectUri'), 'client_secret' => '76cd1014c10586c33f3e13f03929a221'];
     $client = new \GuzzleHttp\Client();
     // Step 1. Exchange authorization code for access token.
     $accessToken = json_decode($client->get($accessTokenUrl, ['query' => $params])->getBody(), true);
     // Step 2. Retrieve profile information about the current user.
     $profile = json_decode($client->get($graphApiUrl, ['query' => $accessToken])->getBody(), true);
     // Step 3a. If user is already signed in then link accounts.
     if ($request->header('Authorization')) {
         $user = User::where('facebook', '=', $profile['id']);
         if ($user->first()) {
             return response()->json(['message' => 'There is already a Facebook account that belongs to you'], 409);
         }
         $token = explode(' ', $request->header('Authorization'))[1];
         $payload = (array) JWT::decode($token, Config::get('jwt.secret'), array('HS256'));
         $user = User::find($payload['sub']);
         $user->facebook = $profile['id'];
         $user->displayName = $user->displayName ?: $profile['name'];
         $user->save();
         return response()->json(['token' => $this->createToken($user)]);
     } else {
         $user = User::where('facebook', '=', $profile['id']);
         if ($user->first()) {
             return response()->json(['token' => $this->createToken($user->first())]);
         }
         $user = new User();
         $user->facebook = $profile['id'];
         $user->displayName = $profile['name'];
         $user->save();
         return response()->json(['token' => $this->createToken($user)]);
     }
 }
コード例 #12
1
ファイル: JWT_Controller.php プロジェクト: vitalsaude/api
 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;
     }
 }
コード例 #13
0
 /**
  * @inheritdoc
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $jwt = $input->getArgument('jwt');
     $secret = $input->getArgument('start');
     $timeout = $input->getArgument('timeout');
     $found = false;
     $start = microtime(true);
     $step = 100000;
     while (microtime(true) - $start < $timeout) {
         for ($i = 0; $i < $step; $i++) {
             try {
                 JWT::decode($jwt, $secret, ['HS256']);
                 $found = true;
                 break 2;
             } catch (\Exception $e) {
                 $secret = $this->findNext($secret);
             }
         }
         $output->write(sprintf('%s, ', $secret));
     }
     $took = number_format(microtime(true) - $start, 2);
     $memoryUsed = number_format(memory_get_peak_usage() / (1024 * 1024), 2) . ' MB';
     if ($found) {
         $output->writeln(sprintf('<info>Secret found:</info> %s (took: %s, memory: %s)', $secret, $took, $memoryUsed));
     } else {
         $output->writeln(sprintf('<error>Secret not found:</error> finished on %s (took: %s, memory: %s)', $secret, $took, $memoryUsed));
     }
 }
コード例 #14
0
ファイル: RestHttpBasicAuth.php プロジェクト: sunil120/yii2
 /**
  * @inheritdoc
  */
 public function authenticate($user, $request, $response)
 {
     parent::authenticate($user, $request, $response);
     $username = $request->getAuthUser();
     $password = $request->getAuthPassword();
     $headers = Yii::$app->request->headers;
     if ($this->auth) {
         if ($username !== null || $password !== null) {
             $identity = call_user_func($this->auth, $username, $password);
             if ($identity !== null) {
                 $user->switchIdentity($identity);
             } else {
                 $this->handleFailure($response);
             }
             return $identity;
         }
     } else {
         if ($headers->has('x-apitoken')) {
             $decoded = JWT::decode($headers->get('x-apitoken'), Yii::$app->params['security-salt'], array('HS256'));
             if (isset($decoded->token) && $decoded->token != '') {
                 $identity = $user->loginByAccessToken($decoded->token, get_class($this));
                 if ($identity === null) {
                     $this->handleFailure($response);
                 }
                 if ($identity->username == $decoded->username) {
                     return $identity;
                 }
             }
             return $identity;
         }
     }
     return null;
 }
コード例 #15
0
 /**
  * @vcr configuration_openid
  */
 public function testCreateAutologinJwt()
 {
     $authorization = $this->getValidAuthorization();
     $tokenSet = new \P7\SSO\TokenSet(['access_token' => 'ACCESS_TOKEN', 'id_token' => 'ID_TOKEN_TOKEN', 'expires_in' => 1234, 'received_at' => 5678]);
     $loginToken = JWT::decode($authorization->createAutologinJwt($tokenSet), $authorization->getConfig()->client_secret, ['HS256']);
     $this->assertEquals((object) ['access_token' => 'ACCESS_TOKEN', 'id_token' => 'ID_TOKEN_TOKEN', 'remember_me' => false], $loginToken);
 }
コード例 #16
0
ファイル: JWT.php プロジェクト: phramework/jwt
 /**
  * @param  array  $params  Request parameters
  * @param  string $method  Request method
  * @param  array  $headers  Request headers
  * @return object|FALSE Returns false on error or the user object on success
  */
 public function check($params, $method, $headers)
 {
     if (!isset($headers['Authorization'])) {
         return false;
     }
     list($jwt) = sscanf($headers['Authorization'], 'Bearer %s');
     if (!$jwt) {
         return false;
     }
     $secret = Phramework::getSetting('jwt', 'secret');
     $algorithm = Phramework::getSetting('jwt', 'algorithm');
     try {
         $token = \Firebase\JWT\JWT::decode($jwt, $secret, [$algorithm]);
         //Call onAuthenticate callback if set
         if (($callback = Manager::getOnCheckCallback()) !== null) {
             call_user_func($callback, $token->data);
         }
         return $token->data;
     } 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)
          */
         return false;
     }
 }
コード例 #17
0
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     $match = $this->router->match($request->getPathInfo());
     $route = substr($request->getPathInfo(), strlen(rtrim($this->config['baseDir'], '/')));
     if ($match) {
         $tokenValid = false;
         $jwtCookie = $this->config['jwt']['cookieName'];
         $jwtKey = $this->config['jwt']['key'];
         // check token from cookie
         if ($request->cookies->has($jwtCookie)) {
             $jwt = $request->cookies->get($jwtCookie);
             try {
                 $decoded = JWT::decode($jwt, $jwtKey, ['HS256']);
                 if ($decoded->e > time()) {
                     $tokenValid = true;
                     $this->auth->init($decoded->uid);
                 }
             } catch (\Exception $e) {
                 $tokenValid = false;
                 if (!$catch) {
                     throw $e;
                 }
                 $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>']);
                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
                 return $response;
             }
         }
         $allowed = false;
         $isPublic = false;
         foreach ($this->config['publicArea'] as $publicRoute) {
             if (preg_match('/^' . addcslashes($publicRoute, '/') . '/', $route)) {
                 $isPublic = true;
                 break;
             }
         }
         if ($match['name'] == 'home') {
             $isPublic = true;
         }
         if ($isPublic) {
             if ($route == '/login' && $tokenValid) {
                 return new RedirectResponse($this->router->generate('dashboard'));
             }
             $allowed = true;
         } else {
             $allowed = $tokenValid;
         }
         if ($allowed) {
             $this->app->setRouteMatch($match);
             return $this->app->handle($request, $type, $catch);
         } else {
             $this->flash->warning('Sesi Anda telah habis atau Anda tidak berhak mengakses halaman ini, silakan login terlebih dahulu!');
             $response = $this->dispatcher->dispatch('User#login', []);
             $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
             return $response;
         }
     }
     $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $route]);
     $response->setStatusCode(Response::HTTP_NOT_FOUND);
     return $response;
 }
コード例 #18
0
ファイル: Auth.php プロジェクト: aodkrisda/notes-api
 /**
  * Handle authentication
  *
  * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param  callable                                 $next     Next middleware
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function __invoke(Request $request, Response $response, $next)
 {
     $path = $request->getUri()->getPath();
     if ($path && $path != 'login') {
         $serverParams = $request->getServerParams();
         $authHeader = isset($serverParams['HTTP_X_AUTHORIZATION']) ? $serverParams['HTTP_X_AUTHORIZATION'] : null;
         list($jwt) = sscanf($authHeader, 'Bearer %s');
         if (!$jwt) {
             return $response->withStatus(401)->write(json_encode(['message' => '401 Unauthorized']));
         }
         try {
             $settings = $this->app->getContainer()->get('settings');
             $secretKey = base64_decode($settings->get('jwt')['key']);
             $token = JWT::decode($jwt, $secretKey, [$settings->get('jwt')['algorithm']]);
             // Get the user info and add to the container
             $this->app->getContainer()['currentUser'] = function ($c) use($token) {
                 return $token->data;
                 // user attributes
             };
         } catch (\Exception $e) {
             return $response->withStatus(401)->write(json_encode(['message' => $e->getMessage()]));
         }
     }
     $response = $next($request, $response);
     return $response;
 }
コード例 #19
0
 public function validateMerchantOtp(request $request)
 {
     $apiKey = $request->only('api_key');
     $validator = Validator::make($apiKey, ['api_key' => 'required']);
     if ($validator->fails()) {
         $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403);
         return $response;
     }
     $role = Role::find(2);
     $key = Config::get('custom.JWTkey');
     $decoded = JWT::decode($apiKey['api_key'], $key, array('HS256'));
     if ($decoded->type != 'merchant') {
         return $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403);
     }
     $user = User::find($decoded->sub);
     // check the current user
     if (empty($user) || !$user->hasRole(['merchant']) || !$user->status) {
         return $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403);
     }
     $user_id = $user->id;
     $input = $request->only('otp');
     $matchThese = ['user_id' => $user_id, 'code' => $input['otp']];
     $sms = UserSmsCode::where($matchThese)->first();
     if ($sms == '' || empty($sms)) {
         return response()->json(['response_code' => 'RES_IOG', 'messages' => 'Invalid OTP Given'], 422);
     }
     $sms->status = true;
     $sms->save();
     $user->is_mobile_verified = true;
     $user->save();
     return response()->json(['response_code' => 'RES_MV', 'messages' => 'Mobile Verified']);
 }
コード例 #20
0
ファイル: JwtLib.php プロジェクト: vihoangson/Family
 public function getJwt()
 {
     $return = [];
     $key = "352352345623463246trswrgsdfgsdfgsdfgsert";
     $token = array("iss" => "http://example.org", "aud" => "http://example.com", "iat" => time(), "nbf" => time() - 4123123);
     /**
      * IMPORTANT:
      * You must specify supported algorithms for your application. See
      * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
      * for a list of spec-compliant algorithms.
      */
     $jwt = JWT::encode($token, $key);
     $return[] = $jwt;
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     $return[] = $decoded;
     /*
      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) $decoded;
     $return[] = $decoded_array;
     /**
      * 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[] = $decoded;
     return $return;
 }
コード例 #21
0
ファイル: JwtEx.php プロジェクト: minutephp/framework
 public function decode($token)
 {
     try {
         $result = JWT::decode($token, $this->key, array('HS256'));
     } catch (\Throwable $e) {
     }
     return $result ?? null;
 }
コード例 #22
0
ファイル: JWTGeneratorTest.php プロジェクト: magarnier/tuleap
 public function testContentJWT()
 {
     $expected = array('user_id' => 9, 'user_rights' => array('@site_active'));
     $token = $this->jwt_generator->getToken();
     $decoded = JWT::decode($token, $this->private_key, array('HS512'));
     $decoded_data = (array) $decoded->data;
     $this->assertEqual($decoded_data, $expected);
 }
コード例 #23
0
ファイル: JWTDecoder.php プロジェクト: kurlzor/jwt
 /**
  * @param string $encodedToken
  *
  * @return object
  *
  * @throws JWTDecodeUnexpectedValueException
  */
 public function decode($encodedToken)
 {
     try {
         return JWT::decode($encodedToken, $this->secretKey, $this->allowedAlgorithms);
     } catch (\UnexpectedValueException $e) {
         throw new JWTDecodeUnexpectedValueException('JWT can not be decoded.', 0, $e);
     }
 }
コード例 #24
0
ファイル: authenticate.php プロジェクト: nipery/siili
function createToken($user)
{
    $key = "example_key";
    $token = array("iss" => "http://crossfitsiilinjarvi.fi", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000);
    $jwt = JWT::encode($token, $key);
    $decoded = JWT::decode($jwt, $key, array('HS256'));
    var_dump($decoded);
}
コード例 #25
0
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $response = new Response();
     //        var_dump($response);die();
     //        $encoder = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjExNDQ1NTM3NTg5LCJtZW51IjpbeyJ0aXR1bG8iOiJBZG1pbmlzdHJhY2lvbiIsImljb25jbHMiOiJhZG1pbl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tTnVVV2xQYVVreFRrUk5lVWxwZDJsYVNFcHdaRzFXZVVscWIybGpSMUoyV0ROQ2JtTXpSbk5KYmpBdWJXTk9Za1k0VUd0b0xVSlFVMFl6TTJveFNHaEpiRWhmVkdaVGRFdDRPVUpNUkRJMGRHUkJNRWhMVlNJLlRFcmhLTUtsbmY5SjRHRmg5Y0thSUUwTnc0eUprSlZHZWktdW10aDg5VVUifQ._bI6Hv8Dzly4i6mnCafD76r2HY10nR2r0wylh2Uasc4";
     $encoder = str_replace("Bearer ", "", $request->headers->get('Authorization'));
     //        var_dump($encoder);
     if (empty($encoder)) {
         $response->setStatusCode(Response::HTTP_INSUFFICIENT_STORAGE);
         $event->setResponse($response);
     } else {
         try {
             //            $encoder = str_replace("Bearer ", "", $request->headers->get('Authorization'));
             $decoded = JWT::decode($encoder, $this->secret, array('HS256'));
             //                var_dump($decoded);die();
             //                var_dump($decoded);
             $token = new JWTUserToken();
             $token->setRawToken($decoded);
             $this->container->set("JWTToken", $token);
             //                var_dump($decoded->usuario->login);die();
             $this->container->set("JWTUser", $decoded->usuario);
             $keydecoded = JWT::decode(JWT::decode($decoded->key, $this->secret, array('HS256')), $this->secret, array('HS256'));
             $this->container->set("JWTTokenPostgres", $keydecoded);
             //Ccreamos la coneccion
             $coneccion = $this->container->get("database_connection");
             $coneccion->close();
             $refCon = new \ReflectionObject($coneccion);
             $refParams = $refCon->getProperty("_params");
             $refParams->setAccessible("public");
             $params = $refParams->getValue($coneccion);
             $params["dbname"] = $keydecoded->dbname;
             $params["user"] = $keydecoded->user;
             $params["password"] = $keydecoded->password;
             $params["driver"] = $keydecoded->driver;
             $params["host"] = $keydecoded->host;
             $params["port"] = $keydecoded->port;
             $refParams->setAccessible("private");
             $refParams->setValue($coneccion, $params);
             $this->container->get("doctrine")->resetEntityManager("default");
             return;
         } catch (\Exception $a) {
             if ($a->getMessage() === "Expired token") {
                 //                    var_dump($a->getCode());
                 $response->setContent($a->getMessage());
                 $response->setStatusCode(Response::HTTP_FORBIDDEN);
                 //                    $response->set
                 $event->setResponse($response);
             } else {
                 //                    var_dump($encoder);
                 $response->setContent($a->getMessage() + " " + $encoder);
                 //                var_dump($a->getMessage());
                 $response->setStatusCode(Response::HTTP_FAILED_DEPENDENCY);
                 $event->setResponse($response);
             }
         }
     }
 }
コード例 #26
0
ファイル: FirebaseParser.php プロジェクト: equip/auth
 /**
  * @inheritDoc
  */
 public function parseToken($token)
 {
     try {
         $metadata = (array) JWT::decode((string) $token, $this->config->getPublicKey(), [$this->config->getAlgorithm()]);
     } catch (ExpiredException $e) {
         throw InvalidException::tokenExpired($token, $e);
     }
     return new Token($token, $metadata);
 }
コード例 #27
0
 /**
  * @inheritDoc
  */
 public function parseToken($token)
 {
     try {
         $metadata = (array) JWT::decode((string) $token, $this->config->getPublicKey(), [$this->config->getAlgorithm()]);
     } catch (ExpiredException $e) {
         throw new InvalidException('Token has expired: ' . $token, InvalidException::CODE_TOKEN_EXPIRED);
     }
     return new Token($token, $metadata);
 }
コード例 #28
0
 /**
  * @param $apiKey
  * @return \stdClass
  * @throws InvalidApiKeyException
  */
 public function getInfoFromApiKey($apiKey)
 {
     try {
         $jwtInfo = JWT::decode($apiKey, $this->secret, ['HS256']);
     } catch (\Exception $e) {
         throw new InvalidApiKeyException($apiKey, 0, $e);
     }
     return $jwtInfo;
 }
コード例 #29
-1
ファイル: Auth.php プロジェクト: adaur/featherbb-marketplace
 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(Config::get('jwt')['key']);
                 $token = JWT::decode($jwt, $secretKey, [Config::get('jwt')['algorithm']]);
                 return $token;
             } catch (\Firebase\JWT\ExpiredException $e) {
                 // TODO: (Optionnal) add flash message to say token has expired
                 return false;
             }
         } else {
             // Token is not present (or invalid) in cookie
             return false;
         }
     } else {
         // Auth cookie is not present in headers
         return false;
     }
 }
コード例 #30
-1
ファイル: Test.php プロジェクト: abhilash698/projectK
 public function postTest(Request $request)
 {
     $key = Config::get('custom.JWTkey');
     $userinputs = $request->only('id');
     $decoded = JWT::decode($userinputs['id'], $key, array('HS256'));
     //print_r($decoded);
     print_r($decoded);
 }