Skip to content

Commit 03d94ed

Browse files
committed
Add cookieDomain to CookieCsrfTokenRepository
Fixes: gh-4315
1 parent 9a357f8 commit 03d94ed

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java

+17
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ public final class CookieCsrfTokenRepository implements CsrfTokenRepository {
5555

5656
private String cookiePath;
5757

58+
private String cookieDomain;
59+
5860
public CookieCsrfTokenRepository() {
5961
this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
6062
if (this.setHttpOnlyMethod != null) {
@@ -88,6 +90,9 @@ public void saveToken(CsrfToken token, HttpServletRequest request,
8890
if (cookieHttpOnly && setHttpOnlyMethod != null) {
8991
ReflectionUtils.invokeMethod(setHttpOnlyMethod, cookie, Boolean.TRUE);
9092
}
93+
if (this.cookieDomain != null && !this.cookieDomain.isEmpty()) {
94+
cookie.setDomain(this.cookieDomain);
95+
}
9196

9297
response.addCookie(cookie);
9398
}
@@ -194,4 +199,16 @@ public void setCookiePath(String path) {
194199
public String getCookiePath() {
195200
return this.cookiePath;
196201
}
202+
203+
/**
204+
* Sets the domain of the cookie that the expected CSRF token is saved to and read from.
205+
*
206+
* @since 5.2
207+
* @param cookieDomain the domain of the cookie that the expected CSRF token is saved to
208+
* and read from
209+
*/
210+
public void setCookieDomain(String cookieDomain) {
211+
this.cookieDomain = cookieDomain;
212+
}
213+
197214
}

web/src/test/java/org/springframework/security/web/csrf/CookieCsrfTokenRepositoryTests.java

+14
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,20 @@ public void saveTokenNullCustomPath() {
189189
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
190190
}
191191

192+
@Test
193+
public void saveTokenWithCookieDomain() {
194+
String domainName = "example.com";
195+
this.repository.setCookieDomain(domainName);
196+
197+
CsrfToken token = this.repository.generateToken(this.request);
198+
this.repository.saveToken(token, this.request, this.response);
199+
200+
Cookie tokenCookie = this.response
201+
.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
202+
203+
assertThat(tokenCookie.getDomain()).isEqualTo(domainName);
204+
}
205+
192206
@Test
193207
public void loadTokenNoCookiesNull() {
194208
assertThat(this.repository.loadToken(this.request)).isNull();

0 commit comments

Comments
 (0)