示例#1
0
文件: JWT.php 项目: jsor/stack-jwt
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     $challenge = function (Response $response, $error = null) {
         $value = 'Bearer';
         if (isset($this->options['realm'])) {
             $value .= sprintf(' realm="%s"', $this->options['realm']);
         }
         if ($error) {
             $value .= sprintf(' error="%s"', $error);
         }
         $response->headers->set('WWW-Authenticate', $value);
         return $response;
     };
     $authenticate = function ($app, $anonymous) use($request, $type, $catch, $challenge) {
         $header = $request->headers->get('authorization');
         if (!preg_match('/^Bearer (.+)$/i', $header, $matches)) {
             if ($anonymous) {
                 return (new WwwAuthenticateStackChallenge($app, $challenge))->handle($request, $type, $catch);
             }
             return $challenge(new Response('Invalid Authorization header (Format is: "Authorization: Bearer [token]")', 400), 'invalid_request');
         }
         $token = $matches[1];
         try {
             $jws = SimpleJWS::load($token);
         } catch (\InvalidArgumentException $e) {
             return $challenge(new Response('Invalid JSON Web Token', 401), 'invalid_token');
         }
         if (!$jws->isValid($this->options['key_provider']($jws->getPayload()))) {
             return $challenge(new Response('Invalid JSON Web Token', 401), 'invalid_token');
         }
         $request->attributes->set('stack.authn.token', $this->options['token_translator']($jws->getPayload()));
         return $app->handle($request, $type, $catch);
     };
     return (new Firewall($this->app, ['challenge' => $challenge, 'authenticate' => $authenticate, 'firewall' => $this->options['firewall']]))->handle($request, $type, $catch);
 }
示例#2
0
 public function testValidationOfInvalidSimpleJWS()
 {
     $date = new DateTime('yesterday');
     $this->jws->setPayload(array('exp' => $date->format('U')));
     $privateKey = openssl_pkey_get_private(SSL_KEYS_PATH . "private.key", self::SSL_KEY_PASSPHRASE);
     $this->jws->sign($privateKey);
     $jws = SimpleJWS::load($this->jws->getTokenString());
     $public_key = openssl_pkey_get_public(SSL_KEYS_PATH . "public.key");
     $this->assertFalse($jws->isValid($public_key, 'RS256'));
 }
