77import org .slf4j .LoggerFactory ;
88import restx .*;
99import restx .factory .Component ;
10- import restx .http .HttpStatus ;
1110
1211import java .io .IOException ;
1312import java .util .Collection ;
@@ -34,7 +33,7 @@ public CORSFilter(Iterable<CORSAuthorizer> authorizers) {
3433 @ Override
3534 public Optional <RestxHandlerMatch > match (RestxRequest req ) {
3635 Optional <String > origin = req .getHeader ("Origin" );
37- if (origin .isPresent ()) {
36+ if (origin .isPresent () && ! isSameOrigin ( req , origin . get ()) && ! isPreflightRequest ( req ) ) {
3837 CORS cors = CORS .check (authorizers , req , origin .get (), req .getHttpMethod (), req .getRestxPath ());
3938 if (cors .isAccepted ()) {
4039 return Optional .of (new RestxHandlerMatch (new StdRestxRequestMatch ("*" , req .getRestxPath (),
@@ -54,6 +53,12 @@ public Optional<RestxHandlerMatch> match(RestxRequest req) {
5453 return Optional .absent ();
5554 }
5655
56+ private boolean isPreflightRequest (RestxRequest req ) {
57+ return req .getHeader ("Origin" ).isPresent ()
58+ && req .getHeader ("Access-Control-Request-Method" ).isPresent ()
59+ && "OPTIONS" .equals (req .getHttpMethod ());
60+ }
61+
5762 protected boolean isSimpleCORSRequest (RestxRequest req ) {
5863 // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
5964 if (!SIMPLE_METHODS .contains (req .getHttpMethod ())) {
@@ -69,18 +74,23 @@ protected boolean isSimpleCORSRequest(RestxRequest req) {
6974 return false ;
7075 }
7176 }
77+ return true ;
78+
79+ }
80+
81+ private boolean isSameOrigin (RestxRequest req , String origin ) {
7282 // same origin check.
7383 // see http://stackoverflow.com/questions/15512331/chrome-adding-origin-header-to-same-origin-request
7484 Optional <String > host = req .getHeader ("Host" );
7585 if (!host .isPresent ()) {
7686 // no host header, can't check same origin
77- return true ;
87+ return false ;
7888 }
79- if (origin .get (). endsWith (host .get ())) {
89+ if (origin .endsWith (host .get ())) {
8090 logger .debug ("Same Origin request not considered as CORS Request: {}" , req );
81- return false ;
82- } else {
8391 return true ;
92+ } else {
93+ return false ;
8494 }
8595 }
8696
0 commit comments