Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
173: JWT Authentication in Play/Akka HTTP
How do I actually create the token once a user logs in?
Once you've verified the user's credentials against your database, you don't want to keep checking the password on every single request. That's where the JWT comes in. I usually reach for the jwt-scala library because it's lightweight and doesn't bring in a mountain of dependencies.
The key is to pack a "claim" into the token—something that identifies the user, like their userId—and set a reasonable expiration time. If you make the token last for a year, you've just created a security hole. I typically go with 15 minutes to an hour.
import jwt.JwtScala
import jwt.JwtScala.Claims
val secret = "your-super-secret-key-keep-it-safe" // In production, load this from config/env
val userId = "user_12345"
val claims = Claims()
claims.setSubject(userId)
claims.setExpiration(System.currentTimeMillis() + 3600000) // 1 hour from now
val token = JwtScala.encode(claims, secret)
// Now send this 'token' back to the client in the response body or a cookie
Where does the logic go to intercept and validate these tokens?
You definitely don't want to manually decode the token inside every single controller method. That's a maintenance nightmare. In Play, the cleanest way to handle this is by creating a custom Action. Think of it as a gatekeeper that runs before your actual logic.
I'll show you a simplified version of a JwtAction. It looks for the Authorization header, strips the "Bearer " prefix, and tries to validate the token. If it fails, we stop right there and return a 401 Unauthorized.
import javax.inject._
import play.api.mvc._
import jwt.JwtScala
class JwtAction @Inject()(val parser: BodyParsers.Default) extends Action {
def execute(request: Request[A]): Future[Result] = {
val authHeader = request.headers.get("Authorization")
authHeader match {
case Some(header) if header.startsWith("Bearer ") =>
val token = header.substring(7)
try {
val claims = JwtScala.decode(token, "your-super-secret-key-keep-it-safe")
// We've validated the token! Now we pass the user ID along to the controller
request.flatMap { req =>
// In a real app, you'd wrap the request in a custom Request type containing the user
Future.successful(next(req))
}
} catch {
case _: Exception => Future.successful(Results.Unauthorized("Invalid or expired token"))
}
case _ =>
Future.successful(Results.Unauthorized("Missing Authorization header"))
}
}
}
What happens when a token expires? How do I handle that gracefully?
This is where most developers trip up. When JwtScala.decode hits an expired token, it throws an exception. If you aren't catching that, your whole request crashes. I prefer treating the decoding process as a "failure-prone" operation using a try-catch or wrapping it in an Either.
From the client's perspective, they just get a 401. Your frontend should be smart enough to see that 401 and either redirect the user to the login page or use a "refresh token" to get a new JWT without making the user type their password again. I personally find that keeping the access token short-lived and using a separate, long-lived refresh token stored in an HttpOnly cookie is the gold standard for security.
📋 Practical Task
Implementing a Protected "Post Review" Endpoint for the Book Review API
You are building a Book Review API. Currently, anyone can post a review, which is causing a lot of spam. Your task is to protect the POST /reviews endpoint.
- Create a custom
JwtAction(or an Akka HTTP Directive if you're using Akka) that extracts theuserIdfrom the JWT claims. - Modify the
postReviewmethod in your controller so that it only accepts requests passing through yourJwtAction. - Ensure that the
userIdextracted from the token is the one saved as the author of the review in the database, rather than trusting auserIdsent in the JSON body of the request. - Test the endpoint by sending a request with an expired token and verify that the server returns a
401 Unauthorizedinstead of a500 Internal Server Error.
There are no comments for now.