Demystifying OAuth2 for PHP
WHO DO YOUTRUST WITH YOUR
USERNAME AND PASSWORD?
Demystifying OAuth2 for PHP
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.”
Demystifying OAuth2 for PHP
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
Demystifying OAuth2 for PHP
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:
Demystifying OAuth2 for PHP
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!

More Related Content

PDF
Introduction to Applied Machine Learning
PPTX
Mastering the game of go with deep neural networks and tree search
PDF
PR-214: FlowNet: Learning Optical Flow with Convolutional Networks
PDF
Self-supervised Learning from Video Sequences - Xavier Giro - UPC Barcelona 2019
PDF
OAM_실물자산관리
PDF
Deep Learning for Video: Action Recognition (UPC 2018)
PPTX
확률의 구현법
DOCX
3301 FINAL PAPER
Introduction to Applied Machine Learning
Mastering the game of go with deep neural networks and tree search
PR-214: FlowNet: Learning Optical Flow with Convolutional Networks
Self-supervised Learning from Video Sequences - Xavier Giro - UPC Barcelona 2019
OAM_실물자산관리
Deep Learning for Video: Action Recognition (UPC 2018)
확률의 구현법
3301 FINAL PAPER

Viewers also liked (13)

PPTX
Mitologia y literatura
PDF
Last Month in PHP - September 2016
PDF
Final Project Report_301819G032
PDF
Combinacón de correspondencia 15 cartas pdf
PDF
Coordinating DV Responses
PPTX
Hardware y Software
PPTX
Metodologia de la investigacion constructo y variable jordana
DOC
Resume jake diamond-1
PDF
Carta comercial bloque estremo
PPT
формування іт компетентності та іт-культури»
DOCX
Especificaciones tecnicas chalhuani
PPT
семінар
PPTX
An Introduction to OAuth 2
Mitologia y literatura
Last Month in PHP - September 2016
Final Project Report_301819G032
Combinacón de correspondencia 15 cartas pdf
Coordinating DV Responses
Hardware y Software
Metodologia de la investigacion constructo y variable jordana
Resume jake diamond-1
Carta comercial bloque estremo
формування іт компетентності та іт-культури»
Especificaciones tecnicas chalhuani
семінар
An Introduction to OAuth 2
Ad

Similar to Demystifying OAuth2 for PHP (20)

PPTX
Integrating OAuth and Social Login Into Wordpress
PDF
Full stack security
PDF
Oauth Php App
PDF
Implementing OAuth with PHP
PDF
OAuth 2.0 and Library
PPTX
Api security
PPTX
(1) OAuth 2.0 Overview
PDF
Securing APIs with OAuth 2.0
PPTX
OAuth [noddyCha]
PPTX
OAuth2 para desarrolladores
PPTX
Devteach 2017 OAuth and Open id connect demystified
PDF
Top X OAuth 2 Hacks
PDF
OAuth - Open API Authentication
PDF
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
PDF
OAuth2
ODP
Securing your Web API with OAuth
ODP
Mohanraj - Securing Your Web Api With OAuth
PPTX
Introduction to OAuth2
PPTX
OAuth2 + API Security
Integrating OAuth and Social Login Into Wordpress
Full stack security
Oauth Php App
Implementing OAuth with PHP
OAuth 2.0 and Library
Api security
(1) OAuth 2.0 Overview
Securing APIs with OAuth 2.0
OAuth [noddyCha]
OAuth2 para desarrolladores
Devteach 2017 OAuth and Open id connect demystified
Top X OAuth 2 Hacks
OAuth - Open API Authentication
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
OAuth2
Securing your Web API with OAuth
Mohanraj - Securing Your Web Api With OAuth
Introduction to OAuth2
OAuth2 + API Security
Ad

More from SWIFTotter Solutions (7)

PDF
Developing a Web-Based business
PDF
Magento SEO Tips and Tricks
PDF
Composer and Git in Magento
PDF
eCommerce Primer - Part 1
PDF
A brief introduction to CloudFormation
PDF
What's new with PHP7
PDF
PHP: 4 Design Patterns to Make Better Code
Developing a Web-Based business
Magento SEO Tips and Tricks
Composer and Git in Magento
eCommerce Primer - Part 1
A brief introduction to CloudFormation
What's new with PHP7
PHP: 4 Design Patterns to Make Better Code

Recently uploaded (20)

PDF
DNT Brochure 2025 – ISV Solutions @ D365
PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PPTX
Python is a high-level, interpreted programming language
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
PDF
Practical Indispensable Project Management Tips for Delivering Successful Exp...
PPTX
Matchmaking for JVMs: How to Pick the Perfect GC Partner
PPTX
Airline CRS | Airline CRS Systems | CRS System
PDF
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
PDF
Wondershare Recoverit Full Crack New Version (Latest 2025)
PDF
Workplace Software and Skills - OpenStax
PPTX
Lecture 5 Software Requirement Engineering
PDF
Guide to Food Delivery App Development.pdf
PPTX
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
PPTX
Trending Python Topics for Data Visualization in 2025
PDF
Topaz Photo AI Crack New Download (Latest 2025)
DOCX
How to Use SharePoint as an ISO-Compliant Document Management System
PDF
AI-Powered Fuzz Testing: The Future of QA
PPTX
Computer Software - Technology and Livelihood Education
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PPTX
4Seller: The All-in-One Multi-Channel E-Commerce Management Platform for Glob...
DNT Brochure 2025 – ISV Solutions @ D365
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Python is a high-level, interpreted programming language
How Tridens DevSecOps Ensures Compliance, Security, and Agility
Practical Indispensable Project Management Tips for Delivering Successful Exp...
Matchmaking for JVMs: How to Pick the Perfect GC Partner
Airline CRS | Airline CRS Systems | CRS System
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
Wondershare Recoverit Full Crack New Version (Latest 2025)
Workplace Software and Skills - OpenStax
Lecture 5 Software Requirement Engineering
Guide to Food Delivery App Development.pdf
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
Trending Python Topics for Data Visualization in 2025
Topaz Photo AI Crack New Download (Latest 2025)
How to Use SharePoint as an ISO-Compliant Document Management System
AI-Powered Fuzz Testing: The Future of QA
Computer Software - Technology and Livelihood Education
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
4Seller: The All-in-One Multi-Channel E-Commerce Management Platform for Glob...

Demystifying OAuth2 for PHP