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




Related Articles

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


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


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



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


LetsEncrypt certificate using ZeroSSL tools

  • ssl-certificate certificate security

Let’s Encrypt is a free, automated, and open Certificate Authority. It uses ACME protocol to validate your domain. If you have complete control over your domain, you can get a certificate for free. In order to provide secure access to your public network like HTTPS, LDAPS etc you need a certificate from a Certificate Authority. The cost of the certificate range from 10$ to 100$. If you want a wildcard certificate then it may cost more. The certificate is valid for one year and you need to pay and renew every year. Let's Encrypt comes for the rescue. You can create and renew certificate for few.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More


Generate Thumbnail in Java using Thumbnailator library 

  • thumbnail image-processing java

In our work there will be situation where we need to resize the image, generate thumbnails and so on. Users need to have little bit of image processing knowledge to achieve it. We have Java ImageIO APIs to achieve these functionalities. As said, we need to be aware of or spend time in learning these APIs. To help us, Thumbnailator library provides easy fluent style API and generates thumbnail in simple three lines of code.

Read More


How to solve CommunicationsException in Java while using Hibernate and MySQL

  • java hibernate mysql communicationsexception timeout

You might have faced CommunicationsException, basically timeout issue in Java while connecting to MySQL using Hibernate. The session would be timed out after certain period of time. You might be thinking that the your site or application is running without any issue but it would have stopped or crashed due to exception.

Read More


How hashmap works in Java. My style of learning.

  • java hashmap opensource-learning

This is the most frequently asked questions in the interview. Googling will throw many links related to this topic. How to learn the implementation of hash map? My style of learning using open source learning technique.

Read More


Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More


GlobalSign - Free Certificate for Open Source Projects

  • free certificate ssl security

GlobalSign is one of the Internet’s original trust service providers (technically known as Certificate Authorities). They have issued millions of trusted Digital Certificates to people, servers and mobile devices for Public Key Infrastructure (PKI) enabled solutions and applications. They are now giving certificates for free for open source projects.

Read More


Identicon - Get unique avatar for your website users

  • identicon avatar icon gravatar

Users login in to the Websites, Blogs, Forum and adding their content, comments, asking or answering the questions etc. If user has added his photo then it will get displayed besides his content but not everyone provides his photo image to the sites. Most of the sites used to display a common avatar image for those who have not provided their image. When we read the content, it may be odd to see the same image representation for all users. Identicon comes for the rescue.

Read More


React Patent Clause Licensing issue. Is it something to worry?

  • react react-license facebook

React libraries from Facebook is one of the most used UI libraries. It is competitive to AngularJS. There are many open source UI components or frameworks available but mostly people narrow down to two choices Angular / React. Recently Facebook has updated React license and added a patent clause which makes companies to worry and rethink whether to use React or not.

Read More


8 Best Open Source Searchengines built on top of Lucene

  • lucene solr searchengine elasticsearch

Lucene is most powerful and widely used Search engine. Here is the list of 7 search engines which is built on top of Lucene. You could imagine how powerful they are.

Read More


Various tools to work with Git version control

  • scm git repository solution tools-used

Git is the most popular SCM, initially developed to manage source of Linux kernel. Later many clients and tools are developed for Git. In this article we going to see various tools to use with Git.

Read More


Why Elastic Search is gaining more popularity than Solr?

  • solr elastic-search search-engine

Solr and Elastic Search both are built on top of Lucene library. Both are compratively equal. Any new feature / enhancement which get introduced in Lucene, will also get added to Solr. But still Elastic Search which uses Lucene as it core gained more popularity than Solr in recent years.

Read More


Should web application store images in Database or File system?

  • database image-store filesystem

Web developers most frequent question, Should user images be stored in database or file system? Which is the best way. Both has some pros and cons.

Read More


An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More