Integrate JWT with Akka HTTP

In this article we will discuss about , how to implement  authentication or authorization in Akka HTTP routes using JWT .

As we know Akka HTTP is full implementation of  server  and client side HTTP stack on top Akka actor and Akka stream . Now Let’s  we  talk about JWT.

what is JWT ?

JSON Web Token (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. This 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.

What is the JSON Web Token structure?

JSON Web Tokens consist of three parts separated by dots “.”, which are:

  • Header
  • Payload
  • Signature

Let’s dive into  detail of each part.

Header :  The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA.

For Example :

Payload: The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata.

For Example :

Signature : To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

So Let’s start with code , you have to add following dependencies in your build.sbt file.

Now , we have to create an Authentication Handler to  handle JWT related operations .

This AuthHandler has three methods like createTokenWithRole()  which creates JWT token with the help of secret key , username and role, second is getAuthToken() which fetch JWT token from HTTP Request and last method is isVerifyWithRole() which is use to verify incoming HTTP Request with the help of secret key and user role.

Now , we have to create Akka HTTP routes with JWT AuthenticationHandler :

I have added test cases of these routes , so that you can easily test it.

I hope, it will be helpful for you.

You can find source code here

Happy Blogging !!!

Written by 

Narayan Kumar is a Sr. Software Consultant having experience of more than 3.5 years. He is passionate about Scala development and have worked on the complete range of Scala Ecosystem. He is a quick learner & curious to learn new technologies. He is responsible and a good team player. He has a good understanding of building streaming application on Apache Spark, Kafka and Cassandra.

3 thoughts on “Integrate JWT with Akka HTTP

Leave a Reply

%d bloggers like this: