Unclear CORS filter in Play

116 Views Asked by At

I have app in Play. My application.conf file is:

include "silhouette.conf"

play.modules.enabled += "modules.SilhouetteModule"


play.filters.enabled += "play.filters.cors.CORSFilter"

play.filters.hosts {
  allowed = ["."]
}

play.filters.cors {
  pathPrefixes = ["/"]
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  allowedHttpHeaders = null
}

So, we can see that all sources should go.

My front-end fetch request looks like this (in react app):

export function signIn(email, password) {
    const host = "http://localhost:9000/"
    const route = "signIn";
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email, password: password }),
        credentials: 'include',      
    };
    return fetch(host + route, requestOptions)
}

Chrome shows this:

Access to fetch at 'http://localhost:9000/signIn' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Yes, I tried to use 'no-cors' but it still doesn't work ;) It's very unclear, and I don't know how it works and how to configure it.

2

There are 2 best solutions below

2
The Trainer On BEST ANSWER

It seems to me that Play adds CSRF filter as default. After adding +nocsrf in routes file everything works. It's quite odd and unclear.

# Authentication
+nocsrf
POST        /signUp                                   controllers.SignUpController.signUp
+nocsrf
POST        /signIn                                   controllers.SignInController.signIn
+nocsrf
POST        /signOut                                  controllers.SignInController.signOut
1
Nisharg Shah On

Here is the thing, I get from the play framwork documentation

play.filters.cors {
  pathPrefixes = ["/some/path", ...]
  allowedOrigins = ["http://www.example.com", ...] <-- Add your localhost url here
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}

Doc: https://www.playframework.com/documentation/2.8.x/CorsFilter