SlideShare a Scribd company logo
www.mobiliya.com
Stateless Auth using OAUTH2 & JWT
Gaurav Roy, @MobiliYa
gaurav-roy-2457635
opengauravroy
- Spread the Knowledge, Initiative
- Jan 4th 2017
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
What is Authentication & Authorization ?
Authentication
Is the user, really who he claims to be?
For eq: Login using email + password
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
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
The Problem Statement
“SSO & Federation”
using “Authentication & Authorization”
“across different systems”
needs
“Standards”
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
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
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
Section #2 : OAuth2 in DEPTH
11
Actors in an OAuth2 system
1. Resource Owner
2. Client (App)
3. Authorization Server
4. Resource Server
12
OAuth 2 – “Resource Owner”
A User (human or machine)
“owning the resource” and/or
“capable of granting access to the resource”.
13
OAuth2 - “Client”
An Application (mobile or Web)
Wanting to access the resource
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
OAuth2 – “Resource Server”
A Server
Hosts the resource (owned by resource owner)
Provides the resource on validation of the resource
16
OAuth2 – “Access Token”
A Protected Object
Contains information regarding identity and privileges
associated with a user account
Issued by the “Authorization Server”
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
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
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
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
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
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
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
Flow #1: Auth Code Grant Flow
3rd Party or Own Web Apps (with server components)
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
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
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
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
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
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
Flow 1.2 : Code Grant Flow : User Consent
Deciphered
from Client ID
Deciphered
from Scope
User Consent
[will typically look like this]
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
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
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
Flow #2: Implicit Grant
No Auth Code – directly get a token
Basically, we don’t trust client to keep client-secret secure.
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
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
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
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
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
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
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
Flow #3: Resource Owner Credentials
Only for really trusted clients [owned by Auth/Resource server]
For eq: Mobile Apps of a web service
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
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
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
Section #3: Enter JWT (JSON WEB TOKEN)
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
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
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
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
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
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
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
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
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
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
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
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
Section#4: Auth Statelessness using JWT
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
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
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
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
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
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
Section #5 : How easy is OAuth2 with JWT
Lets try some code with Java Spring
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
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
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
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
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
© 2015. Mobiliya Technologies. All Rights Reserved Confidential under NDA www.mobiliya.com
Thank You

More Related Content

What's hot (20)

PDF
OAuth - Open API Authentication
leahculver
 
PPTX
An Introduction to OAuth2
Aaron Parecki
 
PDF
OpenID Connect Explained
Vladimir Dzhuvinov
 
PPTX
REST API Design & Development
Ashok Pundit
 
PPTX
OAuth 2
ChrisWood262
 
PPTX
OpenID Connect: An Overview
Pat Patterson
 
PDF
Spring security oauth2
axykim00
 
PDF
OAuth2 and Spring Security
Orest Ivasiv
 
PPTX
Json Web Token - JWT
Prashant Walke
 
PPTX
Open authentication (oauth)
Michael Maurice
 
PDF
JSON WEB TOKEN
Knoldus Inc.
 
PPTX
An introduction to OAuth 2
Sanjoy Kumar Roy
 
PDF
Jwt Security
Seid Yassin
 
PDF
JSON Web Tokens
Ivan Rosolen
 
PPTX
Pentesting ReST API
Nutan Kumar Panda
 
PPTX
Building secure applications with keycloak
Abhishek Koserwal
 
PDF
Spring Framework - Spring Security
Dzmitry Naskou
 
PPTX
Spring security
Saurabh Sharma
 
PPTX
API Security Fundamentals
José Haro Peralta
 
OAuth - Open API Authentication
leahculver
 
An Introduction to OAuth2
Aaron Parecki
 
OpenID Connect Explained
Vladimir Dzhuvinov
 
REST API Design & Development
Ashok Pundit
 
OAuth 2
ChrisWood262
 
OpenID Connect: An Overview
Pat Patterson
 
Spring security oauth2
axykim00
 
OAuth2 and Spring Security
Orest Ivasiv
 
Json Web Token - JWT
Prashant Walke
 
Open authentication (oauth)
Michael Maurice
 
JSON WEB TOKEN
Knoldus Inc.
 
An introduction to OAuth 2
Sanjoy Kumar Roy
 
Jwt Security
Seid Yassin
 
JSON Web Tokens
Ivan Rosolen
 
Pentesting ReST API
Nutan Kumar Panda
 
Building secure applications with keycloak
Abhishek Koserwal
 
Spring Framework - Spring Security
Dzmitry Naskou
 
Spring security
Saurabh Sharma
 
API Security Fundamentals
José Haro Peralta
 

Viewers also liked (20)

PDF
Iot & smart cities
Mobiliya
 
PDF
Web 2.0 Expo Berlin: OpenID Emerging from Web 2.0
David Recordon
 
PDF
JWT Agile Framework
Emmanuel Flores Elías
 
PDF
Reactive Microservices with Vert.x
Anderson Braz
 
PPT
Understanding OpenID
Prabath Siriwardena
 
PPTX
JWT Authentication with AngularJS
robertjd
 
PPTX
Conversations as a Platform
Joshua Drew
 
PDF
OpenID Bootcamp Tutorial
David Recordon
 
PPTX
Microsoft bot framework in azure
Shahriar Hossain
 
PDF
OpenID Authentication by example
Chris Vertonghen
 
PDF
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Java User Group Latvia
 
PDF
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Matt Raible
 
PDF
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Alvaro Sanchez-Mariscal
 
PDF
Game On: Everything you need to know about how games are changing the world
Jeremy Johnson
 
PDF
SAML / OpenID Connect / OAuth / SCIM 技術解説 - ID&IT 2014 #idit2014
Nov Matake
 
PDF
Stateless authentication for microservices
Alvaro Sanchez-Mariscal
 
PDF
Alexa, nice to meet(js) you!
Artur Skowroński
 
PDF
Implications Of OpenID (Google Tech Talk)
Simon Willison
 
PDF
7 Psychological Tactics Used in Games
Dori Adar
 
PPTX
Getting Started with Microsoft Bot Framework
Sarah Sexton
 
Iot & smart cities
Mobiliya
 
Web 2.0 Expo Berlin: OpenID Emerging from Web 2.0
David Recordon
 
JWT Agile Framework
Emmanuel Flores Elías
 
Reactive Microservices with Vert.x
Anderson Braz
 
Understanding OpenID
Prabath Siriwardena
 
JWT Authentication with AngularJS
robertjd
 
Conversations as a Platform
Joshua Drew
 
OpenID Bootcamp Tutorial
David Recordon
 
Microsoft bot framework in azure
Shahriar Hossain
 
OpenID Authentication by example
Chris Vertonghen
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Java User Group Latvia
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Matt Raible
 
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Alvaro Sanchez-Mariscal
 
Game On: Everything you need to know about how games are changing the world
Jeremy Johnson
 
SAML / OpenID Connect / OAuth / SCIM 技術解説 - ID&IT 2014 #idit2014
Nov Matake
 
Stateless authentication for microservices
Alvaro Sanchez-Mariscal
 
Alexa, nice to meet(js) you!
Artur Skowroński
 
Implications Of OpenID (Google Tech Talk)
Simon Willison
 
7 Psychological Tactics Used in Games
Dori Adar
 
Getting Started with Microsoft Bot Framework
Sarah Sexton
 
Ad

Similar to Stateless Auth using OAUTH2 & JWT (20)

PDF
Stateless Auth using OAuth2 & JWT
Gaurav Roy
 
PDF
Spring4 security oauth2
Sang Shin
 
PDF
Spring4 security oauth2
axykim00
 
PPTX
Devteach 2017 OAuth and Open id connect demystified
Taswar Bhatti
 
PPTX
Oauth2 and OWSM OAuth2 support
Gaurav Sharma
 
PDF
Stateless authentication for microservices applications - JavaLand 2015
Alvaro Sanchez-Mariscal
 
PDF
OAuth: Trust Issues
Lorna Mitchell
 
PPTX
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
PDF
OAuth2
SPARK MEDIA
 
