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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Authentication With Remote LDAP Server in Spring Web MVC
  • Microservices With JHipster
  • Spring Reactive Microservices: A Showcase
  • Securing Spring Boot Microservices with JSON Web Tokens (JWT)

Trending

  • Why Documentation Matters More Than You Think
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Start Coding With Google Cloud Workstations
  • Segmentation Violation and How Rust Helps Overcome It
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. JSON Web Token: Security for Applications

JSON Web Token: Security for Applications

Rafael Salerno dissects the components of the JSON Web Token and walks through an example of how to authenticate a user to access an API server.

By 
Rafael Salerno user avatar
Rafael Salerno
·
Feb. 07, 17 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free

JSON Web Token, or 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. 

Each piece of information can be verified and trusted because it is digitally signed. 

JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

Some important concepts:

  • Compact: JWTs can be sent through a URL, POST parameter, or inside an HTTP header. 
  • Self-contained: The payload contains all the required information about the user, avoiding the need to query the database more than once.

When you should use JSON Web Tokens:

  • 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. 
  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties, because as they can be signed, for example using public/private key pairs, you can be sure that the senders are who they say they are. 

JWT Structure

A complete JWT is represented something like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5MaMo

This token could be sliced in 3 parts:

Header

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.

Payload

eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.

Signature

uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5MaMo

Each part is separated by “.” 

<base64url-encoded header>.<base64url-encoded claims>.<base64url-encoded signature>

Here one simple sample of the flow to authentication of User to access a API Server.

I did two samples with JWT, first with main method call some others method to create token and another with Spring Boot call some rest operations.

First Example

dependency:
compile'io.jsonwebtoken:jjwt:0.7.0'


package com.example;

import java.security.Key;
import javax.crypto.SecretKey;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;

public class PocAutorizationApplication {

	private final String key =  "teste";

	public static void main(String[] args) {
		PocAutorizationApplication poc = new PocAutorizationApplication();
		poc.desCompactJws(poc.compactJws(new User("user", "password").toString()));

	}

	public String compactJws(String user) {
		String compactJws = Jwts.builder()
		.setSubject(user)
		.signWith(SignatureAlgorithm.HS512, key)
		.compact();

		System.out.println("compactJws = "+compactJws);

		return compactJws;
	}

	public String desCompactJws(String compactJws) {
		String desCompactJws = Jwts.parser()
		.setSigningKey(key)
		.parseClaimsJws(compactJws)
		.getBody()
		.getSubject();

		System.out.println("desCompactJws = "+ desCompactJws);

		return desCompactJws;
	}
}    

Complete example

The second sample is a POC with JWT and Spring Boot, where I created some filters to check token on Header and I put some validations to Token. (I put just importants code parts)

dependencies {
	compile('org.springframework.boot:spring-boot-starter-web')
	compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.2'
	compile 'io.jsonwebtoken:jjwt:0.7.0'
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

Operations

  • Login return Token and put Token in Header

  • User get use and pass by Header and decompact token

  • Validation is check if Token is valid

  • Users is to list users avaliable

@RestController
public class UserService {

	@Autowired
	private Authentication authentication;

	@Autowired
	private UserBuilder userBuilder;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletResponse response,@RequestBody User user) throws IOException {
		System.out.println(user);
		String token = authentication.compactJws(new ObjectMapper().writeValueAsString(user));
		response.setHeader("X-Auth-Token", token);

		return token ;
	}

	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public String user(HttpServletRequest request) throws IOException {
		System.out.println(request.getHeader("X-Auth-Token"));
		return authentication.desCompactJws(request.getHeader("X-Auth-Token"));
	}

	@RequestMapping(value = "/validation/token", method = RequestMethod.POST)
	public boolean validationToken(HttpServletRequest request) throws IOException {
		return true;
	}

	@RequestMapping(value = "/users", method = RequestMethod.POST)
	public List<User> listUsers(HttpServletRequest request,HttpServletResponse response) throws Exception {
		return userBuilder.users;
	}
}

Class to compact and decompact.

@Component
public class Authentication {

	private final String key = "teste";
	private final int TEMPO_MAX_SESSAO=10;

	public String compactJws(String user) {
		String compactJws = Jwts.builder()
		.setSubject(user)
		.signWith(SignatureAlgorithm.HS512, key)
		.compact();

		System.out.println("compactJws = " + compactJws);

		return compactJws;
	}

	public String desCompactJws(String compactJws) {
		String desCompactJws = "";
		try{
			desCompactJws = Jwts.parser()
			.setSigningKey(key)
			.parseClaimsJws(compactJws)
			.getBody()
			.getSubject();

			System.out.println("desCompactJws = " + desCompactJws);

		}
	catch (MalformedJwtException e) {
		return "Invalid Token";
	}
	return desCompactJws;
	}
}

Filter class to check if operation is different from login, should check if contains token in header and user/password are valid.

@Component
public class AuthFilter implements Filter{

	@Autowired
	private Authentication authentication;

	@Autowired
	private UserBuilder userBuilder;

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		if(request.getRequestURI().contains("login")) {
			chain.doFilter(request, response);
			return;
		}
	try {

		if(getToken(request.getHeader("X-Auth-Token"))){
			response.setHeader("X-Auth-Token", request.getHeader("X-Auth-Token"));
			chain.doFilter(request, response);
			return;
		}

		response.sendError(HttpStatus.UNAUTHORIZED.value());
	} 
   			catch (Exception e) {
			e.printStackTrace();
			response.sendError(HttpStatus.UNAUTHORIZED.value());
		}
	}

	private boolean getToken(String token) throws Exception{
		if(token != null && !token.isEmpty() && validationToken(token))
		return true; 

		return false;
	}

	private boolean validationToken(String token) throws JsonParseException, JsonMappingException, IOException {
		String user = authentication.desCompactJws(token);

		if(user.equals("Invalid Token")) return false;

		User out =  new ObjectMapper().readValue(user, User.class);

		Optional<User> userValid = userBuilder.users.stream().
		filter(x-> x.getUser().equals(out.getUser())&& x.getPass().equals(out.getPass()))
		.findFirst();

		return userValid.isPresent();
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

}

Here is the complete example with Spring Boot and JWT.

JSON Web Service Spring Framework JWT (JSON Web Token) application security

Opinions expressed by DZone contributors are their own.

Related

  • Authentication With Remote LDAP Server in Spring Web MVC
  • Microservices With JHipster
  • Spring Reactive Microservices: A Showcase
  • Securing Spring Boot Microservices with JSON Web Tokens (JWT)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!