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.

Stateless Auth using OAUTH2 & JWT

340 views

Published on

1. Intro - Auth - Authentication & Authorization & SSO
2. OAuth2 in Depth
3. Where does JWT fit in ?
4. How to do stateless Authorization using OAUTH2 & JWT ?
5. Some Sample Code ? How easy is it to implement ?

Published in: Technology
  • Be the first to comment

Stateless Auth using OAUTH2 & JWT

  1. 1. www.mobiliya.com Stateless Auth using OAUTH2 & JWT Gaurav Roy, @MobiliYa gaurav-roy-2457635 opengauravroy - Spread the Knowledge, Initiative - Jan 4th 2017
  2. 2. 2 Agenda 1. Intro - Auth - Authentication & Authorization & SSO 2. OAuth2 in Depth 3. Where does JWT fit in ? 4. How to do stateless Authorization using OAUTH2 & JWT ? 5. Some Sample Code ? How easy is it to implement ?
  3. 3. 3 What is Authentication & Authorization ? Authentication Is the user, really who he claims to be? For eq: Login using email + password
  4. 4. 4 What is Authorization? Authorization Is this “authentic” user, allowed to do Operation “X” on our system? For eq: Whether logged in user, can upload photos? Can user access the resource?
  5. 5. 5 What is SSO? SSO : Single Sign On User has same credentials across multiple sites. (maybe achieved via Federation concept – same identity across different sites) For eq: Stackoverflow trusts Google to do a good job at authentication. Stackoverflow implements SSO with Google-ID. Google User authentication works on stackoverflow
  6. 6. 6 The Problem Statement “SSO & Federation” using “Authentication & Authorization” “across different systems” needs “Standards”
  7. 7. 7 Enter OAuth2 “OAuth2 is an Open standard for Authorization” Note: There are others too But all the big guys in previous page implement OAuth2 (Facebook, Google, Yahoo, Twitter) Authentication can have its own protocol. https://tools.ietf.org/html/rfc6749
  8. 8. 8 What are popular SSO going around? For Federation, Accounts market share matters. NOT STANDARDS Would you Federate with an authentication service that has 5 users or 50 million ? Hence, dev prefer to federate with Google, Facebook, Twitter – all do OAuth2 Reason: Usually, probability of a user already having account higher here.
  9. 9. 9 Can I implement my OAuth2 service too ? You could implement your own service and ask other to work with your OAuth2 spec. NOTHING STOPPING THAT! IT’S A LEVEL FIELD. Your app could be here too ?
  10. 10. 10 Section #2 : OAuth2 in DEPTH
  11. 11. 11 Actors in an OAuth2 system 1. Resource Owner 2. Client (App) 3. Authorization Server 4. Resource Server
  12. 12. 12 OAuth 2 – “Resource Owner” A User (human or machine) “owning the resource” and/or “capable of granting access to the resource”.
  13. 13. 13 OAuth2 - “Client” An Application (mobile or Web) Wanting to access the resource
  14. 14. 14 OAuth2 – “Authorization Server” A Server Authenticates the resource owner Knows username/password of the resource owner Issues access tokens on behalf of resource owner
  15. 15. 15 OAuth2 – “Resource Server” A Server Hosts the resource (owned by resource owner) Provides the resource on validation of the resource
  16. 16. 16 OAuth2 – “Access Token” A Protected Object Contains information regarding identity and privileges associated with a user account Issued by the “Authorization Server”
  17. 17. 17 OAuth2 Actors “Recap” •Validates access token •Provides resource to client app •Validates credentials •Provides access token representing the Resource Owner •Wants •Access token from Authorization Server •To access Resource on Resource Server •Owns/Delegates •Credentials to Access the Resource •Can •Generate access token from Auth Server Resource Owner Client App Resource Server Auth Server
  18. 18. 18 What are we trying to do with OAuth2? A “user” (resource owner), who has an account on “Auth Server” & who has a resource on “Resource Server” Delegates access privilege to a “Client” (app) using a token generated by the “Auth Server” To access the Resource on “Resource Server”
  19. 19. 19 OAuth2 – Main Value Add Resource Owner Resource Server Resource Server has no information regarding the credentials of the Resource owner But can still give him or his clients access
  20. 20. 20 When do you need OAuth2? 1. AuthServer : Your Service wants to implement Identity Management and expose APIs for other services to use your identity 2. Client : Your Service wants SSO with Google, Office365, etc or a Proprietary Auth Server 3. Resource Server: Your Service wants to expose Resources but would like authentication to happen with another service (internal or external) 4. Resource Server: Your big Service wants to split into multiple Services (aka micro-services) and would like SSO & Authorization checks between micro-services.
  21. 21. 21 Setup of OAuth2 [one time setup] Client (App) Registration One time only, for every Client App. Usually a registration form in the developer or API section of AuthServer website Client App will provide following to Auth Server (or more) 1. App Name [shows resource owner] 2. App Website URI 3. Redirect URI Auth Server will provide following to Client 1. Client Id [publicly exposed] 2. Client Secret [should be protected]
  22. 22. 22 Authorization Grant Flows [daily operation] 4 Types of Grant Flows/Types Available for OAuth2 [can support one/more] 1. Authorization Code Grant 2. Implicit Grant 3. Resource Owner Credentials 4. Client Credentials
  23. 23. 23 OH GOD! Which Grant Flow to use When? Cheat Sheet [guideline, not a MUST] Auth Code Grant: 3rd Party or Web Server Apps Implicit: 3rd Party Mobile / Web Apps (no backend) Resource Owner Creds: Apps owned by the Auth Server company Client Credentials: NO UI Backend - Micro-services API Access
  24. 24. 24 Flow #1: Auth Code Grant Flow 3rd Party or Own Web Apps (with server components)
  25. 25. 25 Flow 1.1 Code Grant Flow : Auth Code Request Resource Owner Client Auth Server Resource Server 1. Auth Code Request authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS
  26. 26. 26 Flow 1.1 Code Grant Flow : Auth Code Request Resource Owner Client Auth Server Resource Server 1. Auth Code Request authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS response_type = code [indicates the Auth Code Grant Flow]
  27. 27. 27 Flow 1.1 Code Grant Flow : Auth Code Request Resource Owner Client Auth Server Resource Server 1. Auth Code Request authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS client_id = id [which client app is initiating the flow client id received in setup flow]
  28. 28. 28 Resource Owner Client Auth Server Resource Server 1. Auth Code Request authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS Flow 1.1 Code Grant Flow : Auth Code Request redirect_uri = uri [user is redirected to this uri after authentication – success or failure]
  29. 29. 29 Resource Owner Client Auth Server Resource Server 1. Auth Code Request authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS Flow 1.1 Code Grant Flow : Auth Code Request scope = PHOTOS [level of access, app is trying to access]
  30. 30. 30 Resource Owner Client Auth Server Resource Server 1. Auth Code Request authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS 2. SHOW Login & Consent Pages [accept user creds] [scope and app approval from user] Flow 1.2 Code Grant Flow : User Consent Auth server 1. Validates User Creds 2. Takes Consent on Client + Scope
  31. 31. 31 Flow 1.2 : Code Grant Flow : User Consent Deciphered from Client ID Deciphered from Scope User Consent [will typically look like this]
  32. 32. 32 Flow 1.3 : Code Grant Flow : Auth Code Resource Owner Client Auth Server Resource Server 1. Auth Code Request authserver/authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS 2. SHOW Login & Consent Pages [accept user creds] [scope and app approval from user] OK 3. redirect_uri/?code=AUTHORIZATION_CODE Auth server 1. Sends “Auth Code” to the Client (super-limited time code) 2. Contents of Code – can be anything
  33. 33. 33 Flow 1.4 : Code Grant Flow : Access Token Request Resource Owner Client Auth Server Resource Server 1. Auth Code Request authserver/authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS 2. SHOW Login & Consent Pages [accept user creds] [scope and app approval from user] OK 3. redirect_uri/?code=AUTHORIZATION_CODE 4. Access Token Request authserver/oauth/token? client_id=CLIENT_ID& client_secret=CLIENT_SECRET& grant_type=authorization_code& code=AUTHORIZATION_CODE& redirect_uri=CALLBACK_URL Access Token Request 1. Code – identifies – scope, user, client 2. Client ID/Secret – identifies the client
  34. 34. 34 3. Get Resource (access-token) 4. Resource Flow 1.5 : Code Grant Flow : Access Token + Refresh Token Resource Owner Client Auth Server Resource Server 1. Auth Code Request authserver/authorize? response_type=code& client_id=ID& redirect_uri=URL& scope=PHOTOS 2. SHOW Login & Consent Pages [accept user creds] [scope and app approval from user] OK 3. redirect_uri/?code=AUTHORIZATION_CODE 4. Access Token Request authserver/oauth/token? client_id=CLIENT_ID& client_secret=CLIENT_SECRET& grant_type=authorization_code& code=AUTHORIZATION_CODE& redirect_uri=CALLBACK_URL 5. token Transfer {"access_token", "refresh_token" ,"scope":"read"," "info":{auth server defined user info}} 1. Access Token : Token to access api 2. Refresh Token : Token to refresh access token on expiry • Refresh token is optional and MUST not be decode-able
  35. 35. 35 Flow #2: Implicit Grant No Auth Code – directly get a token Basically, we don’t trust client to keep client-secret secure.
  36. 36. 36 Flow 2.1: Implicit Grant Flow : Auth Resource Owner Client Auth Server Resource Server 1. Auth Token Request authserver/authorize? type=token& client_id=ID& redirect_uri=URI &scope=photos 1. ClientID : identifies the client 2. Refresh URL : redirect url
  37. 37. 37 Resource Owner Client Auth Server Resource Server 1. Auth Token Request authserver/authorize? type=token& client_id=ID& redirect_uri=URI &scope=photos2. SHOW Login & Consent Pages [accept user creds] [scope and app approval from user] OK 3. token Transfer {"access_token"} 3. Get Resource (access-token) 4. Resource Flow 2.2 & 2.3: Implicit Grant Flow : Auth 1. Access token is transferred
  38. 38. 38 Flow 2: Implicit Grant Did you notice the flow ? “has one less leg” – no auth code “has no client secret” “has no refresh token”
  39. 39. 39 Flow 2: Implicit Grant Why is Implicit Flow so small in comparison to Code Grant ? For JavaScript Front ends – cannot keep a secret (client-secret or refresh-token) Used for Limited time user sessions Requires Cross Origin Resource Sharing (CORS) Client has onus to prevent CSRF (Cross site Request forgery) So, in a sense it maybe less secure for the Resource Server
  40. 40. 40 Flow 2 : Implicit Flow - CSRF How is implicit Flow vulnerable to CSRF? 1. Attacker (Resource Owner) loads a Client Website 2. Client calls Authorize to initiate implicit flow on the Auth Server 3. Attacker is redirected to the Auth Server, for credential entry in order to authorize access 4. Instead, Attacker traps/prevents this request and saves the URL 5. Attacker gets Victim (Resource Owner) to visit the saved URL. 6. If Victim is logged-in to the Auth Server with victim’s account, then victim credentials are used to issue an access token 7. Now attacker on the client is authorized to access resource owner account on the resource server Phishing Cross-site Request Forgery
  41. 41. 41 Flow 2 : Implicit – CSRF How to prevent CSRF in Clients ? 1. Attacker (Resource Owner) loads a Client Website 2. Client creates a state parameter (some unique value based on Attackers userinfo) 3. Client calls Authorize to initiate implicit flow on the Auth Server (passes the state parameter along with request) 4. Attacker is redirected to the Auth Server, for credential entry in order to authorize access 5. Instead, Attacker traps/prevents this request and saves the URL 6. Attacker gets Victim (Resource Owner) to visit the saved URL. 7. If Victim is logged-in to the Auth Server with victim’s account, then victim credentials will be used to issue an access token 8. Client regenerates the state parameter based on the current user. Since, they don’t match, the token will be rejected. 9. Now attacker on the client is authorized to access resource owner account on the resource server
  42. 42. 42 Flow 2 : Implicit Vs Auth Code Grant Auth Code Grant – access token is never generated for a CSRF attack (auth code is a limited time code) Client can reject the attacker at the Auth Code level. Hence Auth Code Grant, it’s a little easier to secure than Implicit Grant
  43. 43. 43 Flow #3: Resource Owner Credentials Only for really trusted clients [owned by Auth/Resource server] For eq: Mobile Apps of a web service
  44. 44. 44 Resource Owner Client Auth Server Resource Server 1. Auth Token Request authserver/authorize? type=password& client_id & client_secret & redirect_uri & username & password& 2. token Transfer {"access_token" + refresh token} 1. Pass Creds (username, pass) 3. Get Resource (access-token) 4. Resource Flow 3.1 & 3.2: Credential Grant 1. Trusted client (client id + secret) 2. Resource owner trusts client with credentials 3. Auth Server gives tokens based on client secret, password.
  45. 45. 45 Flow #4 : Client Credentials Micro-services in trusted network belonging to the same website as resource server Data access not related to a user
  46. 46. 46 Resource Owner Client Auth Server Resource Server 1. Auth Token Request authserver/authorize? type=client_credentials& client_id & client_secret & scope 2. token Transfer {"access_token"} 3. Get Resource (access-token) 4. Resource Flow 4: Client Credentials 1. Access token sent based on client credentials (of micro-service) 2. Refresh token is not recommended as Micro-service can always request for new access-token again
  47. 47. 47 Section #3: Enter JWT (JSON WEB TOKEN)
  48. 48. 48 Access & Refresh Token Access Token Can be of Any format that the Auth Server likes. MAY have information decodeable by the clients Refresh Token Can be of Any format that the Auth Server likes. MUST NOT have information readable by the clients
  49. 49. 49 Access Token Requirements in OAuth2 OAuth2 Access Token (aka Bearer Token) A Few Requirements 1. Bearer token needs to be protected in storage and transport 2. Any party in possession of bearer token can use it to access associated resource. 3. Only Auth server can generate a valid bearer token 4. Anyone can validate a bearer token (taking some help from the Auth Server)
  50. 50. 50 One Available Token Standard : JWT (aka “jot”) Rather than defining your own token - use a standard Advantage : Libraries available for JWT + OAuth2 JWT : Set of Claims (protected information) encoded in a json object Claims maybe digitally signed and/or encrypted (why would you not?) Full Form “JSON Web Token” JWT RFC : https://tools.ietf.org/html/rfc7519
  51. 51. 51 Why choose JWT? JWT implementations exist for Clojure, .NET , Go, Haskell, Python, Node.js, Java, JavaScript, Lua, Perl, PHP, Ruby, Rust, S cala, Elixir. That’s most of the Server programming languages going around TODAY.
  52. 52. 52 Structure of a JWT Token Header : Json (plaintext) Algorithm used for encoding claims. Can be none, if not encoded. Could select JWS (signed) or JWE (encrypted) Claims : Json (encoded) • Resource owner information • Token issues information • When is this token valid? • What other info/privileges/scopes etc the token has? (fields completely flexible) Signature: Hash { Header + Claims + Secret}
  53. 53. 53 A. JWT Header { “typ” : “JWT”, “alg” : “HS256” } Algorithm chosen for encoding and signing A lot of them available {optionally, authserver can put own pairs in header}
  54. 54. 54 Which Keys to use for Access & Refresh Tokens Access Token - use a Public/Private Key Pair Others would like to decode your token Public Key should be accessible to all interested. Refresh Token - use a Private/secret key MUST be encrypted using a salt or a private key. Public key of refresh token should not be queryable. Why? – Refresh token is used to generate an access token – No info useful in it, except for the Auth Server. Only Auth Server should decode refresh key.
  55. 55. 55 B. JWT Claims / Payload { "iss":“oauth2.mobiliya.com", “sub” : ”Roy’s Access-token”, "exp":1300819380, “iat” : 1300803380, “nbf” : 1300803380, “jti” : “8973-r38893-288346834”, ======================== “email” : roy@mobiliya.com, “name” : “Gauav Roy”, “access” : [ “photos”, “videos” ] } Registered Claims (predefined by JWT) 1. iss – Issuer? 2. sub – what is in this token? 3. exp – expires at? 4. iat – issued at 5. nbf – token not valid before 6. jti – jwt unique id ======================== Private claims - Anything that the client, resource server or auth server requires. - Keep information regarding the user, scope of the token, user attributes etc.
  56. 56. 56 B. JWT Registered & Private Cliams Standardized claims Predefined names Related to JWT Private (Free form) Claims Anything that you would like to use? This is a great way to send various pieces of information related to the user, authorization or scope
  57. 57. 57 C. JWT Signature HMAC( (base64Encode(header) + “.” + base64Encode(claims)), secret ) JWT could be signed with • Public/Private Key pair • Secure has based on Salt Algorithm for signing based on the “typ” field in JWT Header
  58. 58. 58 Final JWT Token – Base64 Encoded eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyJpc3MiOiJvYXV0aDIubW9iaWxpeWEuY29tIiwic3ViIj oiUm95J3MgQXV0aCBUb2tlbiIsImV4cCI6MTMwMDg xOTM4MCwiaWF0IjoxMzAwODAzMzgwLCJuYmYiOjEz MDA4MDMzODAsImVtYWlsIjoiZ2F1cmF2LnJveUBtb2 JpbGl5YS5jb20iLCJuYW1lIjoiR2F1cmF2IFJveSJ9. gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI JWT HEADER JWT CLAIMS / PAYLOAD JWT SIGNATURE JWT Sections are separate by “dot” . Typically, everyone uses 1. HMAC with SHA-256 (HS256) and 2. RSA signature with SHA-256 (RS256). Have some fun, decode above token at : https://jwt.io/
  59. 59. 59 Bonus – JWT Protects against CSRF Auth Server Resource Server Attacker (Client) Get Auth Token (with client-id) User Consent URL User Consent URL OK, giving consent JWT access token (with user = victim, client = attacker) Victim (Res owner) Client decodes token to understand that the user of client and user on token dont match Auth Server encodes claims JWT Private claims achieves state required to foil CSRF attacks. Without JWT, this would need to be specifically placed by the client in the header and reflected back by the server. STANDARDS MAKE LIFE EASY AGAIN
  60. 60. 60 Section#4: Auth Statelessness using JWT
  61. 61. 61 Monolithic Server – Auth Session Mgmt Identity Mgmt + Authentication Content Mgmt User Settings Analytics Billing & Order Mgmt Load Balancer Router Clients Clients All Business Logic/Data on one server/DB - Easy to share a session / authentication info - Use a DB, share in memory
  62. 62. 62 Micro-services Stack Identity Mgmt + Authentication Content Mgmt User Settings Analytics Billing & Order Mgmt Load Balancer Router Clients Clients Business Logic/Data on different machines/DB - Need to communicate to share a session or authentication info
  63. 63. 63 What is statefulness? Client – Server need to communicate using a variety of packets. Server needs to maintain state of the session with the client. Easier when the server is a “monolith” Hard when the server is a set of “micro-services” Micro-services : Session is distributed. Authorization is distributed
  64. 64. 64 JWT to the rescue Auth Statelessness Remember – Private Claims Private Claims : “Can send arbitrary pieces of information” DON’T STORE the token or give api to other micro-services to get info from Token Encode JWT to transfer the information for you User info Roles of the user Access Rights Whatever you need to transfer from the Auth Server to Resource Server Information / State is being transferred without any api
  65. 65. 65 Old Style Auth : without a OAuth2 & JWT state transfer ? Client Auth Server Resource Server 1. Authenticate (some flow) access token save token, userinfo in DB GET /resource/resourceid {access-token} give user for token, give his role give his billing give info Read token, session DB return Resource Before OAuth2 or JWT the Resource server would need to go to the Auth server to validate the token and get a lot of information regarding the user (resource owner)
  66. 66. 66 New Style : Stateless Auth using OAUTH2 + JWT Client Auth Server Resource Server 1. Authenticate (some flow) access token (encoded with resource owner info) save token, userinfo in DB GET /resource/resourceid {access-token} give user for token, give his role give his billing give info Read token, session DB return Resource Locally 1. Validate the token 2. Extract user Info Advantages: 1. No state DB in Auth server 2. No load on Auth server for validation of access-token 3. No load on Auth server for retrieval of resource owner info 4. Lesser latency
  67. 67. 67 Section #5 : How easy is OAuth2 with JWT Lets try some code with Java Spring
  68. 68. 68 OAuth2 (using Spring Boot) Would really advise https://spring.io/guides/tutorials/spring-boot-oauth2/ It will take you exactly 15 mins to Write a OAuth2 client with SSO with Facebook & Github and any others. Write your own OAuth2 Auth Server Write your own OAuth2 Resource Server Over the next pages are some excerpts from there
  69. 69. 69 Java Spring OAuth2 “Client” 1. Include the OAuth2 Dependency 2. Annotate your app with @EnableOAuth2Sso - This will automatically call the right endpoints and follow the client side of OAuth2 Protocol 3. Configuration 1. OAuth2 : Client ID + Secret 2. Access Token URL: of Auth Provider 3. User Authorization URL: How AuthProvider will ask consent AND YOU ARE ALL SET! MAGIC! STANDARDS MAKE LIFE SO MUCH EASIER!
  70. 70. 70 Java Spring OAuth2 “Auth Server" 1. Include the OAuth2 Dependency 2. Annotate your app with @EnableAuthorizationServer - Annotation implements the bunch of endpoints for you 3. Configuration 1. Allowed OAuth2 Clients : Client ID + Secret 2. Scopes supported :
  71. 71. 71 Java Spring OAuth2 “Resource Server" 1. Include the OAuth2 Dependency 2. Annotate your app with @EnableResourceServer - Protects “/me” using the access token. - authorizeRequests() will check the token validity
  72. 72. 72 References: JWT RFC : https://tools.ietf.org/html/rfc7519 OAuth2 RFC : https://tools.ietf.org/html/rfc6749 https://jwt.io/ https://spring.io/ Various Icons : https://commons.wikimedia.org/ https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2 https://en.wikipedia.org/wiki/JSON_Web_Token http://www.adweek.com/socialtimes/janrain-social-login-study/428890 https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java
  73. 73. © 2015. Mobiliya Technologies. All Rights Reserved Confidential under NDA www.mobiliya.com Thank You

×