Skip to content
This repository has been archived by the owner on Apr 24, 2024. It is now read-only.

Add a CORS example with Authentication #1013

Closed
dwalend opened this issue Feb 26, 2015 · 3 comments
Closed

Add a CORS example with Authentication #1013

dwalend opened this issue Feb 26, 2015 · 3 comments

Comments

@dwalend
Copy link
Contributor

dwalend commented Feb 26, 2015

I've about got this figured out, but I've made a mess of it. There's got to be a way to handle CORS and authentication without the hack I've come up with. Please provide an example in the docs. (And maybe that corsFilter directive.)

I think this needs both spray-routing and spray-can example code to make sense.

Thanks,

Dave

@matsluni
Copy link
Contributor

Hi @dwalend,
have you seen this recent ML post: https://groups.google.com/forum/#!msg/spray-user/GFXMrfeNwzs/9j9sKJqRIlAJ

In the comments of the Coderwall post (https://coderwall.com/p/0izzta/cors-directive-for-spray) there is also an example with authentication.

Maybe this helps you?!

Mats

@dwalend
Copy link
Contributor Author

dwalend commented Mar 23, 2015

Thanks. I found a third one to build from. I don't think it's complete, but we only need it for dev.

//adapted from https://gist.github.com/joseraya/176821d856b43b1cfe19
object gruntWatchCorsSupport extends Directive0 with RouteConcatenation {

  import spray.http.HttpHeaders.{`Access-Control-Allow-Methods`, `Access-Control-Max-Age`, `Access-Control-Allow-Headers`,`Access-Control-Allow-Origin`}
  import spray.routing.directives.RespondWithDirectives.respondWithHeaders
  import spray.routing.directives.MethodDirectives.options
  import spray.routing.directives.RouteDirectives.complete
  import spray.http.HttpMethods.{OPTIONS,GET,POST}
  import spray.http.AllOrigins

  private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
  private val optionsCorsHeaders = List(
    `Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent, Authorization"),
    `Access-Control-Max-Age`(1728000)) //20 days

  val gruntWatch:Boolean = ConfigFactory.load().getBoolean("shrine.steward.gruntWatch")

  override def happly(f: (HNil) => Route): Route = {
    if(gruntWatch) {
      options {
        respondWithHeaders(`Access-Control-Allow-Methods`(OPTIONS, GET, POST) ::  allowOriginHeader :: optionsCorsHeaders){
          complete(StatusCodes.OK)
        }
      } ~ f(HNil)
    }
    else f(HNil)
  }
}

@sirthias
Copy link
Member

Ok, cool.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants