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

Alexandre Rocha Wendling
2024-06-26 755fd78fa0ee0f2a67417a119382c63e02c1091e
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;
755fd7 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";
755fd7 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-";
755fd7 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
755fd7 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();
b92028 140         return new ResourceAdminManager(session).logoutClientSession(realm, client, clientSession);
7f7e0c 141     }
MP 142
57a6c1 143     private void sendSingleLogoutRequest(String logoutUrl, String serviceTicket) {
MP 144         try {
281a7e 145             HttpEntity requestEntity = LogoutHelper.buildSingleLogoutRequest(serviceTicket);
57a6c1 146             LogoutHelper.postWithRedirect(session, logoutUrl, requestEntity);
MP 147             logger.debug("Sent CAS single logout for service " + logoutUrl);
148         } catch (IOException e) {
149             logger.warn("Failed to call CAS service for logout: " + logoutUrl, e);
150         }
151     }
152
7f7e0c 153     @Override
f75caf 154     public Response frontchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
7f7e0c 155         // todo oidc redirect support
MP 156         throw new RuntimeException("NOT IMPLEMENTED");
157     }
158
159     @Override
d5f868 160     public Response finishBrowserLogout(UserSessionModel userSession, AuthenticationSessionModel logoutSession) {
4a6620 161         String redirectUri = userSession.getNote(CASLoginProtocol.LOGOUT_REDIRECT_URI);
MP 162
b88dc3 163         event.event(EventType.LOGOUT)
AP 164             .user(userSession.getUser())
165             .session(userSession)
166             .detail(Details.USERNAME, userSession.getUser().getUsername());
cbb2f2 167
4a6620 168         if (redirectUri != null) {
b88dc3 169             event.detail(Details.REDIRECT_URI, redirectUri);
AP 170             event.success();
cbb2f2 171             return Response.status(302).location(URI.create(redirectUri)).build();
4a6620 172         }
b88dc3 173
AP 174         event.success();
175
176         LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setSuccess("Logout successful");
177         infoPage.setAttribute("skipLink", true);
178         return infoPage.createInfoPage();
7f7e0c 179     }
MP 180
181     @Override
f75caf 182     public boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession) {
MP 183         return "true".equals(authSession.getClientNote(CASLoginProtocol.RENEW_PARAM));
7f7e0c 184     }
MP 185
186     @Override
187     public void close() {
188
189     }
190 }