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

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