KEMBAR78
Demystifying OAuth2 for PHP | PDF
WHO DO YOUTRUST WITH YOUR
USERNAME AND PASSWORD?
WE NEEDTO ACCESS
DATA INTHE CLOUD.
WE DON’T WANTTO STORE
THEIR USERNAME/PASSWORD.
THERE MUST BE AN
ANSWER.
OPEN STANDARD FOR
AUTHORIZATION V2
The framework for a
secure link between
provider, customer and us.
OAUTH PROVIDERS
• Amazon
• Dropbox
• Etsy
• Evernote
• Facebook
• GitHub
• Google
• Instagram
• LinkedIn
• Microsoft
• Paypal
• Reddit
• SalesForce
• StackExchange
• Stripe
• Trello
• Twitter
• Vimeo
• Yelp
https://en.wikipedia.org/wiki/List_of_OAuth_providers
OAUTH IS…
• an Authorization protocol.
• not an Authentication protocol.
• (from the perspective of the web developer)
AUTHORIZATION:
“I GIVE YOU PERMISSION.”
AUTHENTICATION:
“I KNOW WHO YOU ARE.”
AUTHENTICATING USERS
• Can OAuth be used to provide
“login with…”?
• NO: OAuth is not an
authentication protocol.
• SOLUTION: use OpenID Connect
(Google/Microsoft) or similar.
OAUTH GRANTS
• Authorization Code grant
• Implicit grant
• Resource owner credentials grant
• Client credentials grant
WITHOUT OAUTH2
Web Developer Customer
Provider (ex. Google API)
WITH OAUTH
Web Developer Customer
Provider (ex. Google API)
OAuth2
OAUTH PROCESS:
• We redirect user to provider (Google/Facebook/etc.).
• User authorizes us.
• We obtain access token.
• We make requests with access token.
WHO LIKES 100
GRANDSTWIX?
Hasstoredthemsafely
inescrow.
Wantsa100grand.
100GRANDESCROW
http://www.mrwallpaper.com/hungry-cat-wallpaper/
Hasdecidedto
shareONE.
Wantsa100grand.
100GRANDESCROW
100GRANDESCROW
Directsme…
…toEscrowProvider
100GRANDESCROW
“Isitoktoshare
withAndrew?”
100GRANDESCROW
“Yes.”
100GRANDESCROW
Secretword:
“Yummy”
100GRANDESCROW
“Yummy”
Secretword:
“Yummy”
100GRANDESCROW
“Yummy”
“Yummy”
Secretword:
“Yummy”
100GRANDESCROW
“Crunchy”
100GRANDESCROW
“Crunchy”
100GRANDESCROW
PROVIDER(EX.GOOGLE)
WebDeveloper
Customer
OAUTH PROCESS:
• We redirect user to provider (Google/Facebook/etc.).
• User authorizes us.
• We obtain access token.
• We make requests with access token.
THE CODES:
• Authorization code is short-lived.
• It is the key to determine who the user is and what they gave
access to.
• Access token has a longer life.
• It is the key that gives access to the user’s resources.
USERNAME/PASSWORD OAUTH2
Has no expiration.
(unless credentials change)
Access token has expiration.
Able to access everything
in account.
Only can access authorized data.
Can be used to maliciously
take over an account.
Access to data can be
revoked at any time.
Loosing the username/password can
mean all data is compromised.
Loosing the access token can mean
some data is compromised.
THE PROVIDER?
Users Developers
Provider
Client ID
Client Secret
Name
Allowed Scopes
Whitelisted Domains
Tokens/Codes
ID VS SECRET?
• Both are for identifying who you are.
• Client ID: “public” key
• Client Secret: “private” key, never to be sent through
user’s browser
AUTHORIZATION SERVER
• Registers/logs in/validates the user.
• Checks the client ID.
• Validates the scopes that we request access to and
ensures those fall within what we originally asked for.
• Asks the user whether it is acceptable to give access.
• Sends the authorization code through the user to us.
AUTHORIZATION SERVER
• Looks up the authorization code.
• Generates the access token.
• Returns access token back to us.
DO IT YOURSELF…
• https://oauth2.thephpleague.com/
• As always, an excellent package by the amazing PHP League
LET’S SEE HOW
IT IS DONE!
PROVIDER: GOOGLE
GOAL: ACCESS LIST OF CUSTOMER
FILES IN GOOGLE DRIVE.
https://github.com/
JosephMaxwell/
OAuth2Implementation/
ONLINE STEPS
• Go to: http://console.developers.google.com/
• Enable Drive API
• Create OAuth Credentials
CONTINUING
• Save the file as client_secrets.json in your website’s home
directory.
• Change the token_uri attribute to have this value:
• https://www.googleapis.com/oauth2/v3/token
• Open https://[domain_name]/manual
OAUTH IN PHP…
“If debugging is the process of removing software bugs,
then programming must be the process of putting them in.”
AUTHORIZATION URL
https://accounts.google.com/o/oauth2/auth?

response_type=code
&state=RANDOM_GENERATED_CODE

&redirect_uri=[callback_address]

&scope=https://www.googleapis.com/auth/drive.readonly
&state=[generated_state_string]

&client_id=[client_id]

REFRESHTOKENS
• Refresh tokens are indefinite.
• Access tokens have an expiration.
• Refresh tokens are used to create new access tokens.
• access_type=offline to use refresh tokens.
USER DOESTHEIR
MAGIC:
THE CALLBACK
• Success: “code” parameter contains authorization code.
• OpenID: State key will be sent back.
• Error: “error” parameter contains error message.
GET /authorize/?code=4/ASDFASDFASDFASDF123123123123 HTTP/1.1
Host: developers.google.com
$client = new Client();
$code = $_GET['code'] ?? '';
$params = [
'code' => $code,
'grant_type' => 'authorization_code',
'client_id' => $this->config->getClientId(),
'client_secret' => $this->config->getClientSecret(),
'redirect_uri' => $this->helper->getCallbackUrl(self::AREA)
];
$url = “https://www.googleapis.com/oauth2/v4/token”;
$response = $client->post($url, ['form_params' => $params]);
$client = new Client();
$code = $_GET['code'] ?? '';
$params = [
'code' => $code,
'grant_type' => 'authorization_code',
'client_id' => $this->config->getClientId(),
'client_secret' => $this->config->getClientSecret(),
'redirect_uri' => $this->helper->getCallbackUrl(self::AREA)
];
$url = “https://www.googleapis.com/oauth2/v4/token”;
$response = $client->post($url, ['form_params' => $params]);
{
"access_token":"1/asdf1234asdf1234asdf1234",
"expires_in":3920,
"token_type":"Bearer"
}
$client = new GuzzleHttpClient();


$fileResponse = $client->get(
'https://www.googleapis.com/drive/v2/files',
[

'headers' => [
'Authorization' => ‘[TOKEN_TYPE] [ACCESS_TOKEN]’,
'Referer' => 'http://oauth2implementation.com'
]
]
);


$files = new Files($fileResponse->getBody());
// Posted to: https://www.googleapis.com/oauth2/v4/token
$params = [
‘refresh_token' => $refreshToken,
'grant_type' => 'refresh_token',
'client_id' => $this->config->getClientId(),
'client_secret' => $this->config->getClientSecret()
];
// . . .
IN A LIBRARY…
“The best performance improvement is the transition from
the nonworking state to the working state.” (J. Osterhout)
LIBRARY:
• The PHP library:
• The PHP League: OAuth2 Client
• https://github.com/thephpleague/oauth2-client
INITIALIZATION
$this->provider = new Google([

'clientId' => $this->config->getClientId(),

'clientSecret' => $this->config->getClientSecret(),

'redirectUri' => $this->helper->getCallbackUrl(self::AREA)

]);
AUTHORIZATION REDIRECT
$url = $this->provider->getAuthorizationUrl(
['scope' => $config::SCOPE]
);
$_SESSION['oauth2_state'] = $this->provider->getState();



header("Location: {$url}");
ACCESSTOKEN
$token = $this->provider->getAccessToken(
'authorization_code', [
'code' => $_GET[‘code']
]
);
$fileResponse = $client->get(
'https://www.googleapis.com/drive/v2/files', [

'headers' => [
'Authorization' => $token->getToken(),
'Referer' => 'http://oauth2implementation.com'
]
]
);


$files = new Files($fileResponse->getBody());
DO:
• Protect against common security threats.
• Store random state key in the session and send that to
the provider.
• Store the access token securely.
ACCESSTOKEN STORAGE
• Do you need to store access token?
• Encrypt it.
• Store it in the session or the DB.
• Maybe? Store encryption key as cookie.
IMPLICIT GRANT
• Used for client-side authorization.
• Access token is public.
• Resource access must be very limited.
• Access token is sent back with first round-trip to
authorization server.
CLIENT CREDENTIALS GRANT
• Machine-to-machine authentication.
• Agreed-upon signature that has limited permissions
associated with it.
INDUSTRYTERMINOLOGY
• Client: the software we write.
• Resource Server: website with which we will interact.
• ex: Google API
• Resource Owner: the customer.
• ex: the entity who uses our service to access their data.
OAUTH RESOURCES
• Standard:
• https://tools.ietf.org/html/rfc6749
• Security: https://tools.ietf.org/html/rfc6819#section-5.3
• Google API:
• https://developers.google.com/identity/protocols/OAuth2?hl=en
• https://developers.google.com/oauthplayground/
THE STEPS:
• Redirect user to provider (Google/Facebook/etc.).
• Provider authenticates user, user authorizes us.
• We exchange authorization code for access token.
• We make requests with access token.
QUESTIONS?
GO FORTH
AND CONNECT!

Demystifying OAuth2 for PHP