DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Redefining DevOps: The Transformative Power of Containerization
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers
  • Auditing Tools for Kubernetes
  • Execution Type Models in Node.js
  1. DZone
  2. Coding
  3. Frameworks
  4. JWTs With Spring Boot and Java 9

JWTs With Spring Boot and Java 9

Interested in using JWTs for your Java 9/Spring Boot projects? Learn how to set up your dependencies and the use cases for you to consider.

Sergio Martin user avatar by
Sergio Martin
·
Apr. 24, 18 · Tutorial
Like (24)
Save
Tweet
Share
32.78K Views

Join the DZone community and get the full member experience.

Join For Free

JWT (JSON Web Token) is an open source standard commonly used to transmit data between two services in a compact and secure way. This standard offers a wide range of libraries to generate JWTs and includes libraries for platforms such as .NET, Python, Node.js, Java, JavaScript, Perl, Ruby, Elixir, Golang, Groovy, and Haskell. The code is available on GitHub.

Features

  • Secure. JWTs are signed by using a secret or a public/private key pair.
  • Self-contained: all information is stored inside the JWT token. No need for further database calls.
  • Unmodifiable information, but exposed: Do not put secrets inside JWTs.
  • Compact format: JWTs are really small.

How Does It Work?

Image title

  • JWTs are sent through a URL, POST parameter or inside the header.
  • Contains a payload with information about the sender, issued date, expiration date...
  • JWTs are usually generated during the authentication phase, and once the user is logged in, the JWT previously generated allows the user to access to resources without having to make additional calls to databases.
  • They can be used to exchange information between services in a secure way, making sure that was not modified during the transmission, because the signature is calculated using the header and payload.
  • The token is storage locally or in a cookie.
  • When the user wants to use the token the convention is to add it to the header in the Authorization field using the Bearer prefix followed by the token value.
Authorization: Bearer


JSON Web Token format

JWTs are structured in three parts separated by dots:

  • Header: contains the token type (jwt) and hashing algorithm like SHA256 or RSA.
  • Payload: contains claims, which are the metadata like subjects, senders, or expiration date. There are three kinds of claims: registered, public, and private.
  • Signature: the combination of header, payload, secret, and the algorithm specified in the header. The signature ensures that nothing changed.

Therefore, the format is xxx.yyy.zzz

Java Integration

Java JWT provides all you need to generate signed tokens in a Java application.

Set Up

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

Generate JWT Token

String jwt = Jwts.builder()
    .setClaims(claims)
    .setSubject(email)
    .setIssuedAt(new Date())
    .setExpiration(new Date(System.currentTimeMillis()+ JWT_EXPIRATION_TIME))
    .signWith(SignatureAlgorithm.HS256, JWT_SECRET)
    .compact();


  • Issuer (iss): getIssuer() and setIssuer(String)
  • Subject (sub): getSubject() and setSubject(String)
  • Audience (aud): getAudience() and setAudience(String)
  • Expiration (exp): getExpiration() and setExpiration(Date)
  • Not Before (nbf): getNotBefore() and setNotBefore(Date)
  • Issued At (iat): getIssuedAt() and setIssuedAt(Date)
  • JWT ID (jti): getId() and setId(String)

All these parameters are available through Claims getters.

Verify JWT Token

final Claims claims = Jwts.parser()
    .setSigningKey(JWT_SECRET)
    .parseClaimsJws(compactJws)
    .getBody();

  • JWT_SECRET is the secret used when we generated the token.
  • compactJws is the JWT token pass in the header

If the verification fails, a SignatureException will be thrown. Otherwise, we will be able to store the metadata in a claims variable that will be available to consume later.

Troubleshooting

In case you are using Java 9, make sure you add an explicit dependency to the POM file.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
</dependency>

jaxb-api is missing in Java 9, and until jjwt adds the dependency or removes the usage of JAXB classes, we have to add it manually.

JWT (JSON Web Token) Java (programming language) Spring Framework Spring Boot

Published at DZone with permission of Sergio Martin. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Redefining DevOps: The Transformative Power of Containerization
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers
  • Auditing Tools for Kubernetes
  • Execution Type Models in Node.js

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: