-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurity.php
More file actions
52 lines (42 loc) · 1.46 KB
/
Copy pathSecurity.php
File metadata and controls
52 lines (42 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
require_once 'vendor/autoload.php';
use Namshi\JOSE\SimpleJWS;
class Security
{
const PATH_CERTIFICATE_PRIVATE = "";
const PATH_CERTIFICATE_PUBLIC = "";
const SSL_KEY_PASSPHRASE = "";
const TTL = 0; // seconds
public static function createToken($payload = array())
{
$jws = new SimpleJWS(array(
'alg' => 'RS256'
));
$claims = ['iat' => time()];
if (null !== self::TTL) {
$claims['exp'] = time() + self::TTL;
}
$jws->setPayload(array_merge($claims,$payload));
$privateKey = openssl_pkey_get_private(file_get_contents(__DIR__.'/'.self::PATH_CERTIFICATE_PRIVATE), self::SSL_KEY_PASSPHRASE);
$jws->sign($privateKey);
return $jws->getTokenString();
}
public static function validateToken()
{
if (!array_key_exists("HTTP_AUTHORIZATION",$_SERVER)) {
http_response_code(400);
echo( json_encode(array("error" => "Restringed Area.")) );
exit();
}
$jws = SimpleJWS::load($_SERVER['HTTP_AUTHORIZATION']);
$public_key = openssl_pkey_get_public(file_get_contents(__DIR__.'/'.self::PATH_CERTIFICATE_PUBLIC));
if ($jws->isValid($public_key, 'RS256')) {
$payload = $jws->getPayload();
return $payload;
} else {
http_response_code(401);
echo(json_encode(array("error" => "Invalid Token.")));
exit();
}
}
}