Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate CSRF cookie in case of failures #30794

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,7 @@ public void filter(ResteasyReactiveContainerRequestContext requestContext, Routi
if (requestMethodIsSafe(requestContext)) {
// safe HTTP method, tolerate the absence of a token
if (cookieToken == null && isCsrfTokenRequired(routing, config)) {
// Set the CSRF cookie with a randomly generated value
byte[] tokenBytes = new byte[config.tokenSize];
secureRandom.nextBytes(tokenBytes);
byte[] tokenBytes = generateCsrfTokenBytes(config);
routing.put(CSRF_TOKEN_BYTES_KEY, tokenBytes);
routing.put(CSRF_TOKEN_KEY, Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes));
}
Expand Down Expand Up @@ -148,6 +146,13 @@ public void filter(ResteasyReactiveContainerRequestContext requestContext, Routi
}
}

private byte[] generateCsrfTokenBytes(CsrfReactiveConfig config) {
// Generate CSRF token
byte[] tokenBytes = new byte[config.tokenSize];
secureRandom.nextBytes(tokenBytes);
return tokenBytes;
}

private static boolean isMatchingMediaType(MediaType contentType, MediaType expectedType) {
return contentType.getType().equals(expectedType.getType())
&& contentType.getSubtype().equals(expectedType.getSubtype());
Expand Down Expand Up @@ -179,16 +184,15 @@ && getCookieToken(routing, config) == null) {
byte[] csrfTokenBytes = (byte[]) routing.get(CSRF_TOKEN_BYTES_KEY);

if (csrfTokenBytes == null) {
throw new IllegalStateException(
"CSRF Filter should have set the property " + CSRF_TOKEN_KEY + ", but it is null");
csrfTokenBytes = generateCsrfTokenBytes(config);
}
cookieValue = CsrfTokenUtils.signCsrfToken(csrfTokenBytes, config.tokenSignatureKey.get());
} else {
String csrfToken = (String) routing.get(CSRF_TOKEN_KEY);

if (csrfToken == null) {
throw new IllegalStateException(
"CSRF Filter should have set the property " + CSRF_TOKEN_KEY + ", but it is null");
byte[] csrfTokenBytes = generateCsrfTokenBytes(config);
csrfToken = Base64.getUrlEncoder().withoutPadding().encodeToString(csrfTokenBytes);
}
cookieValue = csrfToken;
}
Expand Down