Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Demystifying OAuth2 for PHP

698 views

Published on

I used to dislike OAuth (Open Standard for Authentication): how do I implement it? In this slideshow, we delve into consuming it with the Google APIs. We go first into the background and then step-by-step through the process. Follow along today!

Published in: Software
  • Be the first to comment

Demystifying OAuth2 for PHP

  1. 1. WHO DO YOUTRUST WITH YOUR USERNAME AND PASSWORD?
  2. 2. WE NEEDTO ACCESS DATA INTHE CLOUD.
  3. 3. WE DON’T WANTTO STORE THEIR USERNAME/PASSWORD.
  4. 4. THERE MUST BE AN ANSWER.
  5. 5. OPEN STANDARD FOR AUTHORIZATION V2
  6. 6. The framework for a secure link between provider, customer and us.
  7. 7. 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
  8. 8. OAUTH IS… • an Authorization protocol. • not an Authentication protocol. • (from the perspective of the web developer)
  9. 9. AUTHORIZATION: “I GIVE YOU PERMISSION.”
  10. 10. AUTHENTICATION: “I KNOW WHO YOU ARE.”
  11. 11. 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.
  12. 12. OAUTH GRANTS • Authorization Code grant • Implicit grant • Resource owner credentials grant • Client credentials grant
  13. 13. WITHOUT OAUTH2 Web Developer Customer Provider (ex. Google API)
  14. 14. WITH OAUTH Web Developer Customer Provider (ex. Google API) OAuth2
  15. 15. OAUTH PROCESS: • We redirect user to provider (Google/Facebook/etc.). • User authorizes us. • We obtain access token. • We make requests with access token.
  16. 16. WHO LIKES 100 GRANDSTWIX?
  17. 17. Hasstoredthemsafely inescrow. Wantsa100grand. 100GRANDESCROW
  18. 18. http://www.mrwallpaper.com/hungry-cat-wallpaper/ Hasdecidedto shareONE. Wantsa100grand. 100GRANDESCROW
  19. 19. 100GRANDESCROW Directsme… …toEscrowProvider
  20. 20. 100GRANDESCROW “Isitoktoshare withAndrew?”
  21. 21. 100GRANDESCROW “Yes.”
  22. 22. 100GRANDESCROW Secretword: “Yummy”
  23. 23. 100GRANDESCROW “Yummy” Secretword: “Yummy”
  24. 24. 100GRANDESCROW “Yummy” “Yummy” Secretword: “Yummy”
  25. 25. 100GRANDESCROW “Crunchy”
  26. 26. 100GRANDESCROW “Crunchy”
  27. 27. 100GRANDESCROW
  28. 28. PROVIDER(EX.GOOGLE) WebDeveloper Customer
  29. 29. OAUTH PROCESS: • We redirect user to provider (Google/Facebook/etc.). • User authorizes us. • We obtain access token. • We make requests with access token.
  30. 30. 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.
  31. 31. 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.
  32. 32. THE PROVIDER?
  33. 33. Users Developers Provider Client ID Client Secret Name Allowed Scopes Whitelisted Domains Tokens/Codes
  34. 34. 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
  35. 35. 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.
  36. 36. AUTHORIZATION SERVER • Looks up the authorization code. • Generates the access token. • Returns access token back to us.
  37. 37. DO IT YOURSELF… • https://oauth2.thephpleague.com/ • As always, an excellent package by the amazing PHP League
  38. 38. LET’S SEE HOW IT IS DONE!
  39. 39. PROVIDER: GOOGLE
  40. 40. GOAL: ACCESS LIST OF CUSTOMER FILES IN GOOGLE DRIVE.
  41. 41. https://github.com/ JosephMaxwell/ OAuth2Implementation/
  42. 42. ONLINE STEPS • Go to: http://console.developers.google.com/ • Enable Drive API • Create OAuth Credentials
  43. 43. 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
  44. 44. OAUTH IN PHP… “If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
  45. 45. 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]

  46. 46. 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.
  47. 47. USER DOESTHEIR MAGIC:
  48. 48. 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
  49. 49. $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]);
  50. 50. $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]);
  51. 51. { "access_token":"1/asdf1234asdf1234asdf1234", "expires_in":3920, "token_type":"Bearer" }
  52. 52. $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());
  53. 53. // 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() ]; // . . .
  54. 54. IN A LIBRARY… “The best performance improvement is the transition from the nonworking state to the working state.” (J. Osterhout)
  55. 55. LIBRARY: • The PHP library: • The PHP League: OAuth2 Client • https://github.com/thephpleague/oauth2-client
  56. 56. INITIALIZATION $this->provider = new Google([
 'clientId' => $this->config->getClientId(),
 'clientSecret' => $this->config->getClientSecret(),
 'redirectUri' => $this->helper->getCallbackUrl(self::AREA)
 ]);
  57. 57. AUTHORIZATION REDIRECT $url = $this->provider->getAuthorizationUrl( ['scope' => $config::SCOPE] ); $_SESSION['oauth2_state'] = $this->provider->getState();
 
 header("Location: {$url}");
  58. 58. ACCESSTOKEN $token = $this->provider->getAccessToken( 'authorization_code', [ 'code' => $_GET[‘code'] ] );
  59. 59. $fileResponse = $client->get( 'https://www.googleapis.com/drive/v2/files', [
 'headers' => [ 'Authorization' => $token->getToken(), 'Referer' => 'http://oauth2implementation.com' ] ] ); 
 $files = new Files($fileResponse->getBody());
  60. 60. DO: • Protect against common security threats. • Store random state key in the session and send that to the provider. • Store the access token securely.
  61. 61. 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.
  62. 62. 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.
  63. 63. CLIENT CREDENTIALS GRANT • Machine-to-machine authentication. • Agreed-upon signature that has limited permissions associated with it.
  64. 64. 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.
  65. 65. 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/
  66. 66. 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.
  67. 67. QUESTIONS?
  68. 68. GO FORTH AND CONNECT!

×