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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Trending

  • Building IoT Time-Series Applications With Java and Apache IoTDB
  • How to Format Articles for DZone
  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Constrained Decoding Models Explained: Encoders, Decoders and When to Use Them

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Handling CORS in Akka HTTP

Handling CORS in Akka HTTP

This tutorial shows a quick way for you to handle CORS requests in Akka HTTP-based microservices, with the added bonus of adding CORS headers to any HttpResponse.

By 
Agraj Mangal
·
May. 22, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
33.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Here’s a quick tip for handling CORS requests in your Akka HTTP based microservice:

Create the following trait – CORSHandler

Handler for your Akka Http RoutesScala

trait CORSHandler{

  private val corsResponseHeaders = List(
    `Access-Control-Allow-Origin`.*,
    `Access-Control-Allow-Credentials`(true),
    `Access-Control-Allow-Headers`("Authorization",
      "Content-Type", "X-Requested-With")
  )

  //this directive adds access control headers to normal responses
  private def addAccessControlHeaders: Directive0 = {
    respondWithHeaders(corsResponseHeaders)
  }

  //this handles preflight OPTIONS requests.
  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(StatusCodes.OK).
      withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))
  }

  // Wrap the Route with this method to enable adding of CORS headers 
  def corsHandler(r: Route): Route = addAccessControlHeaders {
    preflightRequestHandler ~ r
  }

  // Helper method to add CORS headers to HttpResponse 
  // preventing duplication of CORS headers across code
  def addCORSHeaders(response: HttpResponse):HttpResponse =
    response.withHeaders(corsResponseHeaders)

}

To use this trait in an actual route, we take the example route given in the Akka documentation and wrap the route with our corsHandler method defined in the above trait, as follows:

ng CORSHandler in RouteScala

get {
   // Using the CORSHandler in our actual routes 
   corsHandler(
      pathSingleSlash {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
             "<html><body>Hello world!</body></html>"))
      } ~
      path("ping") {
          complete("PONG!")
      } ~
      path("crash") {
          sys.error("BOOM!")
      }
   )
}

Explanation

This trait gives us a simple way to add the CORS headers to every response that this route sends back. This CORSHandler, apart from adding response headers is also responsible for handling OPTIONS HTTP request (the preflight request) for which it sends back a 200 OK response with the header Access-Control-Allow-Methods specifying which HTTP methods can be used in subsequent calls as per the CORS specification.

This trait has a bonus method for adding CORS Headers to any HttpResponse, which is created from somewhere else in your application, say from an Exception or Rejection Handler where the response is created and sent back from a different flow than the normal route flow.

That’s it for today. Happy hacking!

Akka (toolkit)

Published at DZone with permission of Agraj Mangal. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook