Protecting a PHP API Using OAuth

Protecting a PHP API Using OAuth

In this tutorial, you’ll learn how to build a simple API in PHP from scratch and integrate it with Okta to provide user authentication.

Eduardo Riquelme

Thanks for this tutorial, it was really easy to implement and test. Just got a problem with JWK after I add the token authorization to the API. To solve this i had to:

1. Install firebase/php-jwt composer require firebase/php-jwt and dump autoloader composer dump-autoload
2. Add this 2 lines on top of index.php use Firebase\JWT\JWT; and use Firebase\JWT\JWK;
3. (Optional) Add catch error when token expires:
try{
$result = JWT::decode($token, $publicKey, array(‘RS256’));
}catch(\Firebase\JWT\ExpiredException $e){
echo 'Caught exception: ', $e->getMessage(), “\n”;
}

Hope this helps!

Nicole H

Just a note, I had to add an .htaccess file to my public folder to allow this to work, this is a composer requirement I believe (probably depends on server) but in case anyone else needs, the .htaccess looks like:

<ifmodule mod_rewrite.c="">
<ifmodule mod_negotiation.c="">
Options -MultiViews
</ifmodule>

RewriteEngine On

# Redirect Trailing Slashes…
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller…
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</ifmodule>