22
22
import java .io .IOException ;
23
23
import java .net .URI ;
24
24
import java .util .List ;
25
+ import java .util .regex .Pattern ;
25
26
26
27
public class CSRFInterceptor implements ContainerRequestFilter {
27
28
@@ -31,14 +32,15 @@ public class CSRFInterceptor implements ContainerRequestFilter {
31
32
32
33
private static final String REFERER_HEADER = "Referer" ;
33
34
34
- private final String serverPort ;
35
+ private static final Pattern localhostPattern = Pattern .compile ("^http[s]?://localhost:" );
36
+
37
+ private static final Pattern loopbackhostPattern = Pattern .compile ("^http[s]?://127\\ .0\\ .0\\ .1:" );
35
38
36
39
private final boolean productionMode ;
37
40
38
41
private final List <String > csrfAllowed ;
39
42
40
- public CSRFInterceptor (String port , boolean productionMode , String csrfAllowed ) {
41
- serverPort = port ;
43
+ public CSRFInterceptor (boolean productionMode , String csrfAllowed ) {
42
44
this .productionMode = productionMode ;
43
45
this .csrfAllowed = Strings .isNullOrEmpty (csrfAllowed ) ? Lists .newArrayList () : Splitter .on ("," ).splitToList (csrfAllowed .trim ());
44
46
}
@@ -61,13 +63,8 @@ public void filter(ContainerRequestContext requestContext)
61
63
// explicitly ok
62
64
if (csrfAllowed .contains (refererHostPort )) return ;
63
65
64
- String localhost = String .format ("localhost:%s" , serverPort );
65
- String loopbackhost = String .format ("127.0.0.1:%s" , serverPort );
66
66
boolean forbidden = false ;
67
- if (localhost .equals (host ) || loopbackhost .equals (host )) {
68
- if (!referer .startsWith (String .format ("http://%s/" , host )))
69
- forbidden = true ;
70
- } else if (!referer .startsWith (String .format ("https://%s/" , host ))) {
67
+ if (!localhostPattern .matcher (host ).matches () && !loopbackhostPattern .matcher (host ).matches () && !referer .startsWith (String .format ("https://%s/" , host ))) {
71
68
forbidden = true ;
72
69
}
73
70
0 commit comments