Skip to content

Commit 0fd5b47

Browse files
authored
Refactor header management in CommentCaptchaFilter for Spring Framework 7 compatibility (#212)
1 parent 69c2e95 commit 0fd5b47

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

src/main/java/run/halo/comment/widget/captcha/CommentCaptchaFilter.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import com.fasterxml.jackson.databind.ObjectMapper;
1010
import lombok.RequiredArgsConstructor;
1111
import org.apache.commons.lang3.StringUtils;
12+
import org.springframework.http.HttpHeaders;
1213
import org.springframework.http.HttpMethod;
1314
import org.springframework.http.HttpStatus;
1415
import org.springframework.http.ProblemDetail;
@@ -65,14 +66,14 @@ public Mono<Void> filter(@NonNull ServerWebExchange exchange, @NonNull WebFilter
6566
private Mono<Void> sendCaptchaRequiredResponse(ServerWebExchange exchange,
6667
SettingConfigGetter.CaptchaConfig captchaConfig,
6768
ResponseStatusException e) {
68-
exchange.getResponse().getHeaders().addIfAbsent(CAPTCHA_REQUIRED_HEADER, "true");
69+
addHeaderIfAbsent(exchange.getResponse().getHeaders(), CAPTCHA_REQUIRED_HEADER, Boolean.TRUE.toString());
6970
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
7071
return captchaManager.generate(exchange, captchaConfig)
7172
.flatMap(captcha -> {
7273
var problemDetail = toProblemDetail(e);
7374
problemDetail.setProperty("captcha", captcha.imageBase64());
7475
var responseData = getResponseData(problemDetail);
75-
exchange.getResponse().getHeaders().addIfAbsent("Content-Type", CONTENT_TYPE);
76+
addHeaderIfAbsent(exchange.getResponse().getHeaders(), HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
7677
return exchange.getResponse()
7778
.writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(responseData)));
7879
});
@@ -151,4 +152,17 @@ Mono<Boolean> isAnonymousCommenter(ServerWebExchange exchange) {
151152
public int getOrder() {
152153
return SecurityWebFiltersOrder.AUTHORIZATION.getOrder();
153154
}
155+
156+
/**
157+
* Adds a header to the HttpHeaders if it is not already present. Only for forward-compatibility with Spring Framework 7.
158+
*
159+
* @param headers the HttpHeaders to add the header to
160+
* @param headerName the name of the header
161+
* @param headerValue the value of the header
162+
*/
163+
private static void addHeaderIfAbsent(HttpHeaders headers, String headerName, String headerValue) {
164+
if (headers.getFirst(headerName) == null) {
165+
headers.add(headerName, headerValue);
166+
}
167+
}
154168
}

0 commit comments

Comments
 (0)