Zuplo

API Key Authentication

Secure Your Play Framework API with API Keys

The Zuplo API Gateway protects your backend API from unauthorized access, abuse, and overload. Add API key authentication to your Play Framework API in minutes.

Secure Access

Authenticate every request before it reaches your backend.

Control Costs

Set rate limits and quotas to prevent runaway usage.

Ensure Reliability

Shield your backend from overload with traffic management.

How it works

The Zuplo API Gateway sits between your clients and your Play Framework backend, providing a secure layer of protection and control.

Client
Zuplo API Gateway

Customer VPC

Backend

Step-by-step tutorial

It takes only a few minutes to put Zuplo in front of your Play Framework backend, adding API key authentication, and configuring your origin to trust requests from Zuplo using JWT verification.

1

Create a Route in Zuplo

First, create a new route in your Zuplo project that will proxy requests to your Play Framework backend. This route will be the entry point for your API consumers.

Creating a route in Zuplo
Learn how to create routes

📄 OpenAPI native. Import your existing OpenAPI spec to instantly create routes and power your API documentation .

2

Add API Key Authentication Policy

Add the API Key Authentication policy to your route. This policy validates incoming API keys and ensures only authorized consumers can access your API.

Adding API Key Authentication policy in Zuplo
API Key Authentication docs

🔐 Leaked key? No problem. As a GitHub Secret Scanning partner, Zuplo can automatically revoke exposed keys before they can be exploited.

3

Enable the JWT Service Plugin

Enable the JWT Service Plugin in your Zuplo project. This plugin generates JWTs that your origin API can validate, creating a secure trust relationship between Zuplo and your backend.

TypeScriptmodules/zuplo.runtime.ts
export function runtimeInit(runtime: RuntimeExtensions) {
  // Register the JWT Service Plugin
  runtime.addPlugin(new JwtServicePlugin());
}
JWT Service Plugin docs
4

Secure Your Play Framework API with JWT Authentication

Configure your Play Framework backend to validate the JWTs issued by Zuplo. This ensures that only requests coming through your Zuplo gateway are accepted.

Scala
// app/filters/JwtAuthFilter.scala
package filters

import javax.inject.Inject
import akka.stream.Materializer
import play.api.mvc._
import play.api.libs.json._
import play.api.libs.ws.WSClient
import pdi.jwt.{JwtJson, JwtAlgorithm, JwtClaim}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Success, Failure}

class JwtAuthFilter @Inject()(
  implicit val mat: Materializer,
  ec: ExecutionContext,
  ws: WSClient
) extends Filter {

  private val issuer = "https://my-api-a32f34.zuplo.api/__zuplo/issuer"
  private val jwksUri = s"$issuer/.well-known/jwks.json"

  @volatile private var cachedJwks: Option[(JsValue, Long)] = None

  def apply(nextFilter: RequestHeader => Future[Result])(request: RequestHeader): Future[Result] = {
    request.headers.get("Authorization") match {
      case Some(header) if header.startsWith("Bearer ") =>
        val token = header.drop(7)
        validateToken(token).flatMap {
          case Right(claims) =>
            nextFilter(request.addAttr(JwtAuthFilter.UserKey, claims))
          case Left(error) =>
            Future.successful(Results.Unauthorized(Json.obj("error" -> error)))
        }
      case _ =>
        Future.successful(Results.Unauthorized(Json.obj("error" -> "No token provided")))
    }
  }

  private def validateToken(token: String): Future[Either[String, JsValue]] = {
    fetchJwks().map { jwks =>
      JwtJson.decodeJson(token, jwks, Seq(JwtAlgorithm.RS256)) match {
        case Success(claims) =>
          val claimsJson = Json.parse(claims.toJson)
          if ((claimsJson \ "iss").asOpt[String].contains(issuer)) {
            Right(claimsJson)
          } else {
            Left("Invalid issuer")
          }
        case Failure(e) =>
          Left(s"Invalid token: ${e.getMessage}")
      }
    }
  }

  private def fetchJwks(): Future[String] = {
    val now = System.currentTimeMillis()
    cachedJwks match {
      case Some((jwks, timestamp)) if now - timestamp < 600000 =>
        Future.successful(jwks.toString)
      case _ =>
        ws.url(jwksUri).get().map { response =>
          cachedJwks = Some((response.json, now))
          response.json.toString
        }
    }
  }
}

object JwtAuthFilter {
  val UserKey = TypedKey[JsValue]("user")
}

// app/controllers/ProtectedController.scala
package controllers

import javax.inject.Inject
import play.api.mvc._
import play.api.libs.json._
import filters.JwtAuthFilter

class ProtectedController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def index = Action { request =>
    request.attrs.get(JwtAuthFilter.UserKey) match {
      case Some(user) =>
        Ok(Json.obj(
          "message" -> "Access granted",
          "user" -> user
        ))
      case None =>
        Unauthorized(Json.obj("error" -> "Not authenticated"))
    }
  }
}

// conf/routes
// GET /protected controllers.ProtectedController.index
5

Call Your API Through Zuplo

Now you can call your API through Zuplo using an API key. The request will be authenticated at the gateway, and a JWT will be forwarded to your Play Framework backend.

Terminalbash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Ready to secure your API?

Get started with Zuplo for free and add API key authentication to your Play Framework API in minutes.