JPA Ticket Registry
The JPA Ticket Registry allows CAS to store tickets in a relational database back-end such as MySQL.
Using a relational database as the back-end persistence choice for ticket registry state management can be complicated. Unless you are already outfitted with clustered database technology and the resources to manage it, the complexity is usually not worth the trouble.
Support is enabled by adding the following module into the overlay:
1
2
3
4
5
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-support-jpa-ticket-registry</artifactId>
<version>${cas.version}</version>
</dependency>
1
implementation "org.apereo.cas:cas-server-support-jpa-ticket-registry:${project.'cas.version'}"
1
2
3
4
5
6
7
8
9
dependencyManagement {
imports {
mavenBom "org.apereo.cas:cas-server-support-bom:${project.'cas.version'}"
}
}
dependencies {
implementation "org.apereo.cas:cas-server-support-jpa-ticket-registry"
}
1
2
3
4
5
6
7
8
9
10
dependencies {
/*
The following platform references are included automatically and are listed for reference only.
implementation enforcedPlatform("org.apereo.cas:cas-server-support-bom:${project.'cas.version'}")
implementation platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES)
*/
implementation "org.apereo.cas:cas-server-support-jpa-ticket-registry"
}
Configuration
The following settings and properties are available from the CAS configuration catalog:
cas.ticket.registry.jpa.crypto.encryption.keyThe encryption key.
The encryption key. The encryption key by default and unless specified otherwise must be randomly-generated string whose length is defined by the encryption key size setting.
cas.ticket.registry.jpa.crypto.signing.keyThe signing key is a string whose length is defined by the signing key size setting.
The signing key is a string whose length is defined by the signing key size setting.
cas.ticket.registry.jpa.driver-classThe JDBC driver used to connect to the database.
org.hsqldb.jdbcDriverThe JDBC driver used to connect to the database.
cas.ticket.registry.jpa.enabledWhether managing tickets via JPA is enabled.
trueWhether managing tickets via JPA is enabled.
cas.ticket.registry.jpa.passwordThe database connection password.
The database connection password.
cas.ticket.registry.jpa.urlThe database connection URL.
jdbc:hsqldb:mem:cas-hsql-databaseThe database connection URL.
cas.ticket.registry.jpa.userThe database user.
saThe database user.
The database user must have sufficient permissions to be able to handle schema changes and updates, when needed.
cas.ticket.registry.jpa.autocommitThe default auto-commit behavior of connections in the pool.
falseThe default auto-commit behavior of connections in the pool. Determined whether queries such as update/insert should be immediately executed without waiting for an underlying transaction.
cas.ticket.registry.jpa.batch-sizeA non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5 and 30.
100A non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5 and 30.
cas.ticket.registry.jpa.connection-timeoutIndicates the maximum number of milliseconds that the service can wait to obtain a connection.
PT30SIndicates the maximum number of milliseconds that the service can wait to obtain a connection.
cas.ticket.registry.jpa.crypto.algThe signing/encryption algorithm to use.
AESThe signing/encryption algorithm to use.
cas.ticket.registry.jpa.crypto.enabledWhether crypto operations are enabled.
trueWhether crypto operations are enabled.
cas.ticket.registry.jpa.crypto.encryption.key-sizeEncryption key size.
16Encryption key size.
cas.ticket.registry.jpa.crypto.signing-enabledWhether signing encryption operations are enabled.
trueWhether signing encryption operations are enabled.
cas.ticket.registry.jpa.crypto.signing.key-sizeThe signing key size.
512The signing key size.
cas.ticket.registry.jpa.data-source-nameAttempts to do a JNDI data source look up for the data source name specified.
Attempts to do a JNDI data source look up for the data source name specified. Will attempt to locate the data source object as is.
cas.ticket.registry.jpa.ddl-autoHibernate feature to automatically validate and exports DDL to the schema.
updatevalidate or none may be more desirable for production, but any of the following options can be used: -
validate: Validate the schema, but make no changes to the database. -
update: Update the schema. -
create: Create the schema, destroying previous data. -
create-drop: Drop the schema at the end of the session. -
none: Do nothing.
Note that during a version migration where any schema has changed create-drop will result in the loss of all data as soon as CAS is started. For transient data like tickets this is probably not an issue, but in cases like the audit table important data could be lost. Using `update`, while safe for data, is confirmed to result in invalid database state. validate or none settings are likely the only safe options for production use.
For more info, see this.
cas.ticket.registry.jpa.default-catalogQualifies unqualified table names with the given catalog in generated SQL.
Qualifies unqualified table names with the given catalog in generated SQL.
cas.ticket.registry.jpa.default-schemaQualify unqualified table names with the given schema/tablespace in generated SQL.
Qualify unqualified table names with the given schema/tablespace in generated SQL.
cas.ticket.registry.jpa.dialectThe database dialect is a configuration setting for platform independent software (JPA, Hibernate, etc) which allows such software to translate its generic SQL statements into vendor specific DDL, DML.
org.hibernate.dialect.HSQLDialectThe database dialect is a configuration setting for platform independent software (JPA, Hibernate, etc) which allows such software to translate its generic SQL statements into vendor specific DDL, DML.
cas.ticket.registry.jpa.fail-fast-timeoutSet the pool initialization failure timeout.
1- Any value greater than zero will be treated as a timeout for pool initialization. The calling thread will be blocked from continuing until a successful connection to the database, or until the timeout is reached. If the timeout is reached, then a
PoolInitializationExceptionwill be thrown. - A value of zero will not prevent the pool from starting in the case that a connection cannot be obtained. However, upon start the pool will attempt to obtain a connection and validate that the
connectionTestQueryandconnectionInitSqlare valid. If those validations fail, an exception will be thrown. If a connection cannot be obtained, the validation is skipped and the pool will start and continue to try to obtain connections in the background. This can mean that callers toDataSource#getConnection()may encounter exceptions. - A value less than zero will not bypass any connection attempt and validation during startup, and therefore the pool will start immediately. The pool will continue to try to obtain connections in the background. This can mean that callers to
DataSource#getConnection()may encounter exceptions.
connectionTimeout or validationTimeout; they will be honored before this timeout is applied. The default value is one millisecond.cas.ticket.registry.jpa.fetch-sizeUsed to specify number of rows to be fetched in a select query.
100Used to specify number of rows to be fetched in a select query.
cas.ticket.registry.jpa.generate-statisticsAllow hibernate to generate query statistics.
falseAllow hibernate to generate query statistics.
cas.ticket.registry.jpa.health-queryThe SQL query to be executed to test the validity of connections.
The SQL query to be executed to test the validity of connections. This is for "legacy" databases that do not support the JDBC4 Connection.isValid() API.
cas.ticket.registry.jpa.idle-timeoutControls the maximum amount of time that a connection is allowed to sit idle in the pool.
PT10MControls the maximum amount of time that a connection is allowed to sit idle in the pool.
cas.ticket.registry.jpa.isolate-internal-queriesThis property determines whether data source isolates internal pool queries, such as the connection alive test, in their own transaction.
falseThis property determines whether data source isolates internal pool queries, such as the connection alive test, in their own transaction.
Since these are typically read-only queries, it is rarely necessary to encapsulate them in their own transaction. This property only applies if #autocommit is disabled.
cas.ticket.registry.jpa.isolation-level-nameDefines the isolation level for transactions.
ISOLATION_READ_COMMITTEDDefines the isolation level for transactions. @see org.springframework.transaction.TransactionDefinition
cas.ticket.registry.jpa.jpa-locking-timeoutIndicates the lock duration when one is about to be acquired by the cleaner.
PT1HIndicates the lock duration when one is about to be acquired by the cleaner.
cas.ticket.registry.jpa.leak-thresholdControls the amount of time that a connection can be out of the pool before a message is logged indicating a possible connection leak.
PT6SControls the amount of time that a connection can be out of the pool before a message is logged indicating a possible connection leak.
cas.ticket.registry.jpa.physical-naming-strategy-class-nameFully-qualified name of the class that can control the physical naming strategy of hibernate.
org.apereo.cas.hibernate.CasHibernatePhysicalNamingStrategyFully-qualified name of the class that can control the physical naming strategy of hibernate.
cas.ticket.registry.jpa.pool.keep-alive-timeThis property controls the keepalive interval for a connection in the pool.
0This property controls the keepalive interval for a connection in the pool. An in-use connection will never be tested by the keepalive thread, only when it is idle will it be tested. Default is zero, which disables this feature.
cas.ticket.registry.jpa.pool.max-sizeControls the maximum number of connections to keep in the pool, including both idle and in-use connections.
18Controls the maximum number of connections to keep in the pool, including both idle and in-use connections.
cas.ticket.registry.jpa.pool.max-waitSets the maximum time in seconds that this data source will wait while attempting to connect to a database.
PT2SSets the maximum time in seconds that this data source will wait while attempting to connect to a database.
A value of zero specifies that the timeout is the default system timeout if there is one; otherwise, it specifies that there is no timeout.
cas.ticket.registry.jpa.pool.maximum-lifetimeThis property controls the maximum lifetime of a connection in the pool.
PT10MThis property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed.
cas.ticket.registry.jpa.pool.min-sizeControls the minimum size that the pool is allowed to reach, including both idle and in-use connections.
6Controls the minimum size that the pool is allowed to reach, including both idle and in-use connections.
cas.ticket.registry.jpa.pool.nameSet the name of the connection pool.
Set the name of the connection pool. This is primarily used for the MBean to uniquely identify the pool configuration.
cas.ticket.registry.jpa.pool.suspensionWhether or not pool suspension is allowed.
falseWhether or not pool suspension is allowed.
There is a performance impact when pool suspension is enabled. Unless you need it (for a redundancy system for example) do not enable it.
cas.ticket.registry.jpa.pool.timeout-millisThe maximum number of milliseconds that the pool will wait for a connection to be validated as alive.
1000The maximum number of milliseconds that the pool will wait for a connection to be validated as alive.
cas.ticket.registry.jpa.propagation-behavior-nameDefines the propagation behavior for transactions.
PROPAGATION_REQUIREDDefines the propagation behavior for transactions. @see org.springframework.transaction.TransactionDefinition
cas.ticket.registry.jpa.propertiesAdditional settings provided by Hibernate (or the connection provider) in form of key-value pairs.
Additional settings provided by Hibernate (or the connection provider) in form of key-value pairs.
cas.ticket.registry.jpa.read-onlyConfigures the Connections to be added to the pool as read-only Connections.
falseConfigures the Connections to be added to the pool as read-only Connections.
cas.ticket.registry.jpa.ticket-lock-typeTicket locking type.
NONETicket locking type. Acceptable values are READ,WRITE,OPTIMISTIC,OPTIMISTIC_FORCE_INCREMENT,PESSIMISTIC_READ, PESSIMISTIC_WRITE,PESSIMISTIC_FORCE_INCREMENT,NONE.
Required settings may be needed to activate or affect the feature; review them even when they have a default. Optional settings only need to be set to change a default or to turn on the behavior they control. Third party settings belong to libraries such as Spring Boot that CAS builds on; their own documentation may have more detail.
Signing & encryption
This CAS feature is able to accept signing and encryption crypto keys. In most scenarios if keys are not provided, CAS will auto-generate them. The following instructions apply if you wish to manually and beforehand create the signing and encryption keys.
Note that if you are asked to create a JWK of a certain size for the key, you are to use the following set of commands to generate the token:
1
2
wget https://raw.githubusercontent.com/apereo/cas/master/etc/jwk-gen.jar
java -jar jwk-gen.jar -t oct -s [size]
The outcome would be similar to:
1
2
3
4
5
{
"kty": "oct",
"kid": "...",
"k": "..."
}
The generated value for k needs to be assigned to the relevant CAS settings. Note that keys generated via
the above algorithm are processed by CAS using the Advanced Encryption Standard (AES) algorithm which is a
specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology.
Hibernate & JDBC
Control global properties that are relevant to Hibernate, when CAS attempts to employ and utilize database resources, connections and queries.
cas.jdbc.gen-ddlWhether to generate DDL after the EntityManagerFactory has been initialized creating/updating all relevant tables.
trueWhether to generate DDL after the EntityManagerFactory has been initialized creating/updating all relevant tables.
cas.jdbc.physical-table-namesIndicate a physical table name to be used by the hibernate naming strategy in case table names need to be customized for the specific type of database.
Indicate a physical table name to be used by the hibernate naming strategy in case table names need to be customized for the specific type of database. The key here indicates the CAS-provided table name and the value is the translate physical name for the database. If a match is not found for the CAS-provided table name, then that name will be used by default.
cas.jdbc.show-sqlWhether SQL queries should be displayed in the console/logs.
falseWhether SQL queries should be displayed in the console/logs.
Notes on configuration
Configuration Metadata
The collection of configuration properties listed in this section are automatically generated from the CAS source and components that contain the actual field definitions, types, descriptions, modules, etc. This metadata may not always be 100% accurate, or could be lacking details and sufficient explanations.
Be Selective
This section is meant as a guide only. Do NOT copy/paste the entire collection of settings into your CAS configuration; rather pick only the properties that you need. Do NOT enable settings unless you are certain of their purpose and do NOT copy settings into your configuration only to keep them as reference. All these ideas lead to upgrade headaches, maintenance nightmares and premature aging.
YAGNI
Note that for nearly ALL use cases, declaring and configuring properties listed here is sufficient. You should NOT have to explicitly massage a CAS XML/Java/etc configuration file to design an authentication handler, create attribute release policies, etc. CAS at runtime will auto-configure all required changes for you. If you are unsure about the meaning of a given CAS setting, do NOT turn it on without hesitation. Review the codebase or better yet, ask questions to clarify the intended behavior.
Naming Convention
Property names can be specified in very relaxed terms. For instance cas.someProperty, cas.some-property, cas.some_property are all valid names. While all
forms are accepted by CAS, there are certain components (in CAS and other frameworks used) whose activation at runtime is conditional on a property value, where
this property is required to have been specified in CAS configuration using kebab case. This is both true for properties that are owned by CAS as well as those
that might be presented to the system via an external library or framework such as Spring Boot, etc.
When possible, properties should be stored in lower-case kebab format, such as cas.property-name=value.
The only possible exception to this rule is when naming actuator endpoints; The name of the
actuator endpoints (i.e. ssoSessions) MUST remain in camelCase mode.
Settings and properties that are controlled by the CAS platform directly always begin with the prefix cas. All other settings are controlled and provided
to CAS via other underlying frameworks and may have their own schemas and syntax. BE CAREFUL with
the distinction. Unrecognized properties are rejected by CAS and/or frameworks upon which CAS depends. This means if you somehow misspell a property definition
or fail to adhere to the dot-notation syntax and such, your setting is entirely refused by CAS and likely the feature it controls will never be activated in the
way you intend.
Validation
Configuration properties are automatically validated on CAS startup to report issues with configuration binding, especially if defined CAS settings cannot be recognized or validated by the configuration schema. Additional validation processes are also handled via Configuration Metadata and property migrations applied automatically on startup by Spring Boot and family.
Indexed Settings
CAS settings able to accept multiple values are typically documented with an index, such as cas.some.setting[0]=value. The index [0] is meant to be
incremented by the adopter to allow for distinct multiple configuration blocks.
New deployments of CAS, and upgrades to a new CAS version, should always start with a clean ticket registry table: drop the existing table and let CAS create it. Schema updates add missing tables, columns and indexes, but they do not change the type or length of an existing column, so a table created by an earlier version can keep a schema that the current version does not expect. Tickets are short-lived, and dropping the table only ends the single sign-on sessions it holds.
Expiration
Each ticket row stores the time the ticket expires unless it is used again: the earlier of its maximum and its idle expiration time, or the time it was saved for a ticket that was already expired, such as one marked expired. The row is rewritten each time the ticket is updated, so the idle expiration follows its last use. The column is indexed, and the ticket registry cleaner reads only the rows whose time has passed, apart from a full scan at startup and hourly. Rows written by earlier versions hold the maximum expiration time; they are caught by those full scans until their tickets are next updated. Schema updates add the index to an existing table; with schema generation turned off, create it by hand:
1
CREATE INDEX idx_ticket_expiration ON cas_tickets (expiration_time);
MySQL
To scan large tables without reading every row into memory, CAS sets useCursorFetch=true for MySQL, together with
cachePrepStmts=true, prepStmtCacheSize=250 and prepStmtCacheSqlLimit=2048, unless the
additional JPA properties of the ticket registry or the JDBC URL already set them. Connector/J uses a
server-side cursor only for statements with a fetch size, so CAS applies the configured
fetch size only to queries that stream tickets, such as the cleaner’s scan;
single-ticket lookups read their row directly. With useCursorFetch, Connector/J prepares every statement on the
server, and the prepared statement cache keeps that to one round trip per lookup.
MySQL limits an index key to 3072 bytes, which with the utf8mb4 character set is 768 characters. On MySQL the
ticket table therefore declares type as VARCHAR(255), principal_id as VARCHAR(512) and parent_id as
VARCHAR(768), so that its indexes on the principal, the parent ticket and the ticket type with the principal can be
created; the service column keeps its length and is not indexed on MySQL. Tables created by earlier versions
declared longer columns, and MySQL refused every one of those indexes, so lookups by principal or parent ticket scanned
the whole table. Schema updates do not shorten existing columns: start with a clean table, as recommended above, or
apply the change to the existing table by hand:
1
2
3
4
5
6
7
ALTER TABLE cas_tickets
MODIFY type VARCHAR(255) NOT NULL,
MODIFY principal_id VARCHAR(512),
MODIFY parent_id VARCHAR(768);
CREATE INDEX idx_ticket_principal ON cas_tickets (principal_id);
CREATE INDEX idx_ticket_parent ON cas_tickets (parent_id);
CREATE INDEX idx_type_principal ON cas_tickets (type, principal_id);
The ticket table no longer declares an index on type alone, since the index on the ticket type and the principal
serves the same queries. Schema updates do not drop indexes either; an existing idx_ticket_type can be removed with
DROP INDEX idx_ticket_type ON cas_tickets (or DROP INDEX idx_ticket_type where indexes are not scoped to a table).
PostgreSQL
On PostgreSQL, ticket attributes are stored as jsonb, so that finding single sign-on sessions by attribute, as
delegated OpenID Connect and SAML2 logout do, can be answered by a GIN index rather than by reading every session.
JPA cannot declare a GIN index, and CAS does not create it. The index is required and must be created manually: the
administrator runs the statement below once, after the ticket table has been created. Without it, those lookups still
work but read the whole table.
1
CREATE INDEX IF NOT EXISTS idx_ticket_attributes ON cas_tickets USING GIN (attributes jsonb_path_ops);
The index is part of the table, so it is needed again whenever the table is dropped and recreated, such as when starting with a clean table as recommended above.
Tables created by earlier versions declare the column as json, which schema updates do not change, and session lookups
by attribute then fail. Start with a clean table, as recommended above, or convert the column first, which rewrites
the table and locks it while it runs:
1
ALTER TABLE cas_tickets ALTER COLUMN attributes TYPE jsonb USING attributes::jsonb;
Ticket Registry Locking
This ticket registry implementation automatically supports distributed locking.
The tables that track locking operations come from Spring Integration JDBC support.
Spring Integration only creates them on its own for embedded databases; for any other database, either create them
up front from the schema scripts that ship with Spring Integration, or let CAS create them on startup by setting the
Spring Integration JDBC schema initialization mode to always.
Without these tables, every attempt to lock a ticket fails, and CAS cannot issue service tickets.
The following settings and properties are available from the CAS configuration catalog:
spring.integration.jdbc.continue-on-errorWhether initialization should continue when an error occurs when applying a schema script.
trueWhether initialization should continue when an error occurs when applying a schema script.
spring.integration.jdbc.initialize-schemaDatabase schema initialization mode.
embeddedDatabase schema initialization mode.
spring.integration.jdbc.platformPlatform to use in initialization scripts if the @@platform@@ placeholder is used.
Platform to use in initialization scripts if the @@platform@@ placeholder is used. Auto-detected by default.
spring.integration.jdbc.schemaPath to the SQL file to use to initialize the database schema.
Path to the SQL file to use to initialize the database schema.
Required settings may be needed to activate or affect the feature; review them even when they have a default. Optional settings only need to be set to change a default or to turn on the behavior they control. Third party settings belong to libraries such as Spring Boot that CAS builds on; their own documentation may have more detail.
Hibernate & JDBC
Control global properties that are relevant to Hibernate, when CAS attempts to employ and utilize database resources, connections and queries.
cas.jdbc.gen-ddlWhether to generate DDL after the EntityManagerFactory has been initialized creating/updating all relevant tables.
trueWhether to generate DDL after the EntityManagerFactory has been initialized creating/updating all relevant tables.
cas.jdbc.physical-table-namesIndicate a physical table name to be used by the hibernate naming strategy in case table names need to be customized for the specific type of database.
Indicate a physical table name to be used by the hibernate naming strategy in case table names need to be customized for the specific type of database. The key here indicates the CAS-provided table name and the value is the translate physical name for the database. If a match is not found for the CAS-provided table name, then that name will be used by default.
cas.jdbc.show-sqlWhether SQL queries should be displayed in the console/logs.
falseWhether SQL queries should be displayed in the console/logs.
Notes on configuration
Configuration Metadata
The collection of configuration properties listed in this section are automatically generated from the CAS source and components that contain the actual field definitions, types, descriptions, modules, etc. This metadata may not always be 100% accurate, or could be lacking details and sufficient explanations.
Be Selective
This section is meant as a guide only. Do NOT copy/paste the entire collection of settings into your CAS configuration; rather pick only the properties that you need. Do NOT enable settings unless you are certain of their purpose and do NOT copy settings into your configuration only to keep them as reference. All these ideas lead to upgrade headaches, maintenance nightmares and premature aging.
YAGNI
Note that for nearly ALL use cases, declaring and configuring properties listed here is sufficient. You should NOT have to explicitly massage a CAS XML/Java/etc configuration file to design an authentication handler, create attribute release policies, etc. CAS at runtime will auto-configure all required changes for you. If you are unsure about the meaning of a given CAS setting, do NOT turn it on without hesitation. Review the codebase or better yet, ask questions to clarify the intended behavior.
Naming Convention
Property names can be specified in very relaxed terms. For instance cas.someProperty, cas.some-property, cas.some_property are all valid names. While all
forms are accepted by CAS, there are certain components (in CAS and other frameworks used) whose activation at runtime is conditional on a property value, where
this property is required to have been specified in CAS configuration using kebab case. This is both true for properties that are owned by CAS as well as those
that might be presented to the system via an external library or framework such as Spring Boot, etc.
When possible, properties should be stored in lower-case kebab format, such as cas.property-name=value.
The only possible exception to this rule is when naming actuator endpoints; The name of the
actuator endpoints (i.e. ssoSessions) MUST remain in camelCase mode.
Settings and properties that are controlled by the CAS platform directly always begin with the prefix cas. All other settings are controlled and provided
to CAS via other underlying frameworks and may have their own schemas and syntax. BE CAREFUL with
the distinction. Unrecognized properties are rejected by CAS and/or frameworks upon which CAS depends. This means if you somehow misspell a property definition
or fail to adhere to the dot-notation syntax and such, your setting is entirely refused by CAS and likely the feature it controls will never be activated in the
way you intend.
Validation
Configuration properties are automatically validated on CAS startup to report issues with configuration binding, especially if defined CAS settings cannot be recognized or validated by the configuration schema. Additional validation processes are also handled via Configuration Metadata and property migrations applied automatically on startup by Spring Boot and family.
Indexed Settings
CAS settings able to accept multiple values are typically documented with an index, such as cas.some.setting[0]=value. The index [0] is meant to be
incremented by the adopter to allow for distinct multiple configuration blocks.