├── src ├── main │ ├── resources │ │ └── META-INF │ │ │ └── services │ │ │ ├── org.keycloak.broker.provider.IdentityProviderFactory │ │ │ └── org.keycloak.broker.provider.IdentityProviderMapper │ └── java │ │ └── io │ │ └── github │ │ └── johnjcool │ │ └── keycloak │ │ └── broker │ │ └── cas │ │ ├── model │ │ ├── Code.java │ │ ├── Failure.java │ │ ├── ServiceResponse.java │ │ └── Success.java │ │ ├── jaxb │ │ ├── AttributesAdapter.java │ │ └── AttributesWrapper.java │ │ ├── mappers │ │ ├── AbstractAttributeMapper.java │ │ ├── AttributeToRoleMapper.java │ │ └── UserAttributeMapper.java │ │ ├── CasIdentityProviderConfig.java │ │ ├── CasIdentityProviderFactory.java │ │ ├── util │ │ └── UrlHelper.java │ │ └── CasIdentityProvider.java └── test │ └── java │ └── io │ └── github │ └── johnjcool │ └── keycloak │ └── broker │ └── cas │ └── model │ └── ServiceResponseTest.java ├── .editorconfig ├── .gitignore ├── .github ├── matchers.json └── workflows │ └── maven.yml ├── README.md ├── renovate.json ├── pom.xml └── LICENSE.md /src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderFactory: -------------------------------------------------------------------------------- 1 | io.github.johnjcool.keycloak.broker.cas.CasIdentityProviderFactory -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | indent_style = space 7 | indent_size = 2 8 | trim_trailing_whitespace = true 9 | 10 | [pom.xml] 11 | indent_style = tab 12 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderMapper: -------------------------------------------------------------------------------- 1 | io.github.johnjcool.keycloak.broker.cas.mappers.UserAttributeMapper 2 | io.github.johnjcool.keycloak.broker.cas.mappers.AttributeToRoleMapper -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/model/Code.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.model; 2 | 3 | public enum Code { 4 | INVALID_REQUEST, 5 | INVALID_TICKET_SPEC, 6 | UNAUTHORIZED_SERVICE_PROXY, 7 | INVALID_PROXY_CALLBACK, 8 | INVALID_TICKET, 9 | INVALID_SERVICE, 10 | INTERNAL_ERROR; 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | /derby.log 26 | -------------------------------------------------------------------------------- /.github/matchers.json: -------------------------------------------------------------------------------- 1 | { 2 | "problemMatcher": [ 3 | { 4 | "owner": "fmt-maven-plugin", 5 | "pattern": [ 6 | { 7 | "regexp": "^\\[([A-Z]{5})\\] ([a-zA-Z ]+): \\/home\\/runner\\/work\\/keycloak-cas\\/keycloak-cas\\/([a-zA-Z0-9-\\.\\/]+)$", 8 | "severity": 1, 9 | "message": 2, 10 | "file": 3 11 | } 12 | ] 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # keycloak-cas 2 | CAS identity provider for Keycloak 3 | 4 | > [!NOTE] 5 | > This package is actively maintained and used in production with the latest Keycloak release. However, we do not currently publish pre-built packages for external use. 6 | 7 | ## Local development 8 | Make sure you have the following installed: 9 | - Java 21 (needs to match `maven.compiler.source`/`maven.compiler.target` in `pom.xml`) 10 | - Maven 11 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ], 5 | "prConcurrentLimit": 1, 6 | "prHourlyLimit": 0, 7 | "rebaseStalePrs": true, 8 | "automerge": true, 9 | "platformAutomerge": true, 10 | "rangeStrategy": "pin", 11 | "customManagers": [ 12 | { 13 | "customType": "regex", 14 | "fileMatch": ["^pom.xml$"], 15 | "matchStrings": ["(?.+)<\\/keycloak\\.version>"], 16 | "depNameTemplate": "org.keycloak:keycloak-parent", 17 | "datasourceTemplate": "maven" 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/jaxb/AttributesAdapter.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.jaxb; 2 | 3 | import jakarta.xml.bind.annotation.adapters.XmlAdapter; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | public class AttributesAdapter extends XmlAdapter>> { 8 | 9 | @Override 10 | public AttributesWrapper marshal(final Map> attributes) { 11 | throw new UnsupportedOperationException("This adapter only supports from xml to map."); 12 | } 13 | 14 | @Override 15 | public Map> unmarshal(final AttributesWrapper attributesWrapper) { 16 | return attributesWrapper.toMap(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/jaxb/AttributesWrapper.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.jaxb; 2 | 3 | import jakarta.xml.bind.annotation.XmlAnyElement; 4 | import jakarta.xml.bind.annotation.XmlType; 5 | import java.util.*; 6 | import java.util.stream.Collectors; 7 | import org.w3c.dom.Node; 8 | 9 | @XmlType 10 | public class AttributesWrapper { 11 | 12 | private final List attributes = new ArrayList<>(); 13 | 14 | @XmlAnyElement 15 | public List getAttributes() { 16 | return attributes; 17 | } 18 | 19 | public Map> toMap() { 20 | return attributes.stream() 21 | .collect( 22 | Collectors.groupingBy( 23 | Node::getLocalName, Collectors.mapping(Node::getTextContent, Collectors.toList()))); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/model/Failure.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.model; 2 | 3 | import jakarta.xml.bind.annotation.XmlAccessType; 4 | import jakarta.xml.bind.annotation.XmlAccessorType; 5 | import jakarta.xml.bind.annotation.XmlAttribute; 6 | import jakarta.xml.bind.annotation.XmlValue; 7 | import java.io.Serial; 8 | import java.io.Serializable; 9 | 10 | @XmlAccessorType(XmlAccessType.FIELD) 11 | public class Failure implements Serializable { 12 | 13 | @Serial private static final long serialVersionUID = 1L; 14 | 15 | @XmlAttribute private Code code; 16 | 17 | @XmlValue private String description; 18 | 19 | public Code getCode() { 20 | return code; 21 | } 22 | 23 | public void setCode(final Code code) { 24 | this.code = code; 25 | } 26 | 27 | public String getDescription() { 28 | return description; 29 | } 30 | 31 | public void setDescription(final String description) { 32 | this.description = description; 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return String.format("Failure [code=%s, description=%s]", code, description); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/model/ServiceResponse.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.model; 2 | 3 | import jakarta.xml.bind.annotation.XmlAccessType; 4 | import jakarta.xml.bind.annotation.XmlAccessorType; 5 | import jakarta.xml.bind.annotation.XmlElement; 6 | import jakarta.xml.bind.annotation.XmlRootElement; 7 | import java.io.Serial; 8 | import java.io.Serializable; 9 | 10 | @XmlAccessorType(XmlAccessType.FIELD) 11 | @XmlRootElement(name = "serviceResponse", namespace = "http://www.yale.edu/tp/cas") 12 | public class ServiceResponse implements Serializable { 13 | 14 | @Serial private static final long serialVersionUID = 1L; 15 | 16 | @XmlElement(name = "authenticationFailure", namespace = "http://www.yale.edu/tp/cas") 17 | private Failure failure; 18 | 19 | @XmlElement(name = "authenticationSuccess", namespace = "http://www.yale.edu/tp/cas") 20 | private Success success; 21 | 22 | public Failure getFailure() { 23 | return failure; 24 | } 25 | 26 | public void setFailure(final Failure failure) { 27 | this.failure = failure; 28 | } 29 | 30 | public Success getSuccess() { 31 | return success; 32 | } 33 | 34 | public void setSuccess(final Success success) { 35 | this.success = success; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return String.format("ServiceResponse [failure=%s, success=%s]", failure, success); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/model/Success.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.model; 2 | 3 | import io.github.johnjcool.keycloak.broker.cas.jaxb.AttributesAdapter; 4 | import jakarta.xml.bind.annotation.XmlAccessType; 5 | import jakarta.xml.bind.annotation.XmlAccessorType; 6 | import jakarta.xml.bind.annotation.XmlElement; 7 | import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; 8 | import java.io.Serial; 9 | import java.io.Serializable; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | @XmlAccessorType(XmlAccessType.FIELD) 15 | public class Success implements Serializable { 16 | 17 | @Serial private static final long serialVersionUID = 1L; 18 | 19 | @XmlElement(name = "user", namespace = "http://www.yale.edu/tp/cas") 20 | private String user; 21 | 22 | @XmlElement(name = "attributes", namespace = "http://www.yale.edu/tp/cas") 23 | @XmlJavaTypeAdapter(AttributesAdapter.class) 24 | private Map> attributes = new HashMap<>(); 25 | 26 | public String getUser() { 27 | return user; 28 | } 29 | 30 | public void setUser(final String user) { 31 | this.user = user; 32 | } 33 | 34 | public Map> getAttributes() { 35 | return attributes; 36 | } 37 | 38 | public void setAttributes(final Map> attributes) { 39 | this.attributes = attributes; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return String.format("Success [user=%s, attributes=%s]", user, attributes); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/mappers/AbstractAttributeMapper.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.mappers; 2 | 3 | import io.github.johnjcool.keycloak.broker.cas.CasIdentityProvider; 4 | import java.util.*; 5 | import org.jboss.logging.Logger; 6 | import org.keycloak.broker.provider.AbstractIdentityProviderMapper; 7 | import org.keycloak.broker.provider.BrokeredIdentityContext; 8 | import org.keycloak.common.util.CollectionUtil; 9 | import org.keycloak.models.IdentityProviderMapperModel; 10 | 11 | public abstract class AbstractAttributeMapper extends AbstractIdentityProviderMapper { 12 | 13 | protected static final Logger logger = Logger.getLogger(AbstractAttributeMapper.class); 14 | 15 | public static final String ATTRIBUTE = "attribute"; 16 | public static final String ATTRIBUTE_VALUE = "attribute.value"; 17 | 18 | public static List getAttributeValue( 19 | final IdentityProviderMapperModel mapperModel, final BrokeredIdentityContext user) { 20 | @SuppressWarnings("unchecked") 21 | Map> userAttributes = 22 | (Map>) user.getContextData().get(CasIdentityProvider.USER_ATTRIBUTES); 23 | logger.debug("getAttributeValue attributes: " + userAttributes); 24 | return userAttributes.getOrDefault( 25 | mapperModel.getConfig().get(ATTRIBUTE), Collections.emptyList()); 26 | } 27 | 28 | protected boolean hasAttributeValue( 29 | final IdentityProviderMapperModel mapperModel, final BrokeredIdentityContext context) { 30 | return CollectionUtil.collectionEquals( 31 | Collections.singletonList(mapperModel.getConfig().get(ATTRIBUTE_VALUE)), 32 | getAttributeValue(mapperModel, context)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Maven 3 | 4 | on: 5 | push: 6 | branches: 7 | - main 8 | pull_request: 9 | branches: 10 | - main 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | permissions: 18 | id-token: write 19 | security-events: write 20 | contents: write 21 | 22 | steps: 23 | - name: Checkout repository 24 | uses: actions/checkout@v6 25 | 26 | - name: Register problem matchers 27 | run: echo "::add-matcher::.github/matchers.json" 28 | 29 | - name: Initialize CodeQL 30 | uses: github/codeql-action/init@v4 31 | with: 32 | languages: java-kotlin 33 | queries: security-extended,security-and-quality 34 | 35 | - name: Set up JDK 21 36 | uses: actions/setup-java@v5 37 | with: 38 | java-version: '21' 39 | distribution: 'corretto' 40 | cache: maven 41 | 42 | - name: Get AWS credentials 43 | id: get_aws_credentials 44 | continue-on-error: true 45 | uses: aws-actions/configure-aws-credentials@v5 46 | with: 47 | aws-region: us-east-1 48 | role-to-assume: arn:aws:iam::771971951923:role/keycloak-cas-artifact-upload 49 | audience: sts.amazonaws.com 50 | role-duration-seconds: 900 51 | 52 | - name: Build with Maven 53 | run: mvn -B clean com.spotify.fmt:fmt-maven-plugin:check package ${{ steps.get_aws_credentials.outcome == 'success' && 'deploy' || '' }} 54 | 55 | - name: Upload JAR to GitHub 56 | uses: actions/upload-artifact@v6 57 | with: 58 | path: target/keycloak-cas-services-*-SNAPSHOT.jar 59 | if-no-files-found: error 60 | compression-level: 0 61 | 62 | - name: Perform CodeQL Analysis 63 | uses: github/codeql-action/analyze@v4 64 | with: 65 | category: "/language:java-kotlin" 66 | 67 | - name: Update dependency graph 68 | uses: advanced-security/maven-dependency-submission-action@v5 69 | continue-on-error: true 70 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/CasIdentityProviderConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas; 2 | 3 | import java.io.Serial; 4 | import org.keycloak.models.IdentityProviderModel; 5 | 6 | public class CasIdentityProviderConfig extends IdentityProviderModel { 7 | 8 | @Serial private static final long serialVersionUID = 1L; 9 | 10 | private static final String DEFAULT_CAS_LOGIN_SUFFIX = "login"; 11 | private static final String DEFAULT_CAS_LOGOUT_SUFFIX = "logout"; 12 | private static final String CAS_SERVICE_VALIDATE_SUFFIX = "serviceValidate"; 13 | private static final String CAS_3_PROTOCOL_PREFIX = "p3"; 14 | 15 | public CasIdentityProviderConfig() { 16 | super(); 17 | } 18 | 19 | public CasIdentityProviderConfig(final IdentityProviderModel model) { 20 | super(model); 21 | } 22 | 23 | public void setCasServerUrlPrefix(final String casServerUrlPrefix) { 24 | getConfig().put("casServerUrlPrefix", casServerUrlPrefix); 25 | } 26 | 27 | public String getCasServerUrlPrefix() { 28 | return getConfig().get("casServerUrlPrefix"); 29 | } 30 | 31 | public void setGateway(final boolean gateway) { 32 | getConfig().put("gateway", String.valueOf(gateway)); 33 | } 34 | 35 | public boolean isGateway() { 36 | return Boolean.parseBoolean(getConfig().get("gateway")); 37 | } 38 | 39 | public void setRenew(final boolean renew) { 40 | getConfig().put("renew", String.valueOf(renew)); 41 | } 42 | 43 | public boolean isRenew() { 44 | return Boolean.parseBoolean(getConfig().get("renew")); 45 | } 46 | 47 | public void setCasLogout(final boolean casLogout) { 48 | getConfig().put("redirectToCasServerAfterLogout", String.valueOf(casLogout)); 49 | } 50 | 51 | public boolean isCasLogout() { 52 | return Boolean.parseBoolean(getConfig().get("redirectToCasServerAfterLogout")); 53 | } 54 | 55 | public String getCasServerLoginUrl() { 56 | return String.format("%s/%s", getConfig().get("casServerUrlPrefix"), DEFAULT_CAS_LOGIN_SUFFIX); 57 | } 58 | 59 | public String getCasServerLogoutUrl() { 60 | return String.format("%s/%s", getConfig().get("casServerUrlPrefix"), DEFAULT_CAS_LOGOUT_SUFFIX); 61 | } 62 | 63 | public String getCasServiceValidateUrl() { 64 | return String.format( 65 | "%s/%s/%s", 66 | getConfig().get("casServerUrlPrefix"), CAS_3_PROTOCOL_PREFIX, CAS_SERVICE_VALIDATE_SUFFIX); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/CasIdentityProviderFactory.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas; 2 | 3 | import java.util.List; 4 | import org.keycloak.broker.provider.AbstractIdentityProviderFactory; 5 | import org.keycloak.models.IdentityProviderModel; 6 | import org.keycloak.models.KeycloakSession; 7 | import org.keycloak.provider.ConfiguredProvider; 8 | import org.keycloak.provider.ProviderConfigProperty; 9 | import org.keycloak.provider.ProviderConfigurationBuilder; 10 | 11 | public class CasIdentityProviderFactory extends AbstractIdentityProviderFactory 12 | implements ConfiguredProvider { 13 | 14 | public static final String PROVIDER_ID = "cas"; 15 | 16 | @Override 17 | public String getName() { 18 | return "CAS"; 19 | } 20 | 21 | @Override 22 | public CasIdentityProvider create( 23 | final KeycloakSession session, final IdentityProviderModel model) { 24 | return new CasIdentityProvider(session, new CasIdentityProviderConfig(model)); 25 | } 26 | 27 | @Override 28 | public String getId() { 29 | return PROVIDER_ID; 30 | } 31 | 32 | @Override 33 | public IdentityProviderModel createConfig() { 34 | return new CasIdentityProviderConfig(); 35 | } 36 | 37 | @Override 38 | public List getConfigProperties() { 39 | return ProviderConfigurationBuilder.create() 40 | .property() 41 | .name("casServerUrlPrefix") 42 | .type(ProviderConfigProperty.STRING_TYPE) 43 | .label("CAS server URL prefix") 44 | .helpText("The start of the CAS server URL, i.e. https://localhost:8443/cas") 45 | .add() 46 | .property() 47 | .name("renew") 48 | .type(ProviderConfigProperty.BOOLEAN_TYPE) 49 | .label("CAS renew") 50 | .helpText("Force users to reauthenticate.") 51 | .add() 52 | .property() 53 | .name("gateway") 54 | .type(ProviderConfigProperty.BOOLEAN_TYPE) 55 | .label("CAS gateway") 56 | .helpText("Do not force users to authenticate if they are not already authenticated.") 57 | .add() 58 | .property() 59 | .name("redirectToCasServerAfterLogout") 60 | .type(ProviderConfigProperty.BOOLEAN_TYPE) 61 | .label("CAS Logout") 62 | .helpText("Should the user also be logged out of CAS when they log out of Keycloak?") 63 | .add() 64 | .build(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/util/UrlHelper.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.util; 2 | 3 | import io.github.johnjcool.keycloak.broker.cas.CasIdentityProvider; 4 | import io.github.johnjcool.keycloak.broker.cas.CasIdentityProviderConfig; 5 | import jakarta.ws.rs.core.UriBuilder; 6 | import jakarta.ws.rs.core.UriInfo; 7 | import org.keycloak.broker.provider.AuthenticationRequest; 8 | import org.keycloak.models.RealmModel; 9 | import org.keycloak.services.resources.IdentityBrokerService; 10 | import org.keycloak.services.resources.RealmsResource; 11 | 12 | public final class UrlHelper { 13 | private static final String PROVIDER_PARAMETER_SERVICE = "service"; 14 | private static final String PROVIDER_PARAMETER_RENEW = "renew"; 15 | private static final String PROVIDER_PARAMETER_GATEWAY = "gateway"; 16 | public static final String PROVIDER_PARAMETER_TICKET = "ticket"; 17 | 18 | private UrlHelper() { 19 | // util 20 | } 21 | 22 | public static UriBuilder createAuthenticationUrl( 23 | final CasIdentityProviderConfig config, final AuthenticationRequest request) { 24 | UriBuilder builder = 25 | UriBuilder.fromUri(config.getCasServerLoginUrl()) 26 | .queryParam(PROVIDER_PARAMETER_SERVICE, request.getRedirectUri()); 27 | if (config.isRenew()) { 28 | builder.queryParam(PROVIDER_PARAMETER_RENEW, config.isRenew()); 29 | } 30 | if (config.isGateway()) { 31 | builder.queryParam(PROVIDER_PARAMETER_GATEWAY, config.isGateway()); 32 | } 33 | return builder; 34 | } 35 | 36 | public static UriBuilder createValidateServiceUrl( 37 | final CasIdentityProviderConfig config, final String ticket, final UriInfo uriInfo) { 38 | UriBuilder builder = 39 | UriBuilder.fromUri(config.getCasServiceValidateUrl()) 40 | .queryParam(PROVIDER_PARAMETER_TICKET, ticket) 41 | .queryParam(PROVIDER_PARAMETER_SERVICE, uriInfo.getAbsolutePath().toString()); 42 | if (config.isRenew()) { 43 | builder.queryParam(PROVIDER_PARAMETER_RENEW, config.isRenew()); 44 | } 45 | return builder; 46 | } 47 | 48 | public static UriBuilder createLogoutUrl( 49 | final CasIdentityProviderConfig config, final RealmModel realm, final UriInfo uriInfo) { 50 | return UriBuilder.fromUri(config.getCasServerLogoutUrl()) 51 | .queryParam( 52 | PROVIDER_PARAMETER_SERVICE, 53 | RealmsResource.brokerUrl(uriInfo) 54 | .path(IdentityBrokerService.class, "getEndpoint") 55 | .path(CasIdentityProvider.Endpoint.class, "logoutResponse") 56 | .build(realm.getName(), config.getAlias()) 57 | .toString()); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/mappers/AttributeToRoleMapper.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.mappers; 2 | 3 | import io.github.johnjcool.keycloak.broker.cas.CasIdentityProviderFactory; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import org.keycloak.broker.provider.BrokeredIdentityContext; 7 | import org.keycloak.broker.provider.ConfigConstants; 8 | import org.keycloak.broker.provider.IdentityBrokerException; 9 | import org.keycloak.models.IdentityProviderMapperModel; 10 | import org.keycloak.models.KeycloakSession; 11 | import org.keycloak.models.RealmModel; 12 | import org.keycloak.models.RoleModel; 13 | import org.keycloak.models.UserModel; 14 | import org.keycloak.models.utils.KeycloakModelUtils; 15 | import org.keycloak.provider.ProviderConfigProperty; 16 | 17 | public class AttributeToRoleMapper extends AbstractAttributeMapper { 18 | 19 | protected static final String[] COMPATIBLE_PROVIDERS = {CasIdentityProviderFactory.PROVIDER_ID}; 20 | 21 | private static final List configProperties = new ArrayList<>(); 22 | 23 | static { 24 | ProviderConfigProperty attributeName = new ProviderConfigProperty(); 25 | attributeName.setName(ATTRIBUTE); 26 | attributeName.setLabel("Attribute Name"); 27 | attributeName.setHelpText("Name of attribute to search for in assertion."); 28 | attributeName.setType(ProviderConfigProperty.STRING_TYPE); 29 | configProperties.add(attributeName); 30 | 31 | ProviderConfigProperty attributeValue = new ProviderConfigProperty(); 32 | attributeValue.setName(ATTRIBUTE_VALUE); 33 | attributeValue.setLabel("Attribute Value"); 34 | attributeValue.setHelpText( 35 | "Value the attribute must have. If the attribute is an array, then the value must be contained in the array."); 36 | attributeValue.setType(ProviderConfigProperty.STRING_TYPE); 37 | configProperties.add(attributeValue); 38 | 39 | ProviderConfigProperty role = new ProviderConfigProperty(); 40 | role.setName(ConfigConstants.ROLE); 41 | role.setLabel("Role"); 42 | role.setHelpText( 43 | "Role to grant to user if attribute is present. Click 'Select Role' button to browse roles, or just type it in the textbox. To reference an application role the syntax is appname.approle, i.e. myapp.myrole"); 44 | role.setType(ProviderConfigProperty.ROLE_TYPE); 45 | configProperties.add(role); 46 | } 47 | 48 | public static final String PROVIDER_ID = "cas-role-idp-mapper"; 49 | 50 | @Override 51 | public List getConfigProperties() { 52 | return configProperties; 53 | } 54 | 55 | @Override 56 | public String getId() { 57 | return PROVIDER_ID; 58 | } 59 | 60 | @Override 61 | public String[] getCompatibleProviders() { 62 | return COMPATIBLE_PROVIDERS; 63 | } 64 | 65 | @Override 66 | public String getDisplayCategory() { 67 | return "Role Importer"; 68 | } 69 | 70 | @Override 71 | public String getDisplayType() { 72 | return "Attribute to Role"; 73 | } 74 | 75 | @Override 76 | public void importNewUser( 77 | final KeycloakSession session, 78 | final RealmModel realm, 79 | final UserModel user, 80 | final IdentityProviderMapperModel mapperModel, 81 | final BrokeredIdentityContext context) { 82 | String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE); 83 | if (hasAttributeValue(mapperModel, context)) { 84 | RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName); 85 | if (role == null) { 86 | throw new IdentityBrokerException("Unable to find role: " + roleName); 87 | } 88 | user.grantRole(role); 89 | } 90 | } 91 | 92 | @Override 93 | public void updateBrokeredUser( 94 | final KeycloakSession session, 95 | final RealmModel realm, 96 | final UserModel user, 97 | final IdentityProviderMapperModel mapperModel, 98 | final BrokeredIdentityContext context) { 99 | String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE); 100 | if (!hasAttributeValue(mapperModel, context)) { 101 | RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName); 102 | if (role == null) { 103 | throw new IdentityBrokerException("Unable to find role: " + roleName); 104 | } 105 | user.deleteRoleMapping(role); 106 | } 107 | } 108 | 109 | @Override 110 | public String getHelpText() { 111 | return "If a attribute exists, grant the user the specified realm or application role."; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | io.github.johnjcool 6 | keycloak-cas-services 7 | ${keycloak.version}-SNAPSHOT 8 | Keycloak CAS Services 9 | https://github.com/johnjcool/keycloak-cas-services 10 | Extend Keycloak with CAS IdP 11 | 12 | 13 | 14 | Apache License, Version 2.0 15 | http://www.apache.org/licenses/LICENSE-2.0.txt 16 | repo 17 | 18 | 19 | 20 | 21 | https://github.com/johnjcool/keycloak-cas-services 22 | scm:git:https://github.com/johnjcool/keycloak-cas-services.git 23 | scm:git:https://github.com/johnjcool/keycloak-cas-services.git 24 | 25 | 26 | 27 | 28 | John J Cool 29 | john.j.cool@gmail.com 30 | 31 | 32 | 33 | 34 | 26.4.7 35 | 36 | 21 37 | 21 38 | 39 | 40 | 41 | 42 | 43 | org.keycloak 44 | keycloak-parent 45 | ${keycloak.version} 46 | pom 47 | import 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.keycloak 55 | keycloak-core 56 | provided 57 | 58 | 59 | org.keycloak 60 | keycloak-server-spi 61 | provided 62 | 63 | 64 | org.keycloak 65 | keycloak-server-spi-private 66 | provided 67 | 68 | 69 | org.jboss.logging 70 | jboss-logging 71 | provided 72 | 73 | 74 | org.keycloak 75 | keycloak-services 76 | provided 77 | 78 | 79 | org.keycloak 80 | keycloak-saml-core-public 81 | provided 82 | 83 | 84 | org.keycloak 85 | keycloak-model-jpa 86 | provided 87 | 88 | 89 | 90 | junit 91 | junit 92 | test 93 | 94 | 95 | org.jboss.resteasy 96 | resteasy-undertow 97 | test 98 | 99 | 100 | io.undertow 101 | undertow-servlet 102 | test 103 | 104 | 105 | 106 | 107 | 108 | 109 | org.apache.maven.plugins 110 | maven-jar-plugin 111 | 3.5.0 112 | 113 | 114 | 115 | org.keycloak.keycloak-services 116 | 117 | 118 | 119 | 120 | 121 | com.spotify.fmt 122 | fmt-maven-plugin 123 | 2.29 124 | 125 | 126 | 127 | check 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | com.github.seahen 136 | maven-s3-wagon 137 | 1.3.3 138 | 139 | 140 | 141 | 142 | 143 | 144 | s3 145 | s3://gatech-me-robojackets-public-artifacts/ 146 | 147 | 148 | s3 149 | s3://gatech-me-robojackets-public-artifacts/ 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/mappers/UserAttributeMapper.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.mappers; 2 | 3 | import io.github.johnjcool.keycloak.broker.cas.CasIdentityProviderFactory; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.function.Consumer; 7 | import java.util.stream.Collectors; 8 | import org.jboss.logging.Logger; 9 | import org.keycloak.broker.provider.BrokeredIdentityContext; 10 | import org.keycloak.common.util.CollectionUtil; 11 | import org.keycloak.models.*; 12 | import org.keycloak.provider.ProviderConfigProperty; 13 | 14 | public class UserAttributeMapper extends AbstractAttributeMapper { 15 | 16 | private static final String[] cp = new String[] {CasIdentityProviderFactory.PROVIDER_ID}; 17 | 18 | private static final List configProperties = new ArrayList<>(); 19 | 20 | private static final String ATTRIBUTE = "attribute"; 21 | private static final String USER_ATTRIBUTE = "user.attribute"; 22 | private static final String EMAIL = "email"; 23 | private static final String FIRST_NAME = "firstName"; 24 | private static final String LAST_NAME = "lastName"; 25 | 26 | protected static final Logger logger = Logger.getLogger(UserAttributeMapper.class); 27 | 28 | static { 29 | ProviderConfigProperty casAttributeName = new ProviderConfigProperty(); 30 | casAttributeName.setName(ATTRIBUTE); 31 | casAttributeName.setLabel("Attribute"); 32 | casAttributeName.setHelpText("Name of attribute to search for in assertion."); 33 | casAttributeName.setType(ProviderConfigProperty.STRING_TYPE); 34 | configProperties.add(casAttributeName); 35 | 36 | ProviderConfigProperty keycloakAttributeName = new ProviderConfigProperty(); 37 | keycloakAttributeName.setName(USER_ATTRIBUTE); 38 | keycloakAttributeName.setLabel("User Attribute Name"); 39 | keycloakAttributeName.setHelpText( 40 | "User attribute name to store CAS attribute. Use email, lastName, and firstName to map to those predefined user properties."); 41 | keycloakAttributeName.setType(ProviderConfigProperty.STRING_TYPE); 42 | configProperties.add(keycloakAttributeName); 43 | } 44 | 45 | public static final String PROVIDER_ID = "cas-user-attribute-idp-mapper"; 46 | 47 | @Override 48 | public List getConfigProperties() { 49 | return configProperties; 50 | } 51 | 52 | @Override 53 | public String getId() { 54 | return PROVIDER_ID; 55 | } 56 | 57 | @Override 58 | public String[] getCompatibleProviders() { 59 | return cp; 60 | } 61 | 62 | @Override 63 | public String getDisplayCategory() { 64 | return "Attribute Importer"; 65 | } 66 | 67 | @Override 68 | public String getDisplayType() { 69 | return "Attribute Importer"; 70 | } 71 | 72 | @Override 73 | public void preprocessFederatedIdentity( 74 | final KeycloakSession session, 75 | final RealmModel realm, 76 | final IdentityProviderMapperModel mapperModel, 77 | final BrokeredIdentityContext context) { 78 | String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE); 79 | if (attribute == null || attribute.isEmpty()) { 80 | logger.debug("preprocessFederatedIdentity called with empty attribute"); 81 | return; 82 | } 83 | 84 | logger.debug("preprocessFederatedIdentity called with attribute " + attribute); 85 | 86 | List value = getAttributeValue(mapperModel, context); 87 | 88 | logger.debug("Values: " + value); 89 | 90 | if (EMAIL.equalsIgnoreCase(attribute)) { 91 | setIfNotEmpty(context::setEmail, value); 92 | } else if (FIRST_NAME.equalsIgnoreCase(attribute)) { 93 | setIfNotEmpty(context::setFirstName, value); 94 | } else if (LAST_NAME.equalsIgnoreCase(attribute)) { 95 | setIfNotEmpty(context::setLastName, value); 96 | } else { 97 | context.setUserAttribute(attribute, value); 98 | } 99 | } 100 | 101 | private void setIfNotEmpty(final Consumer consumer, final List values) { 102 | if (values != null && !values.isEmpty() && !values.getFirst().isEmpty()) { 103 | consumer.accept(values.getFirst()); 104 | } 105 | } 106 | 107 | @Override 108 | public void updateBrokeredUser( 109 | final KeycloakSession session, 110 | final RealmModel realm, 111 | final UserModel user, 112 | final IdentityProviderMapperModel mapperModel, 113 | final BrokeredIdentityContext context) { 114 | String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE); 115 | if (attribute == null || attribute.isEmpty()) { 116 | logger.debug("updateBrokeredUser called with empty attribute"); 117 | return; 118 | } 119 | logger.debug("updateBrokeredUser called with attribute " + attribute); 120 | 121 | List value = getAttributeValue(mapperModel, context); 122 | 123 | logger.debug("Values: " + value); 124 | 125 | if (EMAIL.equalsIgnoreCase(attribute)) { 126 | setIfNotEmpty(user::setEmail, value); 127 | } else if (FIRST_NAME.equalsIgnoreCase(attribute)) { 128 | setIfNotEmpty(user::setFirstName, value); 129 | } else if (LAST_NAME.equalsIgnoreCase(attribute)) { 130 | setIfNotEmpty(user::setLastName, value); 131 | } else { 132 | List current = user.getAttributeStream(attribute).collect(Collectors.toList()); 133 | if (!CollectionUtil.collectionEquals(value, current)) { 134 | user.setAttribute(attribute, value); 135 | } else if (value.isEmpty()) { 136 | user.removeAttribute(attribute); 137 | } 138 | } 139 | } 140 | 141 | @Override 142 | public boolean supportsSyncMode(IdentityProviderSyncMode syncMode) { 143 | return true; 144 | } 145 | 146 | @Override 147 | public String getHelpText() { 148 | return "Import declared CAS attribute if it exists in assertion into the specified user property or attribute."; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/test/java/io/github/johnjcool/keycloak/broker/cas/model/ServiceResponseTest.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas.model; 2 | 3 | import io.undertow.Undertow; 4 | import io.undertow.util.Headers; 5 | import jakarta.ws.rs.client.Client; 6 | import jakarta.ws.rs.client.WebTarget; 7 | import jakarta.ws.rs.core.Response; 8 | import jakarta.xml.bind.JAXBContext; 9 | import jakarta.xml.bind.JAXBException; 10 | import jakarta.xml.bind.Unmarshaller; 11 | import java.io.StringReader; 12 | import java.nio.CharBuffer; 13 | import java.nio.charset.Charset; 14 | import java.util.Arrays; 15 | import java.util.Collections; 16 | import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; 17 | import org.jboss.resteasy.spi.ResteasyProviderFactory; 18 | import org.junit.AfterClass; 19 | import org.junit.Assert; 20 | import org.junit.BeforeClass; 21 | import org.junit.Test; 22 | 23 | public class ServiceResponseTest { 24 | 25 | private static Undertow server; 26 | 27 | @Test 28 | public void testReadWithAttributes() throws JAXBException { 29 | Client client = ResteasyClientBuilder.newClient(ResteasyProviderFactory.getInstance()); 30 | WebTarget target = 31 | client.target(String.format("http://%s:%d%s", "localhost", 9999, "/with-attributes")); 32 | Response response = target.request().get(); 33 | Assert.assertEquals(200, response.getStatus()); 34 | response.bufferEntity(); 35 | 36 | String stringResponse = response.readEntity(String.class); 37 | 38 | Unmarshaller um = JAXBContext.newInstance(ServiceResponse.class).createUnmarshaller(); 39 | um.setEventHandler(new jakarta.xml.bind.helpers.DefaultValidationEventHandler()); 40 | 41 | ServiceResponse serviceResponse = 42 | (ServiceResponse) um.unmarshal(new StringReader(stringResponse)); 43 | 44 | System.out.println(serviceResponse); 45 | System.out.println(serviceResponse.getSuccess()); 46 | System.out.println(serviceResponse.getSuccess().getAttributes()); 47 | Success success = serviceResponse.getSuccess(); 48 | 49 | Assert.assertEquals("test", success.getUser()); 50 | Assert.assertFalse(success.getAttributes().isEmpty()); 51 | Assert.assertEquals( 52 | Collections.singletonList("test.test@test.test"), success.getAttributes().get("mail")); 53 | Assert.assertEquals(Collections.singletonList("tets"), success.getAttributes().get("sn")); 54 | Assert.assertEquals(Collections.singletonList("test"), success.getAttributes().get("cn")); 55 | } 56 | 57 | @Test 58 | public void testReadWithMultiValAttributes() throws JAXBException { 59 | Client client = ResteasyClientBuilder.newClient(ResteasyProviderFactory.getInstance()); 60 | WebTarget target = 61 | client.target( 62 | String.format("http://%s:%d%s", "localhost", 9999, "/with-multival-attributes")); 63 | Response response = target.request().get(); 64 | Assert.assertEquals(200, response.getStatus()); 65 | response.bufferEntity(); 66 | 67 | String stringResponse = response.readEntity(String.class); 68 | 69 | Unmarshaller um = JAXBContext.newInstance(ServiceResponse.class).createUnmarshaller(); 70 | um.setEventHandler(new jakarta.xml.bind.helpers.DefaultValidationEventHandler()); 71 | 72 | ServiceResponse serviceResponse = 73 | (ServiceResponse) um.unmarshal(new StringReader(stringResponse)); 74 | 75 | System.out.println(serviceResponse); 76 | System.out.println(serviceResponse.getSuccess()); 77 | System.out.println(serviceResponse.getSuccess().getAttributes()); 78 | Success success = serviceResponse.getSuccess(); 79 | 80 | Assert.assertEquals("test", success.getUser()); 81 | Assert.assertFalse(success.getAttributes().isEmpty()); 82 | Assert.assertEquals( 83 | Collections.singletonList("test.test@test.test"), success.getAttributes().get("mail")); 84 | Assert.assertEquals(Collections.singletonList("tets"), success.getAttributes().get("sn")); 85 | Assert.assertEquals(Collections.singletonList("test"), success.getAttributes().get("cn")); 86 | Assert.assertEquals( 87 | Arrays.asList("LdapAuthenticationHandler", "mfa-duo"), 88 | success.getAttributes().get("successfulAuthenticationHandlers")); 89 | } 90 | 91 | @Test 92 | public void testReadWithoutAttributes() throws JAXBException { 93 | Client client = ResteasyClientBuilder.newClient(ResteasyProviderFactory.getInstance()); 94 | WebTarget target = 95 | client.target(String.format("http://%s:%d%s", "localhost", 9999, "/without-attributes")); 96 | Response response = target.request().get(); 97 | Assert.assertEquals(200, response.getStatus()); 98 | response.bufferEntity(); 99 | 100 | String stringResponse = response.readEntity(String.class); 101 | 102 | Unmarshaller um = JAXBContext.newInstance(ServiceResponse.class).createUnmarshaller(); 103 | um.setEventHandler(new jakarta.xml.bind.helpers.DefaultValidationEventHandler()); 104 | 105 | ServiceResponse serviceResponse = 106 | (ServiceResponse) um.unmarshal(new StringReader(stringResponse)); 107 | 108 | System.out.println(serviceResponse); 109 | System.out.println(serviceResponse.getSuccess()); 110 | System.out.println(serviceResponse.getSuccess().getAttributes()); 111 | Success success = serviceResponse.getSuccess(); 112 | 113 | Assert.assertEquals("test", success.getUser()); 114 | Assert.assertTrue(success.getAttributes().isEmpty()); 115 | } 116 | 117 | @BeforeClass 118 | public static void init() { 119 | server = 120 | Undertow.builder() 121 | .addHttpListener(9999, "localhost") 122 | .setHandler( 123 | httpServerExchange -> { 124 | switch (httpServerExchange.getRequestURI()) { 125 | case "/without-attributes": 126 | httpServerExchange 127 | .getResponseHeaders() 128 | .put(Headers.CONTENT_TYPE, "application/xml"); 129 | httpServerExchange 130 | .getResponseSender() 131 | .send( 132 | Charset.defaultCharset() 133 | .encode( 134 | CharBuffer.wrap( 135 | """ 136 | 137 | 138 | test 139 | 140 | 141 | """))); 142 | break; 143 | case "/with-attributes": 144 | httpServerExchange 145 | .getResponseHeaders() 146 | .put(Headers.CONTENT_TYPE, "application/xml"); 147 | httpServerExchange 148 | .getResponseSender() 149 | .send( 150 | Charset.defaultCharset() 151 | .encode( 152 | CharBuffer.wrap( 153 | """ 154 | 155 | 156 | test 157 | 158 | 159 | 160 | test.test@test.test 161 | 162 | tets 163 | 164 | test 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | """))); 173 | break; 174 | case "/with-multival-attributes": 175 | httpServerExchange 176 | .getResponseHeaders() 177 | .put(Headers.CONTENT_TYPE, "application/xml"); 178 | httpServerExchange 179 | .getResponseSender() 180 | .send( 181 | Charset.defaultCharset() 182 | .encode( 183 | CharBuffer.wrap( 184 | """ 185 | 186 | 187 | test 188 | 189 | 190 | 191 | test.test@test.test 192 | 193 | tets 194 | 195 | test 196 | 197 | LdapAuthenticationHandler 198 | mfa-duo 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | """))); 207 | break; 208 | default: 209 | throw new IllegalStateException( 210 | "Unexpected value: " + httpServerExchange.getRequestURI()); 211 | } 212 | }) 213 | .build(); 214 | 215 | server.start(); 216 | } 217 | 218 | @AfterClass 219 | public static void stop() { 220 | server.stop(); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /src/main/java/io/github/johnjcool/keycloak/broker/cas/CasIdentityProvider.java: -------------------------------------------------------------------------------- 1 | package io.github.johnjcool.keycloak.broker.cas; 2 | 3 | import static io.github.johnjcool.keycloak.broker.cas.util.UrlHelper.PROVIDER_PARAMETER_TICKET; 4 | import static io.github.johnjcool.keycloak.broker.cas.util.UrlHelper.createAuthenticationUrl; 5 | import static io.github.johnjcool.keycloak.broker.cas.util.UrlHelper.createLogoutUrl; 6 | import static io.github.johnjcool.keycloak.broker.cas.util.UrlHelper.createValidateServiceUrl; 7 | 8 | import io.github.johnjcool.keycloak.broker.cas.model.ServiceResponse; 9 | import io.github.johnjcool.keycloak.broker.cas.model.Success; 10 | import jakarta.ws.rs.CookieParam; 11 | import jakarta.ws.rs.GET; 12 | import jakarta.ws.rs.Path; 13 | import jakarta.ws.rs.QueryParam; 14 | import jakarta.ws.rs.core.*; 15 | import jakarta.xml.bind.JAXBContext; 16 | import jakarta.xml.bind.JAXBException; 17 | import jakarta.xml.bind.Unmarshaller; 18 | import java.io.IOException; 19 | import java.io.StringReader; 20 | import org.jboss.logging.Logger; 21 | import org.keycloak.broker.provider.AbstractIdentityProvider; 22 | import org.keycloak.broker.provider.AuthenticationRequest; 23 | import org.keycloak.broker.provider.BrokeredIdentityContext; 24 | import org.keycloak.broker.provider.IdentityBrokerException; 25 | import org.keycloak.broker.provider.util.SimpleHttp; 26 | import org.keycloak.common.ClientConnection; 27 | import org.keycloak.events.Errors; 28 | import org.keycloak.events.EventBuilder; 29 | import org.keycloak.events.EventType; 30 | import org.keycloak.models.FederatedIdentityModel; 31 | import org.keycloak.models.KeycloakSession; 32 | import org.keycloak.models.RealmModel; 33 | import org.keycloak.models.UserSessionModel; 34 | import org.keycloak.services.ErrorPage; 35 | import org.keycloak.services.managers.AuthenticationManager; 36 | import org.keycloak.services.messages.Messages; 37 | import org.keycloak.sessions.AuthenticationSessionModel; 38 | 39 | public class CasIdentityProvider extends AbstractIdentityProvider { 40 | 41 | protected static final Logger logger = Logger.getLogger(CasIdentityProvider.class); 42 | 43 | public static final String USER_ATTRIBUTES = "UserAttributes"; 44 | 45 | private static final String STATE_COOKIE_NAME = "__Host-cas_state"; 46 | 47 | private static final Unmarshaller unmarshaller; 48 | 49 | static { 50 | try { 51 | unmarshaller = JAXBContext.newInstance(ServiceResponse.class).createUnmarshaller(); 52 | } catch (JAXBException e) { 53 | throw new RuntimeException(e); 54 | } 55 | } 56 | 57 | public CasIdentityProvider( 58 | final KeycloakSession session, final CasIdentityProviderConfig config) { 59 | super(session, config); 60 | } 61 | 62 | @Override 63 | public Response performLogin(final AuthenticationRequest request) { 64 | return Response.seeOther(createAuthenticationUrl(getConfig(), request).build()) 65 | .cookie( 66 | new NewCookie.Builder(STATE_COOKIE_NAME) 67 | .value(request.getState().getEncoded()) 68 | .httpOnly(true) 69 | .secure(true) 70 | .path("/") 71 | .build()) 72 | .build(); 73 | } 74 | 75 | @Override 76 | public Response keycloakInitiatedBrowserLogout( 77 | final KeycloakSession session, 78 | final UserSessionModel userSession, 79 | final UriInfo uriInfo, 80 | final RealmModel realm) { 81 | CasIdentityProviderConfig config = getConfig(); 82 | Response res = 83 | AuthenticationManager.finishBrowserLogout( 84 | session, realm, userSession, uriInfo, session.getContext().getConnection(), null); 85 | if (res.getStatus() != 302) { 86 | logger.error("Failed to logout user session: " + userSession.getId()); 87 | EventBuilder event = new EventBuilder(realm, session, session.getContext().getConnection()); 88 | event.event(EventType.LOGOUT); 89 | event.error(Errors.USER_SESSION_NOT_FOUND); 90 | return ErrorPage.error( 91 | session, null, Response.Status.INTERNAL_SERVER_ERROR, "CAS KC Logout Failed"); 92 | } 93 | if (config.isCasLogout()) { 94 | return Response.status(302) 95 | .location(createLogoutUrl(getConfig(), realm, uriInfo).build()) 96 | .build(); 97 | } 98 | return res; 99 | } 100 | 101 | @Override 102 | public Response retrieveToken( 103 | final KeycloakSession session, final FederatedIdentityModel identity) { 104 | return Response.ok(identity.getToken()).type(MediaType.APPLICATION_JSON).build(); 105 | } 106 | 107 | @Override 108 | public Endpoint callback( 109 | final RealmModel realm, 110 | final org.keycloak.broker.provider.IdentityProvider.AuthenticationCallback callback, 111 | final EventBuilder event) { 112 | return new Endpoint(callback, realm, this); 113 | } 114 | 115 | public static final class Endpoint { 116 | private final AuthenticationCallback callback; 117 | private final RealmModel realm; 118 | private final KeycloakSession session; 119 | private final ClientConnection clientConnection; 120 | private final HttpHeaders headers; 121 | private final CasIdentityProvider provider; 122 | private final CasIdentityProviderConfig config; 123 | 124 | Endpoint( 125 | final AuthenticationCallback callback, 126 | final RealmModel realm, 127 | final CasIdentityProvider provider) { 128 | this.callback = callback; 129 | this.realm = realm; 130 | this.provider = provider; 131 | this.session = provider.session; 132 | this.headers = session.getContext().getRequestHeaders(); 133 | this.clientConnection = session.getContext().getConnection(); 134 | this.config = provider.getConfig(); 135 | } 136 | 137 | @GET 138 | public Response authResponse( 139 | @QueryParam(PROVIDER_PARAMETER_TICKET) final String ticket, 140 | @CookieParam(STATE_COOKIE_NAME) final Cookie stateCookie) { 141 | return callback.authenticated( 142 | getFederatedIdentity( 143 | config, ticket, session.getContext().getUri(), stateCookie.getValue())); 144 | } 145 | 146 | @GET 147 | @Path("logout_response") 148 | public Response logoutResponse( 149 | @Context final UriInfo uriInfo, @QueryParam("state") final String state) { 150 | UserSessionModel userSession = session.sessions().getUserSession(realm, state); 151 | if (userSession == null) { 152 | logger.error("no valid user session"); 153 | EventBuilder e = new EventBuilder(realm, session, clientConnection); 154 | e.event(EventType.LOGOUT); 155 | e.error(Errors.USER_SESSION_NOT_FOUND); 156 | return ErrorPage.error( 157 | session, 158 | null, 159 | Response.Status.BAD_REQUEST, 160 | Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR); 161 | } 162 | if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) { 163 | logger.error("usersession in different state"); 164 | EventBuilder e = new EventBuilder(realm, session, clientConnection); 165 | e.event(EventType.LOGOUT); 166 | e.error(Errors.USER_SESSION_NOT_FOUND); 167 | return ErrorPage.error( 168 | session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE); 169 | } 170 | return AuthenticationManager.finishBrowserLogout( 171 | session, realm, userSession, uriInfo, clientConnection, headers); 172 | } 173 | 174 | private BrokeredIdentityContext getFederatedIdentity( 175 | final CasIdentityProviderConfig config, 176 | final String ticket, 177 | final UriInfo uriInfo, 178 | final String state) { 179 | logger.debug("Current state value: " + state); 180 | try (SimpleHttp.Response response = 181 | SimpleHttp.doGet( 182 | createValidateServiceUrl(config, ticket, uriInfo).build().toURL().toString(), 183 | session) 184 | .asResponse()) { 185 | if (response.getStatus() != 200) { 186 | logger.error(response.asString()); 187 | throw new IdentityBrokerException( 188 | "CAS returned a non-200 response code: " + response.getStatus()); 189 | } 190 | 191 | if (logger.isDebugEnabled()) { 192 | logger.debug("Raw XML from CAS: " + response.asString()); 193 | } 194 | 195 | ServiceResponse serviceResponse = 196 | (ServiceResponse) unmarshaller.unmarshal(new StringReader(response.asString())); 197 | 198 | if (logger.isDebugEnabled()) { 199 | logger.debug("Parsed response: " + serviceResponse); 200 | } 201 | 202 | if (serviceResponse.getFailure() != null) { 203 | throw new IdentityBrokerException( 204 | "Failure response from CAS: " 205 | + serviceResponse.getFailure().getCode() 206 | + "(" 207 | + serviceResponse.getFailure().getDescription() 208 | + ")"); 209 | } 210 | Success success = serviceResponse.getSuccess(); 211 | 212 | BrokeredIdentityContext user = new BrokeredIdentityContext(success.getUser(), config); 213 | user.setUsername(success.getUser()); 214 | user.getContextData().put(USER_ATTRIBUTES, success.getAttributes()); 215 | user.setIdp(provider); 216 | AuthenticationSessionModel authSession = 217 | this.callback.getAndVerifyAuthenticationSession(state); 218 | session.getContext().setAuthenticationSession(authSession); 219 | user.setAuthenticationSession(authSession); 220 | return user; 221 | } catch (IOException | JAXBException e) { 222 | throw new IdentityBrokerException("Failed to complete CAS authentication", e); 223 | } 224 | } 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------