Skip to content

CookieWebSessionIdResolver should set path to the context path + "/" [SPR-16030] #20579

@spring-projects-issues

Description

@spring-projects-issues

Rob Winch opened SPR-16030 and commented

Currently the cookie path of the session is left blank which means the cookie path is the current path of the request. This means when a user creates a session in a nested directory like /foo/bar/ the path of the cookie prevents it from being submitted in / or /a/b/.

Since a session is scoped to an application, we should set the path of the cookie to be the context path of the application.

The following code provides a reasonably simple workaround.

@Bean(WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME)
public WebSessionManager webSessionManager() {
	DefaultWebSessionManager manager = new DefaultWebSessionManager();
	manager.setSessionIdResolver(new PatchCookieWebSessionIdResolver());
	return manager;
}

static class PatchCookieWebSessionIdResolver extends CookieWebSessionIdResolver {
	@Override
	public void setSessionId(ServerWebExchange exchange, String id) {
		Assert.notNull(id, "'id' is required");
		setSessionCookie(exchange, id, getCookieMaxAge());
	}

	private void setSessionCookie(ServerWebExchange exchange, String id, Duration maxAge) {
		String name = getCookieName();
		boolean secure = "https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme());
		MultiValueMap<String, ResponseCookie> cookieMap = exchange.getResponse().getCookies();
		String path = exchange.getRequest().getPath().contextPath().value() + "/";
		cookieMap.set(name, ResponseCookie.from(name, id).path(path).maxAge(maxAge).httpOnly(true).secure(secure).build());
	}
}

Affects: 5.0 GA

Referenced from: commits 2d05e53

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions