mirror of https://github.com/jacekkow/keycloak-protocol-cas

Jacek Kowalski
2024-06-21 508897529ff996bbf5bf2dec5c407517cc7eb520
commit | author | age
7f7e0c 1 package org.keycloak.protocol.cas;
MP 2
fdb9f6 3 import jakarta.ws.rs.core.HttpHeaders;
JK 4 import jakarta.ws.rs.core.Response;
5 import jakarta.ws.rs.core.UriInfo;
57a6c1 6 import org.apache.http.HttpEntity;
MP 7 import org.jboss.logging.Logger;
7f7e0c 8 import org.keycloak.common.util.KeycloakUriBuilder;
b88dc3 9 import org.keycloak.events.Details;
7f7e0c 10 import org.keycloak.events.EventBuilder;
MP 11 import org.keycloak.events.EventType;
4a6620 12 import org.keycloak.forms.login.LoginFormsProvider;
7f7e0c 13 import org.keycloak.models.*;
MP 14 import org.keycloak.protocol.LoginProtocol;
5d7080 15 import org.keycloak.protocol.cas.endpoints.AbstractValidateEndpoint;
57a6c1 16 import org.keycloak.protocol.cas.utils.LogoutHelper;
3882f0 17 import org.keycloak.services.ErrorPage;
7f7e0c 18 import org.keycloak.services.managers.ResourceAdminManager;
f75caf 19 import org.keycloak.sessions.AuthenticationSessionModel;
7f7e0c 20
57a6c1 21 import java.io.IOException;
7f7e0c 22 import java.net.URI;
MP 23
24 public class CASLoginProtocol implements LoginProtocol {
57a6c1 25     private static final Logger logger = Logger.getLogger(CASLoginProtocol.class);
MP 26
7f7e0c 27     public static final String LOGIN_PROTOCOL = "cas";
MP 28
29     public static final String SERVICE_PARAM = "service";
74023a 30     public static final String TARGET_PARAM = "TARGET";
7f7e0c 31     public static final String RENEW_PARAM = "renew";
MP 32     public static final String GATEWAY_PARAM = "gateway";
33     public static final String TICKET_PARAM = "ticket";
34     public static final String FORMAT_PARAM = "format";
5d7080 35     public static final String PGTURL_PARAM = "pgtUrl";
ARW 36     public static final String TARGET_SERVICE_PARAM = "targetService";
37     public static final String PGT_PARAM = "pgt";
7f7e0c 38
MP 39     public static final String TICKET_RESPONSE_PARAM = "ticket";
891484 40     public static final String SAMLART_RESPONSE_PARAM = "SAMLart";
7f7e0c 41
MP 42     public static final String SERVICE_TICKET_PREFIX = "ST-";
5d7080 43     public static final String PROXY_GRANTING_TICKET_IOU_PREFIX = "PGTIOU-";
ARW 44     public static final String PROXY_GRANTING_TICKET_PREFIX = "PGT-";
45     public static final String PROXY_TICKET_PREFIX = "PT-";
57a6c1 46     public static final String SESSION_SERVICE_TICKET = "service_ticket";
4a6620 47
MP 48     public static final String LOGOUT_REDIRECT_URI = "CAS_LOGOUT_REDIRECT_URI";
7f7e0c 49
MP 50     protected KeycloakSession session;
51     protected RealmModel realm;
52     protected UriInfo uriInfo;
53     protected HttpHeaders headers;
54     protected EventBuilder event;
55
7124d2 56     public CASLoginProtocol(KeycloakSession session, RealmModel realm, UriInfo uriInfo, HttpHeaders headers, EventBuilder event) {
7f7e0c 57         this.session = session;
MP 58         this.realm = realm;
59         this.uriInfo = uriInfo;
60         this.headers = headers;
61         this.event = event;
62     }
63
64     public CASLoginProtocol() {
65     }
66
67     @Override
68     public CASLoginProtocol setSession(KeycloakSession session) {
69         this.session = session;
70         return this;
71     }
72
73     @Override
74     public CASLoginProtocol setRealm(RealmModel realm) {
75         this.realm = realm;
76         return this;
77     }
78
79     @Override
80     public CASLoginProtocol setUriInfo(UriInfo uriInfo) {
81         this.uriInfo = uriInfo;
82         return this;
83     }
84
85     @Override
86     public CASLoginProtocol setHttpHeaders(HttpHeaders headers) {
87         this.headers = headers;
88         return this;
89     }
90
91     @Override
92     public CASLoginProtocol setEventBuilder(EventBuilder event) {
93         this.event = event;
94         return this;
95     }
96
97     @Override
c140ce 98     public Response authenticated(AuthenticationSessionModel authSession, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
b8d686 99         AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
7f7e0c 100
c140ce 101         String service = authSession.getRedirectUri();
7f7e0c 102         //TODO validate service
5570d4 103
7f7e0c 104         KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(service);
891484 105
5d7080 106         String loginTicket = AbstractValidateEndpoint.getST(session, clientSession, service);
891484 107
DR 108         if (authSession.getClientNotes().containsKey(CASLoginProtocol.TARGET_PARAM)) {
109             // This was a SAML 1.1 auth request so return the ticket ID as "SAMLart" instead of "ticket"
110             uriBuilder.queryParam(SAMLART_RESPONSE_PARAM, loginTicket);
111         } else {
112             uriBuilder.queryParam(TICKET_RESPONSE_PARAM, loginTicket);
113         }
7f7e0c 114
MP 115         URI redirectUri = uriBuilder.build();
116
117         Response.ResponseBuilder location = Response.status(302).location(redirectUri);
118         return location.build();
119     }
120
121     @Override
f75caf 122     public Response sendError(AuthenticationSessionModel authSession, Error error) {
3882f0 123         if (authSession.getClientNotes().containsKey(CASLoginProtocol.GATEWAY_PARAM)) {
JK 124             if (error == Error.PASSIVE_INTERACTION_REQUIRED || error == Error.PASSIVE_LOGIN_REQUIRED) {
125                 return Response.status(302).location(URI.create(authSession.getRedirectUri())).build();
126             }
127         }
128         return ErrorPage.error(session, authSession, Response.Status.INTERNAL_SERVER_ERROR, error.name());
7f7e0c 129     }
MP 130
131     @Override
0ec410 132     public Response backchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
57a6c1 133         String logoutUrl = clientSession.getRedirectUri();
MP 134         String serviceTicket = clientSession.getNote(CASLoginProtocol.SESSION_SERVICE_TICKET);
135         //check if session is fully authenticated (i.e. serviceValidate has been called)
136         if (serviceTicket != null && !serviceTicket.isEmpty()) {
137             sendSingleLogoutRequest(logoutUrl, serviceTicket);
138         }
7f7e0c 139         ClientModel client = clientSession.getClient();
8560e4 140         new ResourceAdminManager(session).logoutClientSession(realm, client, clientSession).close();
0ec410 141         return Response.ok().build();
7f7e0c 142     }
MP 143
57a6c1 144     private void sendSingleLogoutRequest(String logoutUrl, String serviceTicket) {
MP 145         try {
281a7e 146             HttpEntity requestEntity = LogoutHelper.buildSingleLogoutRequest(serviceTicket);
57a6c1 147             LogoutHelper.postWithRedirect(session, logoutUrl, requestEntity);
MP 148             logger.debug("Sent CAS single logout for service " + logoutUrl);
149         } catch (IOException e) {
150             logger.warn("Failed to call CAS service for logout: " + logoutUrl, e);
151         }
152     }
153
7f7e0c 154     @Override
f75caf 155     public Response frontchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
7f7e0c 156         // todo oidc redirect support
MP 157         throw new RuntimeException("NOT IMPLEMENTED");
158     }
159
160     @Override
d5f868 161     public Response finishBrowserLogout(UserSessionModel userSession, AuthenticationSessionModel logoutSession) {
4a6620 162         String redirectUri = userSession.getNote(CASLoginProtocol.LOGOUT_REDIRECT_URI);
MP 163
b88dc3 164         event.event(EventType.LOGOUT)
AP 165             .user(userSession.getUser())
166             .session(userSession)
167             .detail(Details.USERNAME, userSession.getUser().getUsername());
cbb2f2 168
4a6620 169         if (redirectUri != null) {
b88dc3 170             event.detail(Details.REDIRECT_URI, redirectUri);
AP 171             event.success();
cbb2f2 172             return Response.status(302).location(URI.create(redirectUri)).build();
4a6620 173         }
b88dc3 174
AP 175         event.success();
176
177         LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setSuccess("Logout successful");
178         infoPage.setAttribute("skipLink", true);
179         return infoPage.createInfoPage();
7f7e0c 180     }
MP 181
182     @Override
f75caf 183     public boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession) {
MP 184         return "true".equals(authSession.getClientNote(CASLoginProtocol.RENEW_PARAM));
7f7e0c 185     }
MP 186
187     @Override
188     public void close() {
189
190     }
191 }