Package net.shibboleth.shared.net

# Class CookieManager

java.lang.Object
net.shibboleth.shared.component.AbstractInitializableComponent
net.shibboleth.shared.net.CookieManager

All Implemented Interfaces:
  `Component`, `DestructableComponent`, `InitializableComponent`

public class CookieManager extends AbstractInitializableComponent
A helper class for managing one or more cookies on behalf of a component.

This bean centralizes settings related to cookie creation and access, and is parameterized by name so that multiple cookies may be managed with common properties.

Some of the features depend on Servlet API >= 6.0 and will be conditionally bypassed otherwise.

## Nested Class Summary

Nested Classes
Modifier and Type
Class
Description
`static enum`
`CookieManager.SameSiteValue`
The allowed same-site cookie attribute values.

## Field Summary

Fields
Modifier and Type
Field
Description
`private Map<String,String>`
`cookieAttributes`
Additional cookie attributes.
`private String`
`cookieDomain`
Domain of cookie.
`private int`
`cookieLimit`
Limit on numbeer of cookies when purging.
`private String`
`cookiePath`
Path of cookie.
`private CookieManager.SameSiteValue`
`defaultSameSite`
SameSite attribute.
`private boolean`
`guardSetAttribute`
Whether to guard `Cookie.setAttribute(String, String)` calls.
`private boolean`
`httpOnly`
Is cookie marked HttpOnly?
`private NonnullSupplier<HttpServletRequest>`
`httpRequestSupplier`
Supplier for the servlet request to read from.
`private NonnullSupplier<HttpServletResponse>`
`httpResponseSupplier`
Supplier for the servlet response to write to.
`private org.slf4j.Logger`
`log`
Class logger.
`private int`
`maxAge`
Maximum age in seconds, or -1 for session.
`private Predicate<HttpServletRequest>`
`sameSiteCondition`
Condition controlling application of SameSite.
`private Map<String,CookieManager.SameSiteValue>`
`sameSiteCookies`
Map of cookie name to same-site attribute value.
`private boolean`
`secure`
Is cookie secure?

## Constructor Summary

Constructors
Constructor
Description
`CookieManager()`
Constructor.

## Method Summary

Modifier and Type
Method
Description
`void`
`addCookie(String name, String value)`
Add a cookie with the specified attributes.
`void`
`addCookie(String name, String value, int overrideMaxAge)`
Add a cookie with the specified attributes.
`void`
`addCookie(String name, String value, String overridePath, int overrideMaxAge)`
Add a cookie with the specified attributes.
`private void`
`attachSameSite(Cookie cookie)`
Implementation of SameSite attachment logic when available.
`private String`
`contextPathToCookiePath()`
Turn the servlet context path into an appropriate cookie path.
`boolean`
`cookieHasValue(String name, String expectedValue)`
Check whether a cookie has a certain value.
`protected void`
`doInitialize()`
Performs the initialization of the component.
`Map<String,String>`
`getCookieAttributes()`
Gets additional attributes to apply to the cookie.
`String`
`getCookieDomain()`
Get the cookie domain to use.
`int`
`getCookieLimit()`
Gets the limit on cookies of a given set when purging.
`String`
`getCookiePath()`
Get the cookie path to use.
`String`
`getCookieValue(String name, String defValue)`
Return the first matching cookie's value.
`protected HttpServletRequest`
`getHttpServletRequest()`
Get the current HTTP request if available.
`protected HttpServletResponse`
`getHttpServletResponse()`
Get the current HTTP response if available.
`int`
`getMaxAge()`
Get maximum age of cookies in seconds, or -1 for a session cookie.
`CookieManager.SameSiteValue`
`getSameSite()`
Gets the SameSite attribute.
`Predicate<HttpServletRequest>`
`getSameSiteCondition()`
Gets the condition controlling application of SameSite.
`boolean`
`isHttpOnly()`
Get the HttpOnly flag.
`boolean`
`isSecure()`
Get the TLS-only flag.
`void`
`purgeStaleCookies(String prefix)`
Unset cookies matching a given prefix in excess of the configured amount.
`void`
`purgeStaleCookies(String prefix, String overridePath)`
Unset cookies matching a given prefix in excess of the configured amount.
`void`
`setCookieAttributes(Map<String,String> attributes)`
Sets additional attributes to apply to the cookie.
`void`
`setCookieDomain(String domain)`
Set the cookie domain to use.
`void`
`setCookieLimit(int limit)`
Sets the limit on cookies of a given set when purging.
`void`
`setCookiePath(String path)`
Set the cookie path to use.
`void`
`setGuardSetAttribute(boolean flag)`
Sets whether to guard calls to `Cookie.setAttribute(String, String)` with a check for the container's servlet API version.
`void`
`setHttpOnly(boolean flag)`
Set the HttpOnly flag.
`void`
`setHttpServletRequestSupplier(NonnullSupplier<HttpServletRequest> requestSupplier)`
Set the Supplier for the servlet request to read from.
`void`
`setHttpServletResponseSupplier(NonnullSupplier<HttpServletResponse> responseSupplier)`
Set the supplier for the servlet response to write to.
`void`
`setMaxAge(int age)`
Maximum age in seconds, or -1 for a session cookie.
`void`
`setMaxAgeDuration(Duration age)`
Maximum age expressed as a `Duration`.
`void`
`setSameSite(CookieManager.SameSiteValue value)`
Sets the SameSite attribute.
`void`
`setSameSiteCondition(Predicate<HttpServletRequest> condition)`
Sets the condition controlling application of SameSite.
`void`
`setSameSiteCookies(Map<CookieManager.SameSiteValue,List<String>> map)`
Set the names of cookies to add the same-site attribute to.
`void`
`setSecure(boolean flag)`
Set the TLS-only flag.
`void`
`unsetCookie(String name)`
Unsets a cookie with the specified name and the default path.
`void`
`unsetCookie(String name, String overridePath)`
Unsets a cookie with the specified name and path.

