Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Simple Authentication for SPA & Mobile API

Simple Authentication for SPA & Mobile API

How to use PHP Sessions to simplify authentication for APIs and Single Page Applications without violation the stateless principle for RestFul webservices.

B82b1da7a58dcf37c8f0461c5c08ec0a?s=128

Ricardo Coelho

July 08, 2015
Tweet

Transcript

  1. Simple Authentication for SPA & Mobile API Ricardo Coelho @ramcoelho

  2. – Service Orientation Design Paradigm “Services are best kept stateless”

  3. Token based authentication AUTH_TOKEN

  4. Sessions FTW!

  5. Is $_SESSION a state? It depends…

  6. This one is definitely a state print_r($_SESSION); (Illustration: Massao Hotoshi/Casa

    e Jardim) Array ( [content] => Array ( ) )
  7. 1,000,000 users?! what if

  8. None
  9. But not this one… print_r($_SESSION); Array ( [auth] => valid@user.com

    )
  10. Spot the difference… POST /endpoint HTTP/1.1 Host: server.com Accept: application/json…

    Accept-Encoding: gzip, deflate Content-Type: application/json Connection: keep-alive { “token”: “SOME_TOKEN”, “info”: “some info” } POST /endpoint HTTP/1.1 Host: server.com Accept: application/json… Accept-Encoding: gzip, deflate Content-Type: application/json Cookie: PHPSESSID=SOME_ID Connection: keep-alive { “info”: “some info” }
  11. How do you handle 1,000,000 users? Tip: Server farm, obviously!

  12. How can you know where your request is going to

    land? Tip: There is no way.
  13. So, let’s make sure it doesn’t matter… The CACHE server

  14. Introducing http://memcached.org

  15. Meanwhile, in your Apache servers… $ sudo apt-get install php5-memcached

  16. Meanwhile, in your Apache servers… extension=memcached.so /etc/php5/conf.d/memcached.ini session.save_handler = memcached

    session.save_path = “memcached.mydomain.com:11211”
  17. $_SESSION[‘content’] = ‘Hello World!’; Hello World!

  18. echo $_SESSION[‘content’]; Hello World!

  19. Sessions allow really simple authentication Nevertheless, you should avoid storing

    business data on sessions.
  20. Create a resource Whenever you need to keep business data

    or large amount of information on the server.
  21. Create a resource Associate it with the user id stored

    in the session and avoid passing on every request, saving data plans on mobile.
  22. Thank you

  23. Questions?