# Ticket-Granting Ticket REST Protocol

Source: https://apereo.github.io/cas/development/protocol/REST-Protocol-Request-TicketGrantingTicket.html

Ticket-granting tickets can be issued by the REST protocol:

```bash
POST /cas/v1/tickets HTTP/1.0
'Content-type': 'Application/x-www-form-urlencoded'
username=battags&password=password&additionalParam1=paramvalue
```

You may also specify a `service` parameter to verify whether the authenticated user may be allowed to access the given service.

## Successful Response

```bash
201 Created
Location: http://www.whatever.com/cas/v1/tickets/{TGT id}
```

Remember that REST is stateless. Since the caller is the recipient of the ticket-granting ticket that represents a single sign-on session, that means the caller is also responsible for managing and creating single sign-on sessions, removing that responsibility from CAS. In other words, the REST protocol allows one to use CAS as an authentication engine, and not a single sign-on provider. There have been many workarounds, modifications and *hacks* over the years to bypass this barrier and have REST calls to also, *somehow*, create the necessary cookies, flows and interactions and whatever else necessary to allow applications to leverage a single sign-on session established via REST. Needless to say, all such endeavors over time have resulted in maintenance headaches, premature aging and loss of DNA.

## Unsuccessful Response

If incorrect credentials are sent, CAS will respond with a `401 Unauthorized`. A `400 Bad Request` error will be sent for missing parameters, etc. If you send a media type it does not understand, it will send the `415 Unsupported Media Type`.

## JWT Ticket Granting Tickets

Ticket-granting tickets created by the REST protocol may be issued as JWTs instead. Support is enabled by including the following in your overlay:

```groovy
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-rest-tokens"
}
```

To request a ticket-granting ticket as JWT next, ensure the `POST` request matches the following:

```bash
POST /cas/v1/tickets HTTP/1.0

username=battags&password=password&token=true&additionalParam1=paramvalue
```

The `token` parameter may either be passed as a request parameter or a request header. The body of the response will include the ticket-granting ticket as a JWT. Note that JWTs created are typically signed and encrypted by default with pre-generated keys.

The following settings and properties are available from the CAS configuration catalog:

- `cas.authn.token.crypto.encryption.key` (Required; type `String`): The encryption key is a string whose length is defined by the encryption key size setting.
- `cas.authn.token.crypto.signing.key` (Required; type `String`): The signing key is a string whose length is defined by the signing key size setting.
- `cas.authn.token.credential-criteria` (Optional; type `String`): A number of authentication handlers are allowed to determine whether they can operate on the provided credential and as such lend themselves to be tried and tested during the authentication handler selection phase. The credential criteria may be one of the following options: - 1) A regular expression pattern that is tested against the credential identifier. - 2) A fully qualified class name of your own design that implements `Predicate`. - 3) Path to an external Groovy script that implements the same interface.
- `cas.authn.token.crypto.alg` (Optional; type `String`): The signing/encryption algorithm to use.
- `cas.authn.token.crypto.enabled` (Optional; type `Boolean`; default `true`): Whether crypto operations are enabled.
- `cas.authn.token.crypto.encryption-enabled` (Optional; type `Boolean`; default `true`): Whether crypto encryption operations are enabled.
- `cas.authn.token.crypto.encryption.key-size` (Optional; type `Integer`; default `512`): The encryption key size.
- `cas.authn.token.crypto.signing-enabled` (Optional; type `Boolean`; default `true`): Whether crypto signing operations are enabled.
- `cas.authn.token.crypto.signing.key-size` (Optional; type `Integer`; default `512`): The signing key size.
- `cas.authn.token.crypto.strategy-type` (Optional; type `String`; default `ENCRYPT_AND_SIGN`): Control the cipher sequence of operations. The accepted values are: - `ENCRYPT_AND_SIGN`: Encrypt the value first, and then sign. - `SIGN_AND_ENCRYPT`: Sign the value first, and then encrypt.
- `cas.authn.token.name` (Optional; type `String`): Name of the authentication handler.
- `cas.authn.token.order` (Optional; type `Integer`): Order of the authentication handler in the chain.
- `cas.authn.token.sso-token-enabled` (Optional; type `Boolean`; default `false`): When set to true, will generate a token and store it as an authentication attribute into the single sign-on session. This token can be used later on for token-based authentication attempts, and should allow SSO access to the server.
- `cas.authn.token.state` (Optional; type `AuthenticationHandlerStates`; default `active`): Define the scope and state of this authentication handler and the lifecycle in which it can be invoked or activated. Available values are as follows: - `ACTIVE`: Active authentication handler, and is invoked by default automatically to verify credentials globally. - `STANDBY`: Authentication handler is in a semi-enabled state, waiting to be called only on-demand when explicitly asked for.
- `cas.authn.token.webflow.enabled` (Optional; type `Boolean`; default `true`): Whether webflow auto-configuration should be enabled.
- `cas.authn.token.webflow.order` (Optional; type `Integer`; default `0`): The order in which the webflow is configured.

**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](https://tools.ietf.org/html/rfc7517) of a certain size for the key, you are to use the following set of commands to generate the token:

```bash
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:

```json
{
  "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.

---

**Authentication**

Certain authentication handlers are allowed to determine whether they can operate on the provided credential and as such lend themselves to be tried and tested during the authentication handler selection phase. The credential criteria may be one of the following options:

- A regular expression pattern that is tested against the credential identifier.
- A fully qualified class name of your own design that looks similar to the below example:

```java
import java.util.function.Predicate;
import org.apereo.cas.authentication.Credential;

public class PredicateExample implements Predicate<Credential> {
    @Override
    public boolean test(final Credential credential) {
        // Examine the credential and return true/false
    }
}
```

- Path to an external Groovy script that looks similar to the below example:

```groovy
import org.apereo.cas.authentication.Credential
import java.util.function.Predicate

class PredicateExample implements Predicate<Credential> {
    @Override
    boolean test(final Credential credential) {
        // test and return result
    }
}
```

To prepare CAS to support and integrate with Apache Groovy, please [review this guide](https://apereo.github.io/cas/development//integration/Apache-Groovy-Scripting.html).

## X509 Authentication

The feature extends the CAS REST API communication model to non-interactive X.509 authentication where REST credentials may be retrieved from a certificate embedded in the request rather than the usual and default username/password.

This pattern may be of interest in cases where the internal network architecture hides the CAS server from external users behind firewall, reverse proxy, or a messaging bus and allows only trusted applications to connect directly to the CAS server.

> **Usage Warning!**
>
> The X.509 feature over REST using a body parameter or a http header provides a tremendously convenient target for claiming user identities or obtaining TGTs without proof of private key ownership. To securely use this feature, network configuration **MUST** allow connections to the CAS server only from trusted hosts which in turn have strict security limitations and logging. It is also recommended to make sure that the body parameter or the http header can only come from trusted hosts and not from the original authenticating client.

It is also possible to let the servlet container validate the TLS client key / X.509 certificate during TLS handshake, and have CAS server retrieve the certificate from the container.

Support is enabled by including the following in your overlay:

```groovy
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-rest-x509"
}
```

The following settings and properties are available from the CAS configuration catalog:

- `cas.rest.x509.body-auth` (Optional; type `Boolean`; default `false`): Flag that enables `java.security.cert.X509Certificate` extraction from the request body for authentication.
- `cas.rest.x509.header-auth` (Optional; type `Boolean`; default `true`): Flag that enables `java.security.cert.X509Certificate` extraction from the request headers for authentication.
- `cas.rest.x509.tls-client-auth` (Optional; type `Boolean`; default `false`): Flag that enables TLS client `java.security.cert.X509Certificate` extraction from the servlet container for authentication.

### Body Parameter

```bash
POST /cas/v1/tickets HTTP/1.0
cert=<ascii certificate>
```