### Methods inherited from class net.shibboleth.shared.component.AbstractInitializableComponent

`checkComponentActive, checkSetterPreconditions, destroy, doDestroy, ifDestroyedThrowDestroyedComponentException, ifInitializedThrowUnmodifiabledComponentException, ifNotInitializedThrowUninitializedComponentException, initialize, isDestroyed, isInitialized`

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

## Field Details

### log

@Nonnull private org.slf4j.Logger log
Class logger.

### cookiePath

@Nullable private String cookiePath
Path of cookie.

### cookieDomain

@Nullable private String cookieDomain
Domain of cookie.

### httpRequestSupplier

@NonnullAfterInit private NonnullSupplier<HttpServletRequest> httpRequestSupplier
Supplier for the servlet request to read from.

### httpResponseSupplier

@NonnullAfterInit private NonnullSupplier<HttpServletResponse> httpResponseSupplier
Supplier for the servlet response to write to.

### secure

private boolean secure
Is cookie secure?

### httpOnly

private boolean httpOnly
Is cookie marked HttpOnly?

### maxAge

private int maxAge
Maximum age in seconds, or -1 for session.

### guardSetAttribute

private boolean guardSetAttribute
Whether to guard `Cookie.setAttribute(String, String)` calls.

### defaultSameSite

@Nonnull private CookieManager.SameSiteValue defaultSameSite
SameSite attribute.

### sameSiteCookies

@Nonnull private Map<String,CookieManager.SameSiteValue> sameSiteCookies
Map of cookie name to same-site attribute value.

### sameSiteCondition

@Nonnull private Predicate<HttpServletRequest> sameSiteCondition
Condition controlling application of SameSite.

### cookieAttributes

@Nonnull private Map<String,String> cookieAttributes
Additional cookie attributes.

### cookieLimit

@NonNegative private int cookieLimit
Limit on numbeer of cookies when purging.

## Constructor Details

### CookieManager

public CookieManager()
Constructor.

## Method Details

### getCookiePath

@Nullable public String getCookiePath()
Get the cookie path to use.

Returns:
  cookie path
Since:
  9.1.0

### setCookiePath

public void setCookiePath(@Nullable String path)
Set the cookie path to use.

Defaults to the servlet context path.

Parameters:
  `path` - cookie path to use, or null for the default

### getCookieDomain

@Nullable public String getCookieDomain()
Get the cookie domain to use.

Returns:
  cookie domain
Since:
  9.1.0

### setCookieDomain

public void setCookieDomain(@Nullable String domain)
Set the cookie domain to use.

Parameters:
  `domain` - the cookie domain to use, or null for the default

### setHttpServletRequestSupplier

public void setHttpServletRequestSupplier(@Nonnull NonnullSupplier<HttpServletRequest> requestSupplier)
Set the Supplier for the servlet request to read from.

Parameters:
  `requestSupplier` - servlet request supplier

### getHttpServletRequest

@NonnullAfterInit protected HttpServletRequest getHttpServletRequest()
Get the current HTTP request if available.

Returns:
  current HTTP request

### setHttpServletResponseSupplier

public void setHttpServletResponseSupplier(@Nonnull NonnullSupplier<HttpServletResponse> responseSupplier)
Set the supplier for the servlet response to write to.

Parameters:
  `responseSupplier` - servlet response

### getHttpServletResponse

@NonnullAfterInit protected HttpServletResponse getHttpServletResponse()
Get the current HTTP response if available.

Returns:
  current HTTP response or null

### isSecure

public boolean isSecure()
Get the TLS-only flag.

Returns:
  TLS-only flag
Since:
  9.2.0

### setSecure

public void setSecure(boolean flag)
Set the TLS-only flag.

Parameters:
  `flag` - flag to set

### isHttpOnly

public boolean isHttpOnly()
Get the HttpOnly flag.

Returns:
  HttpOnly flag
Since:
  9.2.0

### setHttpOnly

public void setHttpOnly(boolean flag)
Set the HttpOnly flag.

Parameters:
  `flag` - flag to set

### getMaxAge

public int getMaxAge()
Get maximum age of cookies in seconds, or -1 for a session cookie.

Note that this "convention" for -1 is NOT consistent with the RFC and is a hold-over from Java's native Cookie class, probably because the Integer type didn't exist, so there was no way o easily handle a null Max-Age value in the API.

Returns:
  max age in seconds, or -1 for a session cookie
Since:
  9.1.0

### setMaxAge

public void setMaxAge(int age)
Maximum age in seconds, or -1 for a session cookie.

Note that this "convention" for -1 is NOT consistent with the RFC and is a hold-over from Java's native Cookie class, probably because the Integer type didn't exist, so there was no way o easily handle a null Max-Age value in the API.

Parameters:
  `age` - max age to set

### setMaxAgeDuration

public void setMaxAgeDuration(@Nonnull Duration age)
Maximum age expressed as a `Duration`.

Parameters:
  `age` - max age of cookie
Since:
  9.0.0

### setGuardSetAttribute

public void setGuardSetAttribute(boolean flag)
Sets whether to guard calls to `Cookie.setAttribute(String, String)` with a check for the container's servlet API version.

Defaults to true.

Parameters:
  `flag` -

### getSameSite

@Nonnull public CookieManager.SameSiteValue getSameSite()
Gets the SameSite attribute.

Returns:
  the SameSite attribute
Since:
  9.2.0

### setSameSite

public void setSameSite(@Nonnull CookieManager.SameSiteValue value)
Sets the SameSite attribute.

Defaults to non-existent (which is not the same as "None").

Parameters:
  `value` - value to set
Since:
  9.2.0

### setSameSiteCookies

public void setSameSiteCookies(@Nullable Map<CookieManager.SameSiteValue,List<String>> map)
Set the names of cookies to add the same-site attribute to.

The argument map is flattened to remove the nested collection. The argument map allows duplicate cookie names to appear in order to detect configuration errors which would otherwise not be found during argument injection e.g. trying to set a session identifier cookie as both SameSite=Strict and SameSite=None. Instead, duplicates are detected here, throwing a terminating `IllegalArgumentException` if found.

Parameters:
  `map` - the map of same-site attribute values to cookie names
Since:
  9.2.0

### getSameSiteCondition

@Nonnull public Predicate<HttpServletRequest> getSameSiteCondition()
Gets the condition controlling application of SameSite.

Returns:
  condition
Since:
  9.2.0

### setSameSiteCondition

public void setSameSiteCondition(@Nonnull Predicate<HttpServletRequest> condition)
Sets the condition controlling application of SameSite.

Defaults to true.

Parameters:
  `condition` - condition to set
Since:
  9.2.0

### getCookieAttributes

@Nonnull @NotLive @Unmodifiable public Map<String,String> getCookieAttributes()
Gets additional attributes to apply to the cookie.

Returns:
  additional attributes
Since:
  9.2.0

### setCookieAttributes

public void setCookieAttributes(@Nullable Map<String,String> attributes)
Sets additional attributes to apply to the cookie.

Parameters:
  `attributes` - attributes to apply
Since:
  9.2.0

### getCookieLimit

@NonNegative public int getCookieLimit()
Gets the limit on cookies of a given set when purging.

Returns:
  the limit or 0 for unlimited
Since:
  9.2.0

### setCookieLimit

public void setCookieLimit(@NonNegative int limit)
Sets the limit on cookies of a given set when purging.

Defaults to 0, no limit.

Parameters:
  `limit` - limit to set or 0 for unlimited
Since:
  9.2.0

### doInitialize

protected void doInitialize() throws ComponentInitializationException
Performs the initialization of the component. This method is executed within the lock on the object being initialized. The default implementation of this method is a no-op.

Overrides:
  `doInitialize` in class `AbstractInitializableComponent`
Throws:
  `ComponentInitializationException` - thrown if there is a problem initializing the component

### addCookie

public void addCookie(@Nonnull @NotEmpty String name, @Nonnull @NotEmpty String value)
Add a cookie with the specified attributes.

Parameters:
  `name` - name of cookie
  `value` - value of cookie

### addCookie

public void addCookie(@Nonnull @NotEmpty String name, @Nonnull @NotEmpty String value, int overrideMaxAge)
Add a cookie with the specified attributes.

Parameters:
  `name` - name of cookie
  `value` - value of cookie
  `overrideMaxAge` - max-age value to use
Since:
  9.1.0

### addCookie

public void addCookie(@Nonnull @NotEmpty String name, @Nonnull @NotEmpty String value, @Nullable @NotEmpty String overridePath, int overrideMaxAge)
Add a cookie with the specified attributes.

Parameters:
  `name` - name of cookie
  `value` - value of cookie
  `overridePath` - path value tp use
  `overrideMaxAge` - max-age value to use
Since:
  9.2.0

### unsetCookie

public void unsetCookie(@Nonnull @NotEmpty String name)
Unsets a cookie with the specified name and the default path.

Parameters:
  `name` - name of cookie

### unsetCookie

public void unsetCookie(@Nonnull @NotEmpty String name, @Nullable @NotEmpty String overridePath)
Unsets a cookie with the specified name and path.

Parameters:
  `name` - name of cookie
  `overridePath` - cookie path

### cookieHasValue

public boolean cookieHasValue(@Nonnull @NotEmpty String name, @Nonnull @NotEmpty String expectedValue)
Check whether a cookie has a certain value.

Parameters:
  `name` - name of cookie
  `expectedValue` - expected value of cookie
Returns:
  true iff the cookie exists and has the expected value

### getCookieValue

@Nullable public String getCookieValue(@Nonnull @NotEmpty String name, @Nullable String defValue)
Return the first matching cookie's value.

Parameters:
  `name` - cookie name
  `defValue` - default value to return if the cookie isn't found
Returns:
  cookie value

### purgeStaleCookies

public void purgeStaleCookies(@Nonnull @NotEmpty String prefix)
Unset cookies matching a given prefix in excess of the configured amount.

Parameters:
  `prefix` - cookie name prefix to match on
Since:
  9.2.0

### purgeStaleCookies

public void purgeStaleCookies(@Nonnull @NotEmpty String prefix, @Nullable @NotEmpty String overridePath)
Unset cookies matching a given prefix in excess of the configured amount.

Parameters:
  `prefix` - cookie name prefix to match on
  `overridePath` - cookie path
Since:
  9.2.0

### attachSameSite

private void attachSameSite(@Nonnull Cookie cookie)
Implementation of SameSite attachment logic when available.

Parameters:
  `cookie` - cookie to attach attribute to

### contextPathToCookiePath

@Nonnull @NotEmpty private String contextPathToCookiePath()
Turn the servlet context path into an appropriate cookie path.

Returns:
  the cookie path