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

Rafael Salerno user avatar by
Rafael Salerno
·
Feb. 07, 17 · Tutorial
Like (7)
Save
Tweet
Share
8.12K 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.

Popular on DZone

  • How To Check Docker Images for Vulnerabilities
  • A Brief Overview of the Spring Cloud Framework
  • API Design Patterns Review
  • How Observability Is Redefining Developer Roles

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
  • +1 (919) 678-0300

Let's be friends: