SlideShare uma empresa Scribd logo
1 de 58
Baixar para ler offline
MODERN SECURITY WITH
OAUTH 2.0 AND JWT AND
SPRING
Dmitry Buzdin
03.11.2016
AGENDA
➤ Single-sign on
➤ OAuth 2.0
➤ JSON Web Tokens
➤ Some Spring examples
➤ You will learn what is it and why you need that
OAUTH 2.0
Explained
_________
SECURITY MATTERS
➤ Every app needs security
➤ Basic security knowledge is a must
➤ Developers are ignoring security sometimes
➤ Security is based on standards - do not invent stuff!
SINGLE SIGN-ON
➤ Accessing multiple systems with single id and password
➤ Centralised control of access rights
➤ Well known protocols
➤ LDAP
➤ Kerberos
➤ SAML 2.0
➤ OpenID
➤ OAuth 2.0
WHY YOU NEED SSO?
➤ Internal applications with one corporate login
➤ Integration with platform as a service
➤ Web sites with business affiliates
➤ Partner sites
➤ Mobile apps
➤ Third-party plugins
OAUTH 2.0
➤ OAuth is an open standard for authorization, commonly used
as a way for Internet users to authorize websites or
applications to access their information on other websites but
without giving them the passwords
➤ Standard published in October 2012
➤ Open and cross-platform
WHO USES OAUTH 2.0
➤ GitHub
➤ Google
➤ Facebook
➤ DigitalOcean
➤ etc.
HAVE YOU SEEN THESE PAGES?
OAUTH 2.0 OPEN STANDARD
https://tools.ietf.org/html/rfc6749
OAUTH 2.0 COMPONENTS
Resource Owner
Resource Server
Authorisation
Server
Client
RESOURCE OWNER
➤ Basically a user
➤ Could be technical user as well
➤ Owns resources on the resource server
CLIENT
➤ Third-party application
➤ Could be trusted or not-trusted
➤ Wants to access resources on Resource Server
AUTHORIZATION SERVER
➤ Centralised security gateway
➤ Issues access tokens
➤ Knows user credentials
RESOURCE SERVER
➤ Application expecting requests with authorised tokens
➤ There could be many resource servers
CLIENT REQUIRES
ACCESS TOKEN
TO RETRIEVE RESOURCES
AUTHORIZATION GRANT TYPES
➤ Access token is granted upon authorization
➤ There are following standard grant types:
➤ Authorization Code Grant
➤ Resource Owner Password Credentials
➤ Client Credentials
➤ Implicit Grant
http://bshaffer.github.io/oauth2-server-php-docs/overview/grant-types/
AUTHORIZATION CODE GRANT
➤ User is not entering credentials in client app, but in auth server
authorisation page
➤ Auth server redirects back to with auth code
➤ Auth code is exchanged for access token
➤ Auth code is short-lived
➤ Access token is used for requests to resource server
AUTHORISATION CODE GRANT HTTP
GET /authorize?response_type=code
&client_id=123
&scope=view_profile
&redirect_uri=https://partner.com/oauth
302 REDIRECT https://partner.com/oauth
&code=9srN6sqmjrvG5bWvNB42PCGju0TFVV
POST /token?code=9srN6sqmjrvG5bWvNB42PCGju0TFVV
&grant_type=authorization_code
&client_id=123
&redirect_uri=https://partner.com/oauth
RESOURCE OWNER PASSWORD GRANT
➤ Trusted client, has access to resource owner credentials
➤ Less secure as there is a “middleman”
➤ Could be used for subdomains in one organization
POST /authorize?grant_type=password
&username=code
&password=password
&client_id=123
&client_secret=secret
CLIENT CREDENTIALS GRANT
➤ Client is sending its own password directly
➤ Used in a situation when the client is the resource owner
➤ Again, less secure option
POST /authorize?grant_type=client_credentials
&client_id=123
&client_secret=secret
IMPLICIT GRANT
➤ Used in JavaScript front-ends
➤ Does not allow the issuance of a refresh token
➤ Requires Cross-Origin Resource Sharing (CORS)
➤ Least secure, access token is available in the client
➤ Exposure to Cross-site Request Forgery (XSRF) attack
IMPLICIT GRANT HTTP
302 REDIRECT https://partner.com/
oauth#access_token=19437jhj2781FQd44AzqT3Zg
&token_type=Bearer&expires_in=3600
GET /authorize?response_type=token
&client_id=123
&redirect_uri=https://partner.com/oauth
AUTHORIZATION TOKEN
➤ What is a token?
➤ Anything you like, really…
➤ Its important that OAuth 2.0 server can validate the token
OPEN STANDARD
https://tools.ietf.org/html/rfc6750
TOKEN RESPONSE
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"mF_9.B5f-4.1JqM",
"token_type":"Bearer",
"expires_in":3600,
“refresh_token”:”*****************”
}
TOKEN INSIDE REQUEST
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer ***************
REFRESH TOKEN
➤ Tokens should be refreshed after they have expired
➤ Optional feature
➤ Allows easier implementation of OAuth 2.0 providers
POST /token?grant_type=refresh_token
&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
SPRING IMPLEMENTATION
org.springframework.security.oauth:spring-security-oauth2
@EnableAuthorizationServer @EnableResourceServer
Authorization and Resource servers could be same or
separate applications
SPRING: AUTHORISATION SERVER
@Configuration
@EnableAuthorizationServer
class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {


public void configure(ClientDetailsServiceConfigurer clients) {

clients.inMemory()

.withClient(“client-id")

.authorizedGrantTypes("password", "refresh_token", "authorization_code")

.authorities("USER")

.scopes(“view_profile", “view_email")

.resourceIds(“user_profile”)

.secret("secret");

}
void configure(AuthorizationServerEndpointsConfigurer endpoints) {

endpoints

.tokenStore(tokenStore())

.accessTokenConverter(accessTokenConverter())

.authenticationManager(authenticationManager)

.userDetailsService(userDetailsService);

}
CLIENT CONFIGURATION
Client configuration could be in memory, jdbc
based or any other configuration
User credentials configuration could be
anywhere as well
SPRING: RESOURCE SERVER
@Configuration
@EnableResourceServer

public class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {

public void configure(ResourceServerSecurityConfigurer config) {

config

.resourceId(“user_profile)

.tokenServices(tokenServices());

}
public void configure(HttpSecurity http) {

http

.authorizeRequests()
.anyRequest().hasRole("USER")

}
RESTRICTING FUNCTIONALITY BY SCOPE
@Service
public class SecureResourceServer {
@PreAuthorize("#oauth2.hasScope('write')")
public void create(Contact contact) {
…
}
}
SPRING OAUTH 2.0 ENDPOINTS
/oauth/authorize - requests for authorisation
/oauth/token - requests for token
contains default Spring MVC authentication page, which could be customised
http://projects.spring.io/spring-security-oauth/docs/oauth2.html
TOKEN STORAGE
➤ Shared token service is required
➤ Could be in-memory or persisted
Token Storage
Authorization
Server
Resource Server
WHAT TOKENS TO USE?
➤ AtomicLong - predictable?
➤ Random numbers - clashes possible?
➤ Hash - from what?
➤ Is there any existing approach?
JSON WEB
TOKEN
Explained
JWT OPEN STANDARD
https://tools.ietf.org/html/rfc7519
JSON WEB TOKENS
➤ Send stuff between client and server securely
➤ Signed content
➤ Cross-platform
➤ Token storage is not necessary
https://jwt.io/
JWT TOKEN STRUCTURE
HEADER
PAYLOAD
SIGNATURE
HEADER
PAYLOAD
➤ Reserved claims
➤ issuer
➤ expiration time
➤ subject
➤ Public claims (named according to registry)
➤ Private claims (custom)
https://www.iana.org/assignments/jwt/jwt.xhtml
SIGNATURE
➤ JSON Web Token could be signed with
➤ Secure hash based on salt
➤ Public/private key using RSA
JWT EXAMPLE
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj
M0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRyd
WV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
BASE64 Encoded
Parts are separated by dots (.)
JWT SIMPLE FLOW
TOKEN INSIDE REQUEST
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer $JWT_TOKEN
JAVA IMPLEMENTATION
io.jsonwebtoken:jjwt
String token = Jwts.builder()
.setSubject(user.getUsername())
.setClaims([“scope” -> “user profile”])
.setIssuedAt(new Date())
.setExpiration(from(now().plus(3600)))
.setId(random(1000000))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
JWT BENEFITS
➤ Standard approach
➤ Self-contained - no need for token/session storage
➤ Passed with each request to the server
➤ Plays nice with OAuth 2.0
SPRING OAUTH 2.0 INTEGRATION
@Bean public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(SIGNING_KEY);
return converter;
}
@Bean @Primary public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setSupportRefreshToken(true);
return tokenServices;
}
org.springframework.security:spring-security-jwt
JWT AND OAUTH 2.0
➤ JWT can be used as a token in OAuth 2.0 authorisation
➤ There is no need for token storage in this case
➤ Everything works out of the box
SUMMARY
➤ OAuth 2.0 is all about information flow
➤ Interpretation is possible
➤ Extensions are available (e.g. token revocation, additional
grant types)
➤ Token could be arbitrary
➤ It is possible to use JWT tokens
REFERENCES
➤ https://oauth.net/2/
➤ http://www.bubblecode.net/en/2016/01/22/understanding-
oauth2/
➤ http://docs.oracle.com/cd/E39820_01/doc.11121/
gateway_docs/content/oauth_flows.html
➤ https://www.digitalocean.com/community/tutorials/an-
introduction-to-oauth-2

Mais conteúdo relacionado

Mais procurados

Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT ExploitationAkshaeyBhosale
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreStormpath
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0Mika Koivisto
 
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...Jorge Hidalgo
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityMohammed Fazuluddin
 
Kong API Gateway
Kong API Gateway Kong API Gateway
Kong API Gateway Chris Mague
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch APIXcat Liu
 
Introduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityIntroduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityBruno Henrique Rother
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST APIAmilaSilva13
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - IntroductionKnoldus Inc.
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 

Mais procurados (20)

Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT Exploitation
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET Core
 
OpenID Connect Explained
OpenID Connect ExplainedOpenID Connect Explained
OpenID Connect Explained
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0
 
Tomcat
TomcatTomcat
Tomcat
 
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of t...
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API Security
 
Kong API Gateway
Kong API Gateway Kong API Gateway
Kong API Gateway
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Introduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityIntroduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring Security
 
gRPC Overview
gRPC OverviewgRPC Overview
gRPC Overview
 
JSON Web Tokens
JSON Web TokensJSON Web Tokens
JSON Web Tokens
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
 
Spring Core
Spring CoreSpring Core
Spring Core
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Java script
Java scriptJava script
Java script
 

Semelhante a Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin

Accessing APIs using OAuth on the federated (WordPress) web
Accessing APIs using OAuth on the federated (WordPress) webAccessing APIs using OAuth on the federated (WordPress) web
Accessing APIs using OAuth on the federated (WordPress) webFelix Arntz
 
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...Vladimir Bychkov
 
Y U No OAuth, Using Common Patterns to Secure Your Web Applications
Y U No OAuth, Using Common Patterns to Secure Your Web ApplicationsY U No OAuth, Using Common Patterns to Secure Your Web Applications
Y U No OAuth, Using Common Patterns to Secure Your Web ApplicationsJason Robert
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesErick Belluci Tedeschi
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...iMasters
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2Rodrigo Cândido da Silva
 
OAuth and OEmbed
OAuth and OEmbedOAuth and OEmbed
OAuth and OEmbedleahculver
 
Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018MOnCloud
 
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"Andreas Falk
 
OAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring BootOAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring BootGeert Pante
 
Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Nino Ho
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015Stuart
 
Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Mads Toustrup-Lønne
 

Semelhante a Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin (20)

Accessing APIs using OAuth on the federated (WordPress) web
Accessing APIs using OAuth on the federated (WordPress) webAccessing APIs using OAuth on the federated (WordPress) web
Accessing APIs using OAuth on the federated (WordPress) web
 
Securing RESTful API
Securing RESTful APISecuring RESTful API
Securing RESTful API
 
Iam f42 a
Iam f42 aIam f42 a
Iam f42 a
 
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
 
Y U No OAuth, Using Common Patterns to Secure Your Web Applications
Y U No OAuth, Using Common Patterns to Secure Your Web ApplicationsY U No OAuth, Using Common Patterns to Secure Your Web Applications
Y U No OAuth, Using Common Patterns to Secure Your Web Applications
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within Microservices
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2
 
OAuth and OEmbed
OAuth and OEmbedOAuth and OEmbed
OAuth and OEmbed
 
Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018
 
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
 
OAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring BootOAuth2 and OpenID with Spring Boot
OAuth2 and OpenID with Spring Boot
 
Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares
 
Demystifying REST
Demystifying RESTDemystifying REST
Demystifying REST
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
 
Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
Session management
Session management  Session management
Session management
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
Full stack security
Full stack securityFull stack security
Full stack security
 

Último

Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Último (20)

Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin

  • 1. MODERN SECURITY WITH OAUTH 2.0 AND JWT AND SPRING Dmitry Buzdin 03.11.2016
  • 2.
  • 3. AGENDA ➤ Single-sign on ➤ OAuth 2.0 ➤ JSON Web Tokens ➤ Some Spring examples ➤ You will learn what is it and why you need that
  • 5. SECURITY MATTERS ➤ Every app needs security ➤ Basic security knowledge is a must ➤ Developers are ignoring security sometimes ➤ Security is based on standards - do not invent stuff!
  • 6. SINGLE SIGN-ON ➤ Accessing multiple systems with single id and password ➤ Centralised control of access rights ➤ Well known protocols ➤ LDAP ➤ Kerberos ➤ SAML 2.0 ➤ OpenID ➤ OAuth 2.0
  • 7. WHY YOU NEED SSO? ➤ Internal applications with one corporate login ➤ Integration with platform as a service ➤ Web sites with business affiliates ➤ Partner sites ➤ Mobile apps ➤ Third-party plugins
  • 8. OAUTH 2.0 ➤ OAuth is an open standard for authorization, commonly used as a way for Internet users to authorize websites or applications to access their information on other websites but without giving them the passwords ➤ Standard published in October 2012 ➤ Open and cross-platform
  • 9. WHO USES OAUTH 2.0 ➤ GitHub ➤ Google ➤ Facebook ➤ DigitalOcean ➤ etc.
  • 10. HAVE YOU SEEN THESE PAGES?
  • 11. OAUTH 2.0 OPEN STANDARD https://tools.ietf.org/html/rfc6749
  • 12. OAUTH 2.0 COMPONENTS Resource Owner Resource Server Authorisation Server Client
  • 13. RESOURCE OWNER ➤ Basically a user ➤ Could be technical user as well ➤ Owns resources on the resource server
  • 14. CLIENT ➤ Third-party application ➤ Could be trusted or not-trusted ➤ Wants to access resources on Resource Server
  • 15. AUTHORIZATION SERVER ➤ Centralised security gateway ➤ Issues access tokens ➤ Knows user credentials
  • 16. RESOURCE SERVER ➤ Application expecting requests with authorised tokens ➤ There could be many resource servers
  • 17. CLIENT REQUIRES ACCESS TOKEN TO RETRIEVE RESOURCES
  • 18. AUTHORIZATION GRANT TYPES ➤ Access token is granted upon authorization ➤ There are following standard grant types: ➤ Authorization Code Grant ➤ Resource Owner Password Credentials ➤ Client Credentials ➤ Implicit Grant http://bshaffer.github.io/oauth2-server-php-docs/overview/grant-types/
  • 19.
  • 20. AUTHORIZATION CODE GRANT ➤ User is not entering credentials in client app, but in auth server authorisation page ➤ Auth server redirects back to with auth code ➤ Auth code is exchanged for access token ➤ Auth code is short-lived ➤ Access token is used for requests to resource server
  • 21. AUTHORISATION CODE GRANT HTTP GET /authorize?response_type=code &client_id=123 &scope=view_profile &redirect_uri=https://partner.com/oauth 302 REDIRECT https://partner.com/oauth &code=9srN6sqmjrvG5bWvNB42PCGju0TFVV POST /token?code=9srN6sqmjrvG5bWvNB42PCGju0TFVV &grant_type=authorization_code &client_id=123 &redirect_uri=https://partner.com/oauth
  • 22.
  • 23. RESOURCE OWNER PASSWORD GRANT ➤ Trusted client, has access to resource owner credentials ➤ Less secure as there is a “middleman” ➤ Could be used for subdomains in one organization POST /authorize?grant_type=password &username=code &password=password &client_id=123 &client_secret=secret
  • 24.
  • 25. CLIENT CREDENTIALS GRANT ➤ Client is sending its own password directly ➤ Used in a situation when the client is the resource owner ➤ Again, less secure option POST /authorize?grant_type=client_credentials &client_id=123 &client_secret=secret
  • 26.
  • 27. IMPLICIT GRANT ➤ Used in JavaScript front-ends ➤ Does not allow the issuance of a refresh token ➤ Requires Cross-Origin Resource Sharing (CORS) ➤ Least secure, access token is available in the client ➤ Exposure to Cross-site Request Forgery (XSRF) attack
  • 28. IMPLICIT GRANT HTTP 302 REDIRECT https://partner.com/ oauth#access_token=19437jhj2781FQd44AzqT3Zg &token_type=Bearer&expires_in=3600 GET /authorize?response_type=token &client_id=123 &redirect_uri=https://partner.com/oauth
  • 29. AUTHORIZATION TOKEN ➤ What is a token? ➤ Anything you like, really… ➤ Its important that OAuth 2.0 server can validate the token
  • 31. TOKEN RESPONSE HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"mF_9.B5f-4.1JqM", "token_type":"Bearer", "expires_in":3600, “refresh_token”:”*****************” }
  • 32. TOKEN INSIDE REQUEST GET /resource HTTP/1.1 Host: server.example.com Authorization: Bearer ***************
  • 33. REFRESH TOKEN ➤ Tokens should be refreshed after they have expired ➤ Optional feature ➤ Allows easier implementation of OAuth 2.0 providers POST /token?grant_type=refresh_token &refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
  • 35. SPRING: AUTHORISATION SERVER @Configuration @EnableAuthorizationServer class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { 
 public void configure(ClientDetailsServiceConfigurer clients) {
 clients.inMemory()
 .withClient(“client-id")
 .authorizedGrantTypes("password", "refresh_token", "authorization_code")
 .authorities("USER")
 .scopes(“view_profile", “view_email")
 .resourceIds(“user_profile”)
 .secret("secret");
 } void configure(AuthorizationServerEndpointsConfigurer endpoints) {
 endpoints
 .tokenStore(tokenStore())
 .accessTokenConverter(accessTokenConverter())
 .authenticationManager(authenticationManager)
 .userDetailsService(userDetailsService);
 }
  • 36. CLIENT CONFIGURATION Client configuration could be in memory, jdbc based or any other configuration User credentials configuration could be anywhere as well
  • 37. SPRING: RESOURCE SERVER @Configuration @EnableResourceServer
 public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
 public void configure(ResourceServerSecurityConfigurer config) {
 config
 .resourceId(“user_profile)
 .tokenServices(tokenServices());
 } public void configure(HttpSecurity http) {
 http
 .authorizeRequests() .anyRequest().hasRole("USER")
 }
  • 38. RESTRICTING FUNCTIONALITY BY SCOPE @Service public class SecureResourceServer { @PreAuthorize("#oauth2.hasScope('write')") public void create(Contact contact) { … } }
  • 39. SPRING OAUTH 2.0 ENDPOINTS /oauth/authorize - requests for authorisation /oauth/token - requests for token contains default Spring MVC authentication page, which could be customised http://projects.spring.io/spring-security-oauth/docs/oauth2.html
  • 40. TOKEN STORAGE ➤ Shared token service is required ➤ Could be in-memory or persisted Token Storage Authorization Server Resource Server
  • 41. WHAT TOKENS TO USE? ➤ AtomicLong - predictable? ➤ Random numbers - clashes possible? ➤ Hash - from what? ➤ Is there any existing approach?
  • 44. JSON WEB TOKENS ➤ Send stuff between client and server securely ➤ Signed content ➤ Cross-platform ➤ Token storage is not necessary https://jwt.io/
  • 47. PAYLOAD ➤ Reserved claims ➤ issuer ➤ expiration time ➤ subject ➤ Public claims (named according to registry) ➤ Private claims (custom) https://www.iana.org/assignments/jwt/jwt.xhtml
  • 48. SIGNATURE ➤ JSON Web Token could be signed with ➤ Secure hash based on salt ➤ Public/private key using RSA
  • 51. TOKEN INSIDE REQUEST GET /resource HTTP/1.1 Host: server.example.com Authorization: Bearer $JWT_TOKEN
  • 52. JAVA IMPLEMENTATION io.jsonwebtoken:jjwt String token = Jwts.builder() .setSubject(user.getUsername()) .setClaims([“scope” -> “user profile”]) .setIssuedAt(new Date()) .setExpiration(from(now().plus(3600))) .setId(random(1000000)) .signWith(SignatureAlgorithm.HS512, secret) .compact();
  • 53. JWT BENEFITS ➤ Standard approach ➤ Self-contained - no need for token/session storage ➤ Passed with each request to the server ➤ Plays nice with OAuth 2.0
  • 54. SPRING OAUTH 2.0 INTEGRATION @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey(SIGNING_KEY); return converter; } @Bean @Primary public DefaultTokenServices tokenServices() { DefaultTokenServices tokenServices = new DefaultTokenServices(); tokenServices.setTokenStore(tokenStore()); tokenServices.setSupportRefreshToken(true); return tokenServices; } org.springframework.security:spring-security-jwt
  • 55. JWT AND OAUTH 2.0 ➤ JWT can be used as a token in OAuth 2.0 authorisation ➤ There is no need for token storage in this case ➤ Everything works out of the box
  • 56.
  • 57. SUMMARY ➤ OAuth 2.0 is all about information flow ➤ Interpretation is possible ➤ Extensions are available (e.g. token revocation, additional grant types) ➤ Token could be arbitrary ➤ It is possible to use JWT tokens
  • 58. REFERENCES ➤ https://oauth.net/2/ ➤ http://www.bubblecode.net/en/2016/01/22/understanding- oauth2/ ➤ http://docs.oracle.com/cd/E39820_01/doc.11121/ gateway_docs/content/oauth_flows.html ➤ https://www.digitalocean.com/community/tutorials/an- introduction-to-oauth-2