Skip to content

Instantly share code, notes, and snippets.

@tspycher
Last active March 7, 2019 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tspycher/3d25058cb977dce16528eac55c60669d to your computer and use it in GitHub Desktop.
Save tspycher/3d25058cb977dce16528eac55c60669d to your computer and use it in GitHub Desktop.
Flask Session generation in PHP
<?php
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
// payload
$data = array("username"=>"John");
$data_json = json_encode($data);
$dataz = gzcompress($data_json);
if(strlen($dataz) < (strlen($data_json) - 1))
$dataz64 = "." . base64url_encode($dataz);
else
$dataz64 = base64url_encode($data_json);
// Time
$EPOCH = 1293840000; #2011/01/01
$salt = "cookie-session";
$secret_key = "xxxxxxxxxxxxxxxx";
$digest_method = "sha1";
$timestamp = time() - $EPOCH;
$timestamp_b = pack("L", $timestamp); #unpack("C*", $x);
$timestamp64 = base64url_encode($timestamp_b);
$payload = $dataz64 . "." . $timestamp64;
$ctx = hash_init($digest_method, HASH_HMAC, $secret_key);
hash_update($ctx, $salt);
$derived_secret = hash_final($ctx, true);
$signature = hash_hmac ($digest_method , $payload , $derived_secret, true);
$signature64 = base64url_encode($signature);
$session = $payload . "." . $signature64;
print_r($session);
@tspycher
Copy link
Author

tspycher commented Jun 30, 2016

If you share the same secret in your PHP and Flask Application you are able to create a Session String in PHP, send it as Cookie to the user and user will have a valid session in the Flask Environment.

I use this in an Micro Service Architecture during login.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment