JWT Authentication using Auth0 Library

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Token is nothing but an encrypted string, server has the secure key and using that it signs a user data and sends it to client. Once the user is authenticated, a token will be issued to the client. Client will be sending the token in subsequent API. Since server holds the key, it can only verify the signature. 

Token mechanism exist before JWT and how JWT different from traditional way of generating token ?

JWT provides a standard mechanism to authenticate the user. In cloud environment, micro services are distributed across the cluster. Each service requires some mechanism to authenticate. JWT provides a standard. The JWT token has 3 parts,

  1. Algortithm (header)
  2. User data (payload)
  3. Signature

We have used Auth0 library to generate and validate JWT token.

<dependency>
   <groupId>com.auth0</groupId>
   <artifactId>java-jwt</artifactId>
   <version>3.4.0</version>
</dependency>

Below code helps to generate JWT token. Token generated will have a expiry of 1 hour. If it is used beyond 1 hour then server will reject the request.

public static void generateToken() {

   try {

           Algorithm algorithm = Algorithm.HMAC512("secret-key");

           Calendar cal = Calendar.getInstance();
           cal.add(Calendar.HOUR, 1);

           String token = JWT.create()
                             .withSubject("secure-login")
                             .withClaim("Name", "Best open source")
                             .withClaim("Role", "Admin")
                             .withIssuer("App-1")
                             .withExpiresAt(cal.getTime())
                             .sign(algorithm);

          System.out.println(token);
   }
   catch(Exception exp) {
        System.out.println(exp.getMessage());
   }
}

Now the token is generated. In Rest API, client will send the token as part of Authorization Header. Server will valiadate the token before processing the API.

Below code is helps to validate the token.

public static void verifyToken(String token) {

try {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);

     Algorithm algorithm = Algorithm.HMAC512("secret-key");

     JWTVerifier verifier = JWT.require(algorithm)
                               .acceptExpiresAt(60)
.acceptNotBefore(cal.getTimeInMillis())
                               .build();

     DecodedJWT decodedJwt = verifier.verify(token);
     System.out.println(decodedJwt.getClaim("Name").asString());
  }
  catch(Exception exp) {
    System.out.println(exp.getMessage());
  }
}

JWT.io provides an user interface to validate the token.

References:

https://jwt.io/

https://github.com/auth0/java-jwt

https://www.findbestopensource.com/tagged/jwt-library

 


   

We publish blog post about open source products. If you are interested in sharing knowledge about open source products, please visit write for us

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


Angular Security - Authentication Service

  • angular security authentication jwt

Angular is a framework for creating single page web application. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Caching using Ehcache Java Library

  • ehcache cache java map key-value

Ehcache from Terracotta is one of Java's most widely used Cache. It is concurrent and highly scalable. It has small footprint with SL4J as the only dependencies. It supports multiple strategies like Expiration policies, Eviction policies. It supports three storage tiers, heap, off-heap, disk storage. There are very few caching products supports multiple tier storage. If you want to scale, you cannot store all items in heap there should be support for off-heap and disk storage. Ehcache is licensed under Apache 2.0. In this article, we can see about basic usage of Ehcache.

Read More


Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More



Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More


Restrict Solr Admin Access

  • solr searchengine tips

Solr is a search engine built on top of Lucene. It supports REST interface and has lot of built-in capabilities. Solr package has Admin UI interface which has support to perform query and even delete the contents of the index. If you are using Solr in production then you may need to restrict access. I saw couple of questions in the group related to this topic. Thought to write an article explaining few tips to restrict the user access to Solr admin UI.

Read More


mkcert - No config certificate authority tool

  • certificate ssl security cert go go-lang

Mkcert is go-lang project, which is super easy tool to setup certificate authority without any configuration. Using certificates are inevitable these days, data should be transferred in a secure communication channel. Buying a certificate is expensive and mostly companies buy certificates only for production systems. In Dev setup, if we use self-signed certificate then there will be trust errors. mkcert automatically creates and installs a local CA in the system root store, and generates locally-trusted certificates.

Read More


Electron JS- Native capabilities

  • electronjs electron desktop-app

Electron is an open source library to build native applications which also works as cross-platform desktop applications. It provision operating system functionalities with help of node integration. In this article, we will go through how to access the Operating System variables, Inter system communication, System dialog, Access files, folders also their statistics.

Read More


Holistic usage guide for OpenSSL

  • openssl security certificate tools

OpenSSL is a general purpose cryptographty toolkit that provides an open source implementation of Transport Layer Security(TLS) and Secure Socket Layer(SSL) protocols. It is written in C,assembly and Perl language but wrappers are available in all languages. This article explains about OpenSSL commands.

Read More


Struts 1.x End Of Life. Whats alternative?

  • java eol struts

The Apache Struts Project Team announced End of Life (EOL) for Struts 1.x web framework. Struts was launched in the year 2000. It is only of the widely used web framework. It gave better control over writing UI and business logic code directly in to JSPs.

Read More


Appserver.io – The First Multithreaded Application Server for PHP written in PHP

  • appserver application-server php

What if you could reliably run PHP without Nginx or Apache, but also without relying on its internal server? What if you could do async operations in PHP with true multi threading, fully taking advantage of multi core processors without hacks or a jungle of callbacks? What if you had drag and drop installation support for your PHAR packaged web apps in an environment identical to its production counterpart? Welcome to appserver.io – the worlds first open source application server for PHP.

Read More


Understanding Web Real-Time Communication (WebRTC)

  • webrtc communication web

Web Real-Time Communication (WebRTC) is an open source project currently being developed with an aim to provide real time, peer-to-peer communication between web applications. WebRTC provides simple JavaScript APIs that help developers to easily build web applications with real time audio, video and data transfer capabilities. This blog has been written assuming that the reader has zero knowledge of how WebRTC works and hence have explained the entire working in detail using simple terms and analogies wherever possible. Let’s get started!

Read More


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More


Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More


Advanced Programming Guide in Redis using Jedis

  • redis jedis advanced-guide cluster pipline publish-subscribe

Redis is an in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This blog covers the advanced concepts like cluster, publish and subscribe, pipeling concepts of Redis using Jedis Java library.

Read More


Top 10 AI development tools which you should know in 2020

  • artificial-Intelligence neural-networks frameworks

It is a fact the 2020 is not going the way we expected to be but when it comes to technology breakthrough we can say 2020 will be the heir of greatness. <br />Speaking of technical breakthroughs we have got artificial intelligence which is known to be taking over the mankind like a wildfire. Everything around us is connected through AI be it shopping travelling or even reading. Every other activity of ours is transforming into a whole new extent.

Read More