SlideShare a Scribd company logo
JSON WEB TOKENS
+
SPRING SECURITY
Why should we use JWT and how
Bruno H. Rother
What is JSON Web
Token ?
What is JSON Web Token?
u JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact
and self-contained way for securely transmitting information between parties
as a JSON object
u This information can be verified and trusted because it is digitally signed.
u JWTs can be signed using a secret (with the HMAC algorithm) or a
public/private key pair using RSA.
What is JSON Web Token?
u Compact: Because of their smaller size, JWTs can be sent through a URL,
POST parameter, or inside an HTTP header. Additionally, the smaller size
means transmission is fast.
Ex:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpva
G4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
u Self-contained: The payload contains all the required information about the
user, avoiding the need to query the database more than once.
When should you use JSON Web Tokens?
u Authentication: This is the most common scenario for using JWT. Once the
user is logged in, each subsequent request will include the JWT, allowing the
user to access routes, services, and resources that are permitted with that
token. Single Sign On is a feature that widely uses JWT nowadays, because of
its small overhead and its ability to be easily used across different domains.
u Information Exchange: JSON Web Tokens are a good way of securely
transmitting information between parties. Because JWTs can be signed—for
example, using public/private key pairs—you can be sure the senders are who
they say they are.
What is the JSON Web Token structure?
u JSON Web Tokens consist of three parts separated by dots (.), which are:
u Header
u Payload
u Signature
Therefore, a JWT typically looks like the following.
u xxxxx.yyyyy.zzzzz
What is the JSON Web Token structure?
Header
The header typically consists of two parts: the type of the token, which is JWT,
and the hashing algorithm being used, such as HMAC SHA256 or RSA.
u For example:
u Then, this JSON is Base64Url encoded to form the first part of the JWT.
What is the JSON Web Token structure?
Payload
The second part of the token is the payload, which contains the claims.
Claims are statements about an entity (typically, the user) and additional
metadata. There are three types of claims:
u reserved
u public
u private
What is the JSON Web Token structure?
Payload
u Reserved claims
These are a set of predefined claims which are not mandatory but recommended, to
provide a set of useful, interoperable claims. Some of them
are: iss (issuer), exp (expiration time), sub(subject), aud (audience), and others.
Notice that the claim names are only three characters long as JWT is meant to be
compact.
What is the JSON Web Token structure?
Payload
u Public claims
These can be defined at will by those using JWTs. But to avoid collisions they should
be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a
collision resistant namespace.
What is the JSON Web Token structure?
Payload
u Private claims
These are the custom claims created to share information between parties that agree
on using them.
What is the JSON Web Token structure?
Payload
u Example
The payload is then Base64Url encoded to form the second part of the JSON Web
Token.
What is the JSON Web Token structure?
Signature
To create the signature part you have to take the encoded header, the encoded
payload, a secret, the algorithm specified in the header, and sign that.
u The signature is used to verify that the sender of the JWT is who it says it is
and to ensure that the message wasn't changed along the way.
u For example if you want to use the HMAC SHA256 algorithm, the signature will
be created in the following way:
Putting all together
The output is three Base64 strings separated by dots that can be easily passed in HTML and
HTTP environments, while being more compact when compared to XML-based standards
such as SAML.
The following shows a JWT that has the previous header and payload encoded, and it is
signed with a secret.
What is the JSON Web Token structure?
u Jwt.io
It is a web page where you can learn
more about JWT and debug a token.
You can also verify the signature.
And download the libraries for
different languages as:
Java, JS, Node.js, Python, .NET, etc.
How to test and see my JWT?
How do JSON Web Tokens work?
u In authentication, when the user successfully logs in using their credentials, a
JSON Web Token will be returned and must be saved locally (typically in local
storage, but cookies can be also used).
u Whenever the user wants to access a protected route or resource, the user
agent should send the JWT, typically in the Authorization header using
the Bearer schema. The content of the header should look like the following:
u This is a stateless authentication mechanism as the user state is never saved
in server memory. The server's protected routes will check for a valid JWT in
the Authorization header, and if it's present, the user will be allowed to
access protected resources. As JWTs are self-contained, all the necessary
information is there, reducing the need to query the database multiple times.
How do JSON Web Tokens work?
u This allows you to fully rely on data APIs that are stateless and even make
requests to downstream services. It doesn't matter which domains are serving
your APIs, so Cross-Origin Resource Sharing (CORS) won't be an issue as it
doesn't use cookies.
JWT Signature and Encryption
u A JWT is usually complemented with a signature or encryption. These are
handled in their own specs as JSON Web Signature (JWS) and JSON Web
Encryption (JWE).
u A signature allows a JWT to be validated against modifications. Encryption, on
the other hand, makes sure the content of the JWT is only readable by
certain parties.
Common JWT Signing Algorithms
u Most JWTs in the wild are just signed. The most common algorithms are:
u HMAC + SHA256
u RSASSA-PKCS1-v1_5 + SHA256
u ECDSA + P-256 + SHA256
The specs defines many more algorithms for signing. You can find them all in RFC 7518.
Common JWT Signing Algorithms
HMAC algorithms
This is probably the most common algorithm for signed JWTs.
u Hash-Based Message Authentication Codes (HMACs) are a group of algorithms
that provide a way of signing messages by means of a shared key. In the case of
HMACs, a cryptographic hash function is used (for instance SHA256).
u The strength (i.e. how hard it is to forge an HMAC) depends on the hashing
algorithm being used.
u The main objective in the design of the algorithm was to allow the combination
of a key with a message while providing strong guarantees against tampering.
Common JWT Signing Algorithms
HMAC algorithms
u HMACs are used with JWTs when you want a simple way for all parties to create
and validate JWTs. Any party knowing the key can create new JWTs. In other
words, with shared keys, it is possible for party to impersonate another one:
HMAC JWTs do not provide guarantees with regards to the creator of the JWT.
Anyone knowing the key can create one.
u For certain use cases, this is too permissive. This is where asymmetric
algorithms come into play.
Common JWT Signing Algorithms
RSA and ECDSA algorithms
u Both RSA and ECDSA are asymmetric encryption and digital signature algorithms.
u What asymmetric algorithms bring to the table is the possibility of verifying or
decrypting a message without being able to create a new one.
u This is key for certain use cases.
Common JWT Signing Algorithms
RSA and ECDSA algorithms
u Example: Picture a big company where data generated by the sales team needs
to be verified by the accounting team.
u If an HMAC were to be used to sign the data, then both the sales team and the
accounting team would need to know the same key.
u This would allow the sales team to sign data and make it pass as if it were from the
accounting team.
u Although this might seem unlikely, especially in the context of a corporation,
there are times when the ability to verify the creator of a signature is essential.
Common JWT Signing Algorithms
RSA and ECDSA algorithms
u The main difference between RSA and ECDSA lies in speed and key size.
u ECDSA requires smaller keys to achieve the same level of security as RSA. This makes
it a great choice for small JWTs once is faster generating keys and signatures..
u RSA, however, is usually faster than ECDSA for signature verification.
u As usual, pick the one that best aligns with your requirements.
Conclusion
JWTs are a convenient way of representing authentication and authorization claims
for your application.
u They are easy to parse, human readable and compact. But the killer features are in
the JWS and JWE specs.
u With JWS and JWE all claims can be conveniently signed and encrypted, while
remaining compact enough to be part of every API call
u Solutions such as session-ids and server-side tokens seem old and cumbersome
when compared to the power of JWTs.
Spring Security
What is the Spring Security ?
u Spring Security is a framework that focuses on providing both authentication
and authorization to Java applications.
u Like all Spring projects, the real power of Spring Security is found in how
easily it can be extended to meet custom requirements.
u Features:
u Comprehensive and extensible support for both Authentication and Authorization
u Protection against attacks like session fixation, clickjacking, cross site request
forgery, etc.
u Servlet API integration
u Optional integration with Spring Web MVC
u Much more…
Fundamentals
u Principal
u User that performs the action
u Authentication
u Confirming truth of credentials
u Authorization
u Define access policy for principal
u GrantedAuthority
u Application-wide permissions granted to a principal
u SecurityContext
u Hold the Authentication and other security information
u SecurityContextHolder
u Provide access to SecurityContext
SecurityContextHolder
u Provide access to SecurityContext
u Strategies
u ThreadLocal – only read/write in the same thread
u Global
Use Case
Basic filters
Authentication
u Variants
u Credential-based
u Two-factor or 2FA
u Hardware
u Mechanisms
u Basic
u Form
u Storage
u RDBMS (Relational database managementsystem)
u LDAP
u Custom Storage
Core Authentication service
u AuthenticationManager
u Handles authentication requests
u AuthenticationProvider
u Performs authentication
u UserDetailsService
u Responsible for returning an UserDetails object
u UserDetails
u Provides the core user information
AuthenticationManager
AuthenticationProvider
UserDetailsService
UserDetails
How to configure the Spring Security?
u The first step is to secure some routes of our application.
u For this demo we will expose the routes:
u / and /login -> to everyone
u /users -> to people whom can provide a valid JWT token.
u
u
u
Once we have updated
the pom.xml file and
imported the new
dependencies, we are ready
to start securing our routes.
Ex: Maven Configuration
How to configure the Spring Security?
u First of all, we want to avoid exposing /users to everyone, so we will create a
configuration that restricts its access.
u We will accomplish this by adding a new class called WebSecurityConfig that
extends the WebSecurityConfigurerAdapter class from Spring Security.
How to configure the Spring Security?
u Here, we are specifying that
/ and /login are permitAll().
u All other requests are
authenticated and:
u We are filtering login to add
before the filter of users
u Any other endpoint, check
the present of the JWT
Token
How to configure the Spring Security?
u We also configure from WHERE we are getting the users, where are 2 options:
u inMemoryAuthentication() – Username and password pre-defined (good for tests).
u userDetailsService() – You can declare a Service class to authenticate/authorize.
Needs to implement UserDetailsService interface.
Custom UserService
What about securing REST applications?
u The previous examples were normally for web applications, where you
redirect pages, login using page, etc. In REST, we don’t have:
u Login page
u Page to redirect after login
u Page to redirect in failure or unauthorized
u Solution:
u Override AuthenticationFailureHandler to return 401
u Override AuthenticationSuccessHandler to return the JSON object / token.
u Override AuthenticationEntryPoint to always return 401.
u Override LogoutSuccessHandler to return 200.
Overriding the AuthenticationEntryPoint
u Class extends org.springframework.security.web.AuthenticationEntryPoint,
and implements only one method, which sends response error (with 401 status
code) in cause of unauthorized attempt.
Overriding the AuthenticationSuccessHandler
u The AuthenticationSuccessHandler is responsible of what to do after a
successful authentication, by default it will redirect to an URL, but in our
case we want it to send an HTTP response with data.
Overriding the AuthenticationFailureHandler
u The AuthenticationFaillureHandler is responsible of what to after a failed
authentication, by default it will redirect to the login page URL, but in our
case we just want it to send an HTTP response with the 401 UNAUTHORIZED
code.
Spring Security
+
JWT
What do we need?
u Filter to intercept the calls, read the token and authenticate.
u Authentication Provider responsible for returning the user.
u Handlers for
u AuthenticationFailure
u AuthenticationSuccess
u EntryPoint
DEMO
https://github.com/BHRother/spring-boot-security-jwt
How JWT can help ?
u Some Challenges:
u Using asymmetric signature.
u Manage the keys
u If token contains personal information, encrypt before generate the token.
About Me
Thank You !

More Related Content

What's hot (20)

PPTX
Understanding JWT Exploitation
AkshaeyBhosale
 
PPTX
Pentesting jwt
Jaya Kumar Kondapalli
 
PDF
Using JSON Web Tokens for REST Authentication
Mediacurrent
 
PDF
Json web token
Mayank Patel
 
PDF
Jwt Security
Seid Yassin
 
PDF
JSON Web Token
Deddy Setyadi
 
PDF
Spring Security
Knoldus Inc.
 
PDF
JSON Web Tokens
Ivan Rosolen
 
PDF
[OPD 2019] Attacking JWT tokens
OWASP
 
PPTX
Rest API Security
Stormpath
 
PDF
REST APIs with Spring
Joshua Long
 
PPTX
Injection flaws
DANISH INAMDAR
 
PPTX
Spring Boot and REST API
07.pallav
 
PDF
Exception handling
Anna Pietras
 
PDF
OAuth2 and Spring Security
Orest Ivasiv
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PDF
Modern API Security with JSON Web Tokens
Jonathan LeBlanc
 
PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
ODP
Spring User Guide
Muthuselvam RS
 
PDF
Applications secure by default
SecuRing
 
Understanding JWT Exploitation
AkshaeyBhosale
 
Pentesting jwt
Jaya Kumar Kondapalli
 
Using JSON Web Tokens for REST Authentication
Mediacurrent
 
Json web token
Mayank Patel
 
Jwt Security
Seid Yassin
 
JSON Web Token
Deddy Setyadi
 
Spring Security
Knoldus Inc.
 
JSON Web Tokens
Ivan Rosolen
 
[OPD 2019] Attacking JWT tokens
OWASP
 
Rest API Security
Stormpath
 
REST APIs with Spring
Joshua Long
 
Injection flaws
DANISH INAMDAR
 
Spring Boot and REST API
07.pallav
 
Exception handling
Anna Pietras
 
OAuth2 and Spring Security
Orest Ivasiv
 
Spring boot jpa
Hamid Ghorbani
 
Modern API Security with JSON Web Tokens
Jonathan LeBlanc
 
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring User Guide
Muthuselvam RS
 
Applications secure by default
SecuRing
 

Similar to Introduction to JWT and How to integrate with Spring Security (20)

PDF
Landscape
Amit Gupta
 
PDF
Landscape
Amit Gupta
 
PPTX
Json web tokens
ElieHannouch
 
PDF
5 easy steps to understanding json web tokens (jwt)
Amit Gupta
 
PPTX
JsonWebTokens ppt - explains JWT, JWS , JWE Tokens
nagarajapallafl
 
PPTX
JWT_Presentation to show how jwt is better then session based authorization
nathakash343
 
PDF
Jwt the complete guide to json web tokens
remayssat
 
PPTX
jwt.pptx
Maleerat Maliyaem
 
PDF
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
iMasters
 
PPTX
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
SohailCreation
 
PDF
Autenticação com Json Web Token (JWT)
Ivan Rosolen
 
PDF
JSON Web Tokens Will Improve Your Life
John Anderson
 
PDF
Jwt, wtf? - Phil Nash - Codemotion Amsterdam 2017
Codemotion
 
PPTX
JWTs and JOSE in a flash
Evan J Johnson (Not a CISSP)
 
PPTX
Uniface Lectures Webinar - Application & Infrastructure Security - JSON Web T...
Uniface
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Luciano Mammino
 
PDF
What are JSON Web Tokens and Why Should I Care?
Derek Edwards
 
PDF
Jwt with flask slide deck - alan swenson
Jeffrey Clark
 
Landscape
Amit Gupta
 
Landscape
Amit Gupta
 
Json web tokens
ElieHannouch
 
5 easy steps to understanding json web tokens (jwt)
Amit Gupta
 
JsonWebTokens ppt - explains JWT, JWS , JWE Tokens
nagarajapallafl
 
JWT_Presentation to show how jwt is better then session based authorization
nathakash343
 
Jwt the complete guide to json web tokens
remayssat
 
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
iMasters
 
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
SohailCreation
 
Autenticação com Json Web Token (JWT)
Ivan Rosolen
 
JSON Web Tokens Will Improve Your Life
John Anderson
 
Jwt, wtf? - Phil Nash - Codemotion Amsterdam 2017
Codemotion
 
JWTs and JOSE in a flash
Evan J Johnson (Not a CISSP)
 
Uniface Lectures Webinar - Application & Infrastructure Security - JSON Web T...
Uniface
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Luciano Mammino
 
What are JSON Web Tokens and Why Should I Care?
Derek Edwards
 
Jwt with flask slide deck - alan swenson
Jeffrey Clark
 
Ad

Recently uploaded (20)

PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Ad

Introduction to JWT and How to integrate with Spring Security

  • 1. JSON WEB TOKENS + SPRING SECURITY Why should we use JWT and how Bruno H. Rother
  • 2. What is JSON Web Token ?
  • 3. What is JSON Web Token? u JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object u This information can be verified and trusted because it is digitally signed. u JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.
  • 4. What is JSON Web Token? u Compact: Because of their smaller size, JWTs can be sent through a URL, POST parameter, or inside an HTTP header. Additionally, the smaller size means transmission is fast. Ex: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpva G4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ u Self-contained: The payload contains all the required information about the user, avoiding the need to query the database more than once.
  • 5. When should you use JSON Web Tokens? u Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains. u Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are.
  • 6. What is the JSON Web Token structure? u JSON Web Tokens consist of three parts separated by dots (.), which are: u Header u Payload u Signature Therefore, a JWT typically looks like the following. u xxxxx.yyyyy.zzzzz
  • 7. What is the JSON Web Token structure? Header The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA. u For example: u Then, this JSON is Base64Url encoded to form the first part of the JWT.
  • 8. What is the JSON Web Token structure? Payload The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. There are three types of claims: u reserved u public u private
  • 9. What is the JSON Web Token structure? Payload u Reserved claims These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub(subject), aud (audience), and others. Notice that the claim names are only three characters long as JWT is meant to be compact.
  • 10. What is the JSON Web Token structure? Payload u Public claims These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.
  • 11. What is the JSON Web Token structure? Payload u Private claims These are the custom claims created to share information between parties that agree on using them.
  • 12. What is the JSON Web Token structure? Payload u Example The payload is then Base64Url encoded to form the second part of the JSON Web Token.
  • 13. What is the JSON Web Token structure? Signature To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. u The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way. u For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
  • 14. Putting all together The output is three Base64 strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML. The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret. What is the JSON Web Token structure?
  • 15. u Jwt.io It is a web page where you can learn more about JWT and debug a token. You can also verify the signature. And download the libraries for different languages as: Java, JS, Node.js, Python, .NET, etc. How to test and see my JWT?
  • 16. How do JSON Web Tokens work? u In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used). u Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following: u This is a stateless authentication mechanism as the user state is never saved in server memory. The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources. As JWTs are self-contained, all the necessary information is there, reducing the need to query the database multiple times.
  • 17. How do JSON Web Tokens work? u This allows you to fully rely on data APIs that are stateless and even make requests to downstream services. It doesn't matter which domains are serving your APIs, so Cross-Origin Resource Sharing (CORS) won't be an issue as it doesn't use cookies.
  • 18. JWT Signature and Encryption u A JWT is usually complemented with a signature or encryption. These are handled in their own specs as JSON Web Signature (JWS) and JSON Web Encryption (JWE). u A signature allows a JWT to be validated against modifications. Encryption, on the other hand, makes sure the content of the JWT is only readable by certain parties.
  • 19. Common JWT Signing Algorithms u Most JWTs in the wild are just signed. The most common algorithms are: u HMAC + SHA256 u RSASSA-PKCS1-v1_5 + SHA256 u ECDSA + P-256 + SHA256 The specs defines many more algorithms for signing. You can find them all in RFC 7518.
  • 20. Common JWT Signing Algorithms HMAC algorithms This is probably the most common algorithm for signed JWTs. u Hash-Based Message Authentication Codes (HMACs) are a group of algorithms that provide a way of signing messages by means of a shared key. In the case of HMACs, a cryptographic hash function is used (for instance SHA256). u The strength (i.e. how hard it is to forge an HMAC) depends on the hashing algorithm being used. u The main objective in the design of the algorithm was to allow the combination of a key with a message while providing strong guarantees against tampering.
  • 21. Common JWT Signing Algorithms HMAC algorithms u HMACs are used with JWTs when you want a simple way for all parties to create and validate JWTs. Any party knowing the key can create new JWTs. In other words, with shared keys, it is possible for party to impersonate another one: HMAC JWTs do not provide guarantees with regards to the creator of the JWT. Anyone knowing the key can create one. u For certain use cases, this is too permissive. This is where asymmetric algorithms come into play.
  • 22. Common JWT Signing Algorithms RSA and ECDSA algorithms u Both RSA and ECDSA are asymmetric encryption and digital signature algorithms. u What asymmetric algorithms bring to the table is the possibility of verifying or decrypting a message without being able to create a new one. u This is key for certain use cases.
  • 23. Common JWT Signing Algorithms RSA and ECDSA algorithms u Example: Picture a big company where data generated by the sales team needs to be verified by the accounting team. u If an HMAC were to be used to sign the data, then both the sales team and the accounting team would need to know the same key. u This would allow the sales team to sign data and make it pass as if it were from the accounting team. u Although this might seem unlikely, especially in the context of a corporation, there are times when the ability to verify the creator of a signature is essential.
  • 24. Common JWT Signing Algorithms RSA and ECDSA algorithms u The main difference between RSA and ECDSA lies in speed and key size. u ECDSA requires smaller keys to achieve the same level of security as RSA. This makes it a great choice for small JWTs once is faster generating keys and signatures.. u RSA, however, is usually faster than ECDSA for signature verification. u As usual, pick the one that best aligns with your requirements.
  • 25. Conclusion JWTs are a convenient way of representing authentication and authorization claims for your application. u They are easy to parse, human readable and compact. But the killer features are in the JWS and JWE specs. u With JWS and JWE all claims can be conveniently signed and encrypted, while remaining compact enough to be part of every API call u Solutions such as session-ids and server-side tokens seem old and cumbersome when compared to the power of JWTs.
  • 27. What is the Spring Security ? u Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. u Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. u Features: u Comprehensive and extensible support for both Authentication and Authorization u Protection against attacks like session fixation, clickjacking, cross site request forgery, etc. u Servlet API integration u Optional integration with Spring Web MVC u Much more…
  • 28. Fundamentals u Principal u User that performs the action u Authentication u Confirming truth of credentials u Authorization u Define access policy for principal u GrantedAuthority u Application-wide permissions granted to a principal u SecurityContext u Hold the Authentication and other security information u SecurityContextHolder u Provide access to SecurityContext
  • 29. SecurityContextHolder u Provide access to SecurityContext u Strategies u ThreadLocal – only read/write in the same thread u Global
  • 32. Authentication u Variants u Credential-based u Two-factor or 2FA u Hardware u Mechanisms u Basic u Form u Storage u RDBMS (Relational database managementsystem) u LDAP u Custom Storage
  • 33. Core Authentication service u AuthenticationManager u Handles authentication requests u AuthenticationProvider u Performs authentication u UserDetailsService u Responsible for returning an UserDetails object u UserDetails u Provides the core user information
  • 38. How to configure the Spring Security? u The first step is to secure some routes of our application. u For this demo we will expose the routes: u / and /login -> to everyone u /users -> to people whom can provide a valid JWT token. u u u Once we have updated the pom.xml file and imported the new dependencies, we are ready to start securing our routes. Ex: Maven Configuration
  • 39. How to configure the Spring Security? u First of all, we want to avoid exposing /users to everyone, so we will create a configuration that restricts its access. u We will accomplish this by adding a new class called WebSecurityConfig that extends the WebSecurityConfigurerAdapter class from Spring Security.
  • 40. How to configure the Spring Security? u Here, we are specifying that / and /login are permitAll(). u All other requests are authenticated and: u We are filtering login to add before the filter of users u Any other endpoint, check the present of the JWT Token
  • 41. How to configure the Spring Security? u We also configure from WHERE we are getting the users, where are 2 options: u inMemoryAuthentication() – Username and password pre-defined (good for tests). u userDetailsService() – You can declare a Service class to authenticate/authorize. Needs to implement UserDetailsService interface.
  • 43. What about securing REST applications? u The previous examples were normally for web applications, where you redirect pages, login using page, etc. In REST, we don’t have: u Login page u Page to redirect after login u Page to redirect in failure or unauthorized u Solution: u Override AuthenticationFailureHandler to return 401 u Override AuthenticationSuccessHandler to return the JSON object / token. u Override AuthenticationEntryPoint to always return 401. u Override LogoutSuccessHandler to return 200.
  • 44. Overriding the AuthenticationEntryPoint u Class extends org.springframework.security.web.AuthenticationEntryPoint, and implements only one method, which sends response error (with 401 status code) in cause of unauthorized attempt.
  • 45. Overriding the AuthenticationSuccessHandler u The AuthenticationSuccessHandler is responsible of what to do after a successful authentication, by default it will redirect to an URL, but in our case we want it to send an HTTP response with data.
  • 46. Overriding the AuthenticationFailureHandler u The AuthenticationFaillureHandler is responsible of what to after a failed authentication, by default it will redirect to the login page URL, but in our case we just want it to send an HTTP response with the 401 UNAUTHORIZED code.
  • 48. What do we need? u Filter to intercept the calls, read the token and authenticate. u Authentication Provider responsible for returning the user. u Handlers for u AuthenticationFailure u AuthenticationSuccess u EntryPoint
  • 50. How JWT can help ? u Some Challenges: u Using asymmetric signature. u Manage the keys u If token contains personal information, encrypt before generate the token.