本文整理汇总了PHP中Firebase\JWT\JWT::decode方法的典型用法代码示例。如果您正苦于以下问题:PHP JWT::decode方法的具体用法?PHP JWT::decode怎么用?PHP JWT::decode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Firebase\JWT\JWT
的用法示例。
在下文中一共展示了JWT::decode方法的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
/**
* 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: 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;
}
}
}
示例4: 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());
}
示例5: 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;
}
示例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: 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;
}
示例8: 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;
}
示例9: 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;
}
}
示例10: decode
/**
* @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: facebook
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: 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;
}
}
示例13: execute
/**
* @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: authenticate
/**
* @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: testCreateAutologinJwt
/**
* @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);
}