PPTX
(1) OAuth 2.0 Overview
anikristo
 
PDF
O auth2.0 guide
Dilip Mohapatra
 
PPTX
Introduction to OAuth2
Kumaresh Chandra Baruri
 
PPTX
OAuth
Tom Elrod
 
PPTX
O auth
Ashok Kumar N
 
PPTX
OAuth 2 Spring Boot 3 Integration Presentation
Knoldus Inc.
 
PDF
OAuth and why you should use it
Sergey Podgornyy
 
PDF
Full stack security
DPC Consulting Ltd
 
PDF
Stateless authentication for microservices - GR8Conf 2015
Alvaro Sanchez-Mariscal
 
PPTX
OAuth2 + API Security
Amila Paranawithana
 
PDF
Keeping Pace with OAuth’s Evolving Security Practices.pdf
Sirris
 
Stateless Auth using OAuth2 & JWT
Gaurav Roy
 
Spring4 security oauth2
Sang Shin
 
Spring4 security oauth2
axykim00
 
Devteach 2017 OAuth and Open id connect demystified
Taswar Bhatti
 
Oauth2 and OWSM OAuth2 support
Gaurav Sharma
 
Stateless authentication for microservices applications - JavaLand 2015
Alvaro Sanchez-Mariscal
 
OAuth: Trust Issues
Lorna Mitchell
 
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
OAuth2
SPARK MEDIA
 
(1) OAuth 2.0 Overview
anikristo
 
O auth2.0 guide
Dilip Mohapatra
 
Introduction to OAuth2
Kumaresh Chandra Baruri
 
OAuth
Tom Elrod
 
OAuth 2 Spring Boot 3 Integration Presentation
Knoldus Inc.
 
OAuth and why you should use it
Sergey Podgornyy
 
Full stack security
DPC Consulting Ltd
 
Stateless authentication for microservices - GR8Conf 2015
Alvaro Sanchez-Mariscal
 
OAuth2 + API Security
Amila Paranawithana
 
Keeping Pace with OAuth’s Evolving Security Practices.pdf
Sirris
 
Ad

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Digital Circuits, important subject in CS
contactparinay1
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 

Stateless Auth using OAUTH2 & JWT

  • 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 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 What is Authentication & Authorization ? Authentication Is the user, really who he claims to be? For eq: Login using email + password
  • 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 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 The Problem Statement “SSO & Federation” using “Authentication & Authorization” “across different systems” needs “Standards”
  • 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 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 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 Section #2 : OAuth2 in DEPTH
  • 11. 11 Actors in an OAuth2 system 1. Resource Owner 2. Client (App) 3. Authorization Server 4. Resource Server
  • 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 OAuth2 - “Client” An Application (mobile or Web) Wanting to access the resource
  • 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 OAuth2 – “Resource Server” A Server Hosts the resource (owned by resource owner) Provides the resource on validation of the resource
  • 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 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 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 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 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 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 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 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 Flow #1: Auth Code Grant Flow 3rd Party or Own Web Apps (with server components)
  • 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 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 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 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 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 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 Flow 1.2 : Code Grant Flow : User Consent Deciphered from Client ID Deciphered from Scope User Consent [will typically look like this]
  • 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 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 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 Flow #2: Implicit Grant No Auth Code – directly get a token Basically, we don’t trust client to keep client-secret secure.
  • 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 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 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 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 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 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 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 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 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 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 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 Section #3: Enter JWT (JSON WEB TOKEN)
  • 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 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 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 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 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 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 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 B. JWT Claims / Payload { "iss":“oauth2.mobiliya.com", “sub” : ”Roy’s Access-token”, "exp":1300819380, “iat” : 1300803380, “nbf” : 1300803380, “jti” : “8973-r38893-288346834”, ======================== “email” : [email protected], “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 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 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 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 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
  • 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 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 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 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 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 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 Section #5 : How easy is OAuth2 with JWT Lets try some code with Java Spring
  • 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 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 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 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 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. © 2015. Mobiliya Technologies. All Rights Reserved Confidential under NDA www.mobiliya.com Thank You