use of org.apereo.cas.web.cookie.CookieGenerationContext in project cas by apereo.
the class CookieRetrievingCookieGenerator method addCookieHeaderToResponse.
/**
* Add cookie header to response.
*
* @param cookie the cookie
* @param request the request
* @param response the response
* @return the cookie
*/
protected Cookie addCookieHeaderToResponse(final Cookie cookie, final HttpServletRequest request, final HttpServletResponse response) {
val builder = new StringBuilder();
builder.append(String.format("%s=%s;", cookie.getName(), cookie.getValue()));
if (cookie.getMaxAge() > -1) {
builder.append(String.format(" Max-Age=%s;", cookie.getMaxAge()));
}
if (StringUtils.isNotBlank(cookie.getDomain())) {
builder.append(String.format(" Domain=%s;", cookie.getDomain()));
}
val path = cleanCookiePath(cookie.getPath());
builder.append(String.format(" Path=%s;", path));
val sameSiteResult = CookieSameSitePolicy.of(cookieGenerationContext).build(request, response);
sameSiteResult.ifPresent(result -> builder.append(String.format(" %s", result)));
val sameSitePolicy = cookieGenerationContext.getSameSitePolicy().toLowerCase();
if (cookie.getSecure() || (sameSiteResult.isPresent() && StringUtils.equalsIgnoreCase(sameSiteResult.get(), "none"))) {
builder.append(" Secure;");
LOGGER.trace("Marked cookie [{}] as secure as indicated by cookie configuration or " + "the configured same-site policy set to [{}]", cookie.getName(), sameSitePolicy);
}
if (cookie.isHttpOnly()) {
builder.append(" HttpOnly;");
}
val value = StringUtils.removeEndIgnoreCase(builder.toString(), ";");
LOGGER.trace("Adding cookie header as [{}]", value);
val setCookieHeaders = response.getHeaders("Set-Cookie");
response.setHeader("Set-Cookie", value);
setCookieHeaders.stream().filter(header -> !header.startsWith(cookie.getName() + '=')).forEach(header -> response.addHeader("Set-Cookie", header));
return cookie;
}
Aggregations