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

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

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

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

  • Understanding the Identity Bridge Framework
  • Secure Your API With JWT: Kong OpenID Connect
  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Navigating the API Seas: A Product Manager's Guide to Authentication

Trending

  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Grafana Loki Fundamentals and Architecture
  1. DZone
  2. Coding
  3. Frameworks
  4. JWT Authentication with Play Framework

JWT Authentication with Play Framework

In this post, we'll go over using JWT Authentication with the Play Framework for front-end web development to help make your site more secure.

By 
Teena Vashist user avatar
Teena Vashist
·
Feb. 21, 17 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
18.3K Views

Join the DZone community and get the full member experience.

Join For Free

In this blog, I will demonstrate how to implement JWT Authentication with Play Framework.

JSON Web Token (JWT) is a compact, self-contained means to securely transfer information between two parties. It can be sent via a Post request or inside the HTTP header. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret or a public/private key pair using RSA. It consists of three parts separated by a dot(.): the Header, Payload, and Signature. The header tells the user the type of token and hashing algorithm, the payload contains the claims (and the claims in a JWT are encoded as a JSON object that is used as the payload or as the plaintext), and the signature is used to verify the sender of the JWT.

Here, we are using JSON Web Token for authentication with Play Framework. This is one of the most common ways of using JWT. Once the user is logged in, we need to include JWT with each request that allows the user to access the routes, services, and resources which authenticate the token in order to permit the request.

Let’s start with the implementation of JWT Authentication using Play Framework:

1. First, we need to include JWT library in our project. There are several libraries for JWT. You can use any of them depending on your requirement.

"com.jason-goodwin" %% "authentikat-jwt" % "0.4.5"

2. Next, you need to create a JWT utility class into which you need to add all these methods for creating, verifying, and decoding the JWT token, and provide the secret key and algorithm such as HMAC, SHA256.

val JwtSecretKey = "secretKey"
val JwtSecretAlgo = "HS256"

def createToken(payload: String): String = {
  val header = JwtHeader(JwtSecretAlgo)
  val claimsSet = JwtClaimsSet(payload)

  JsonWebToken(header, claimsSet, JwtSecretKey)
}

def isValidToken(jwtToken: String): Boolean =
  JsonWebToken.validate(jwtToken, JwtSecretKey)

def decodePayload(jwtToken: String): Option[String] =
  jwtToken match {
    case JsonWebToken(header, claimsSet, signature) => Option(claimsSet.asJsonString)
    case _                                          => None
  }

3. To implement JWT authentication, we need to create a reusable custom secured action by using ActionBuilder that authenticates each subsequent request and verifies the JWT in order to permit the request to access the corresponding service. ActionBuilder is the special case of functions that takes requests as input and thus can build actions and provides several factory methods that help in creating actions. To implement ActionBuilder, we need to implement the invokeBlock method. Here, I have created a custom JWTAuthentication using ActionBuilder.

case class User(email: String, userId: String) 
case class UserRequest[A](user: User, request: Request[A]) extends WrappedRequest(request)

object JWTAuthentication extends ActionBuilder[UserRequest] {
  def invokeBlock[A](request: Request[A], block: (UserRequest[A]) => Future[Result]): Future[Result] = {
    implicit val req = request

    val jwtToken = request.headers.get("jw_token").getOrElse("")

    if (JwtUtility.isValidToken(jwtToken)) {
      JwtUtility.decodePayload(jwtToken).fold(
        Future.successful(Unauthorized("Invalid credential"))
      ) { payload =>
        val userInfo = Json.parse(payload).validate[User].get

        // Replace this block with data source
        if (userInfo.email == "test@example.com" && userInfo.userId == "userId123") {
          Future.successful(Ok("Authorization successful"))
        } else {
          Future.successful(Unauthorized("Invalid credential"))
        }
      }
    }
    else {
      Future.successful(Unauthorized("Invalid credential"))
    }
  }
}

4. Now we can use “JWTAuthentication” the same way we use Action.

def index = JWTAuthentication { implicit request =>
  Ok(views.html.index("Hello world"))
}

5. You can test it through Postman (on which you can send the request and view responses), all we need to do is create a JWT and pass it to the Headers, corresponding to the field “jw_token.” You can create a JSON web token by the “createToken” method that I showed you in step 2 by passing payload as a parameter which can be anything. Here's an example:

val payload = """{"email":"test@example.com","userId":"userId123"}"""

JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJ1c2VySWQiOiJ1c2VySWQxMjMifQ.mjMQN8m_wH1NSE9GGexCW_GUh8uruNco18jgt7AWuO4

jwt.png

You can get the source code from here.

I hope this blog is helpful to you!

Thanks

References:

  • https://jwt.io/introduction/
JWT (JSON Web Token) authentication Framework Play Framework

Published at DZone with permission of Teena Vashist. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Understanding the Identity Bridge Framework
  • Secure Your API With JWT: Kong OpenID Connect
  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Navigating the API Seas: A Product Manager's Guide to Authentication

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!