本文整理汇总了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");
}
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}
示例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;
}
}
示例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);
}
}
}
示例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;
}
示例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);
}
示例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;
}
}
}
示例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');
}
示例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;
}
}
示例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;
}
示例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;
}
示例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']);
}