Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Now that we have a JWT created, we can pass that instead of our JSON encoded array. Although a JWT is JSON encoded, there is more to it, so we'll need to change our decode function.
Decode JWT
function decodeAuthCookie($prop = null)
{
try {
Firebase\JWT\JWT::$leeway=1;
$cookie = Firebase\JWT\JWT::decode(
request()->cookies->get('auth'),
getenv("SECRET_KEY"),
['HS256']
);
} catch (Exception $e) {
return false;
}
if ($prop === null) {
return $cookie;
}
if ($prop == 'auth_user_id') {
$prop = 'sub';
}
if (!isset($cookie->$prop)) {
return false;
}
return $cookie->$prop;
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Now that we have a JWT created,
we can pass that to our cookie,
0:00
instead of our JSON-encoded array.
0:06
Although a JWT is JSON-encoded,
there's more to it than just JSON-encode.
0:14
So we'll need to change
our decode function.
0:20
We'll start by setting the leeway,
0:25
Firebase\JWT\JWT::$leeway=1.
0:32
This will account for
0:40
when there is a clock skew of time between
the signing and verifying servers.
0:42
Next, we can use the static method
decode from the Firebase class.
0:47
Firebase\JWT\JWT::decode.
0:55
First we pass our auth cookie.
1:04
And then we pass the secret key,
1:11
getenv (SECRET_KEY).
1:16
And finally,
an array of approved signing algorithms.
1:21
Since we signed the token with HS 256,
that's the only
1:28
one we're going to use in
our approved list, HS 256.
1:33
If there's any problem reading
the JWT we want to return false.
1:38
To do this, let's wrap
the decode in a try catch block.
1:43
Try, Catch,
1:49
Exception, And
2:02
if we catch an exception,
we'll just return false.
2:09
Because we're using the sub, or the
subject from the JWT RFC, we could either
2:13
change our call to the function or add
an additional condition before our return.
2:19
Since auth_user_id makes
more sense than sub,
2:25
I'm going to use that second option and
add an additional check.
2:29
If prop equals auth_user_id,
2:35
Then I'm going to set prop equal to sub.
2:48
This will allow the next check to work
to make sure that we actually have sub.
2:56
The rest of the decode
function we can leave as is.
3:01
Let's give our new authentication a try.
3:05
Any time that you make changes to
your JWT make sure you log out and
3:07
you log back in to make sure
that cookie is saved properly.
3:13
And once again, everything still works.
3:23
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up