示例#3
0
 public function testValidationOfInvalidSimpleJWSWithExpAsInt()
 {
     $date = new DateTime('yesterday');
     $data = array('a' => 'b', 'exp' => $date->getTimestamp(), 'iat' => time());
     $this->jws->setPayload($data);
     $privateKey = openssl_pkey_get_private(SSL_KEYS_PATH . 'private.key', self::SSL_KEY_PASSPHRASE);
     $this->jws->sign($privateKey);
     $jws = SimpleJWS::load($this->jws->getTokenString());
     $public_key = openssl_pkey_get_public(SSL_KEYS_PATH . 'public.key');
     $this->assertFalse($jws->isValid($public_key, 'RS256'));
 }
 /**
  * {@inheritdoc}
  */
 public function decode($token)
 {
     try {
         $jws = SimpleJWS::load($token);
     } catch (InvalidArgumentException $e) {
         return false;
     }
     if (!$jws->isValid($this->getPublicKey(), self::ALGORYTHM)) {
         return false;
     }
     return $jws->getPayload();
 }
    public function testGenerateIdentityToken()
    {
        $layerIdentityTokenProvider = new \Layer\LayerIdentityTokenProvider();
        $privateKey = <<<EOF
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDhfR1nIkmSyGUmpTajKgUWpm2f3ObmCgZMTNvadYzwBoJ3ktRG
t3cSvRdsyo1EZQPKLOOLv4sXxTE4RrMu/xBnbvUYzn9uvygcW8YT+gW1taJ7GM01
qjKfhAGbC9fhVvJC6VZRmk/ioGBYkA3+7lZTil33szwBK/REcWlPpXOH5wIDAQAB
AoGAECEzCT2apbVQBwOqdOF8m7IsBVN38Nymtq6Iy4e9HS5aBtOp+6UED4MXOeED
WfEf5EZxwH1jJcAlVTE5gBMeyST0dZ1BYrHU/RKtPAb/RqoxIy2ON9lQOzV+xR/Z
0W8LcrAHbIgu7iBGecTSsTrNw0i5Wo4684gEMM3MDtkbIQECQQD2W00r9CA+A8uL
xXa/p/8YLw3He4tAeU13qb7W/Wx0RfF5oZT3aqUwvgLTDP+ASycFUAD1MjKYOQpP
mwDu70eZAkEA6lCzE77b3xWFsNv9GysqTYQr3CoNmxWwGOdxsBsKrmuRdwRu5YvG
p00JG48VaNs5RXTiO42kefjHkPCQ1Wz7fwJBAOJNWISpyvxsrAwHJmBESHbEspmu
iWp+g4UK7v266mec4IdkwNzOoFQ4F4wcApCteHjO1zJmHEftDeW2c5MJRvECQHOO
wxJs4UC++4UCqWv5uM4r7fmRn84pPwS5N/9TBsyIbmAVBqAcdCdUPbaitTtWSoNv
ppcaPtCMmddoXPV03v8CQE01dePAfsVIACSSHTFSx9nmLzRmMqFT04uaBKDcqgEw
Ks3Omb1JuXYxR4elMX4d5Y3JPUMbqUPKylnE4X9ogbc=
-----END RSA PRIVATE KEY-----
EOF;
        $layerIdentityTokenProvider->setPrivateKey($privateKey);
        $layerIdentityTokenProvider->setKeyID('foo');
        $layerIdentityTokenProvider->setProviderID('bar');
        $identityToken = $layerIdentityTokenProvider->generateIdentityToken('sean', 'nonce');
        $publicKey = <<<EOF
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhfR1nIkmSyGUmpTajKgUWpm2f
3ObmCgZMTNvadYzwBoJ3ktRGt3cSvRdsyo1EZQPKLOOLv4sXxTE4RrMu/xBnbvUY
zn9uvygcW8YT+gW1taJ7GM01qjKfhAGbC9fhVvJC6VZRmk/ioGBYkA3+7lZTil33
szwBK/REcWlPpXOH5wIDAQAB
-----END PUBLIC KEY-----
EOF;
        $expectedISSResult = 'bar';
        $expectedPRNResult = 'sean';
        $public_key = openssl_pkey_get_public($publicKey);
        $jws = SimpleJWS::load($identityToken);
        if ($jws->isValid($public_key, 'RS256')) {
            $payload = $jws->getPayload();
            $this->assertEquals($expectedISSResult, $payload['iss'], 'iss did not match expected value');
            $this->assertEquals($expectedPRNResult, $payload['prn'], 'prn did not match expected value');
        } else {
            $this->assertFalse($jws->isValid($public_key, 'RS256'), 'SimpleJWS did not create a valid identity token');
        }
    }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (false === $request->hasHeader('Authorization')) {
         if (false === $this->allRequests) {
             return $next($request, $response);
         }
         return $this->invalidResponse;
     }
     $token = $request->getHeaderLine('Authorization');
     if (false === strpos($token, 'Bearer ')) {
         return $this->invalidResponse;
     }
     $token = substr($token, 7);
     /** @var SimpleJWS $jws */
     $jws = SimpleJWS::load($token, false);
     if (false === $jws->isValid($this->publicKey, $this->encoder)) {
         return $this->invalidResponse;
     }
     return $next($request->withAttribute('jwt', $jws->getPayload()), $response);
 }
 /**
  * {@inheritdoc}
  */
 function verifyToken(App $app, $token)
 {
     try {
         // Load token
         $jws = SimpleJWS::load($token);
         $publicKey = openssl_pkey_get_public('file://' . $app->getAppDir() . '/public.key');
         // verify that the token is valid and had the same values
         // you emitted before while setting it as a cookie
         if ($jws->isValid($publicKey, 'RS256')) {
             $payload = $jws->getPayload();
             $response = new JsonResponse(array('authorized' => true));
         } else {
             $response = new JsonResponse(array('authorized' => false), 401);
         }
     } catch (\InvalidArgumentException $ex) {
         return new JsonResponse(array('error' => 'Invalid token'), 400);
     }
     return new $response();
 }
 /**
  * Create Appellate Reviews for an Issue
  *
  * @return mixed
  */
 public function newReview()
 {
     $body = $this->requestBody;
     $headers = apache_request_headers();
     $arr = explode(" ", $headers['Authorization']);
     $value = $arr[1];
     $jws = SimpleJWS::load($value, true);
     $user_arr = $jws->getPayLoad();
     $user = $user_arr['uid'];
     error_log("Creating Review for user with iD: " . $user);
     $shared = $this->getDi()->getShared('db');
     $con = $shared->query("INSERT INTO appellate_reviews(legalhead, subjectmatter, issue, title, content, user_id) VALUES (?,?,?,?,?,?)", array($body->legalHead, $body->subjectMatter, $body->issue, $body->title, $body->content, $user));
     $con->execute();
     $id = $shared->lastInsertId();
     $data = $shared->query("SELECT appellate_reviews.id, legalhead, subjectmatter, issue, title, content, name FROM appellate_reviews join users on users.id = user_id WHERE appellate_reviews.id = {$id}")->fetch();
     return $data;
 }
示例#9
0
    }
    // Basic auth, for programmatic responses
    $headers = apache_request_headers();
    if (isset($headers['X_API_KEY'])) {
        $user = new \PhalconRest\Controllers\UserController();
        if (!$user->loginWithPrivateKey($headers['X_API_KEY'])) {
            throw new \PhalconRest\Exceptions\HTTPException("Invalid/Expired API Key", 403);
        } else {
            return true;
        }
    }
    if (isset($headers['Authorization']) && !empty($headers['Authorization'])) {
        $arr = explode(" ", $headers['Authorization']);
        if (count($arr) > 1) {
            $value = $arr[1];
            $jws = SimpleJWS::load($value, true);
            return true;
            //			if (!$jws->isExpired()) {
            //				return true;
            //			} else
            //				throw new \PhalconRest\Exceptions\HTTPException("Invalid/Expired Token Key", 403);
        } else {
            throw new \PhalconRest\Exceptions\HTTPException("No Key Set", 403);
        }
    }
    // If we made it this far, we have no valid auth method, throw a 401.
    throw new \PhalconRest\Exceptions\HTTPException('Must login or provide credentials.', 401, array('dev' => 'Please provide credentials by either passing in a session token via cookie, or providing password and username via BASIC authentication.', 'internalCode' => 'Unauth:1'));
});
/**
 * Mount all of the collections, which makes the routes active.
 */
示例#10
0
 /**
  * Proxy JWS::load static method to allow unit testing.
  * Creates an instance of a JWS from a JWT.
  *
  * @param string $jwsTokenString
  * @return JWS
  * @throws \InvalidArgumentException
  */
 public function callLoad($jwsTokenString, $allowUnsecure = false, Encoder $encoder = null, $encryptionEngine = 'OpenSSL')
 {
     return parent::load($jwsTokenString, $allowUnsecure, $encoder, $encryptionEngine);
     // TODO: Change the autogenerated stub
 }