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

github-actions
2023-02-21 9611602e6a9532220a03bb286351fd0379a5e8bc
commit | author | age
7f7e0c 1 package org.keycloak.protocol.cas;
MP 2
57a6c1 3 import org.apache.http.HttpEntity;
MP 4 import org.jboss.logging.Logger;
7f7e0c 5 import org.keycloak.common.util.KeycloakUriBuilder;
c140ce 6 import org.keycloak.common.util.Time;
b88dc3 7 import org.keycloak.events.Details;
7f7e0c 8 import org.keycloak.events.EventBuilder;
MP 9 import org.keycloak.events.EventType;
4a6620 10 import org.keycloak.forms.login.LoginFormsProvider;
7f7e0c 11 import org.keycloak.models.*;
MP 12 import org.keycloak.protocol.LoginProtocol;
57a6c1 13 import org.keycloak.protocol.cas.utils.LogoutHelper;
c140ce 14 import org.keycloak.protocol.oidc.utils.OAuth2Code;
MP 15 import org.keycloak.protocol.oidc.utils.OAuth2CodeParser;
3882f0 16 import org.keycloak.services.ErrorPage;
7f7e0c 17 import org.keycloak.services.managers.ResourceAdminManager;
f75caf 18 import org.keycloak.sessions.AuthenticationSessionModel;
7f7e0c 19
MP 20 import javax.ws.rs.core.HttpHeaders;
21 import javax.ws.rs.core.Response;
22 import javax.ws.rs.core.UriInfo;
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(),
MP 103                 null, null, authSession.getRedirectUri(), null, null);
104         String code = OAuth2CodeParser.persistCode(session, clientSession, codeData);
105
7f7e0c 106         KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(service);
891484 107
DR 108         String loginTicket = SERVICE_TICKET_PREFIX + code;
109
110         if (authSession.getClientNotes().containsKey(CASLoginProtocol.TARGET_PARAM)) {
111             // This was a SAML 1.1 auth request so return the ticket ID as "SAMLart" instead of "ticket"
112             uriBuilder.queryParam(SAMLART_RESPONSE_PARAM, loginTicket);
113         } else {
114             uriBuilder.queryParam(TICKET_RESPONSE_PARAM, loginTicket);
115         }
7f7e0c 116
MP 117         URI redirectUri = uriBuilder.build();
118
119         Response.ResponseBuilder location = Response.status(302).location(redirectUri);
120         return location.build();
121     }
122
123     @Override
f75caf 124     public Response sendError(AuthenticationSessionModel authSession, Error error) {
3882f0 125         if (authSession.getClientNotes().containsKey(CASLoginProtocol.GATEWAY_PARAM)) {
JK 126             if (error == Error.PASSIVE_INTERACTION_REQUIRED || error == Error.PASSIVE_LOGIN_REQUIRED) {
127                 return Response.status(302).location(URI.create(authSession.getRedirectUri())).build();
128             }
129         }
130         return ErrorPage.error(session, authSession, Response.Status.INTERNAL_SERVER_ERROR, error.name());
7f7e0c 131     }
MP 132
133     @Override
0ec410 134     public Response backchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
57a6c1 135         String logoutUrl = clientSession.getRedirectUri();
MP 136         String serviceTicket = clientSession.getNote(CASLoginProtocol.SESSION_SERVICE_TICKET);
137         //check if session is fully authenticated (i.e. serviceValidate has been called)
138         if (serviceTicket != null && !serviceTicket.isEmpty()) {
139             sendSingleLogoutRequest(logoutUrl, serviceTicket);
140         }
7f7e0c 141         ClientModel client = clientSession.getClient();
019db5 142         new ResourceAdminManager(session).logoutClientSession(realm, client, clientSession);
0ec410 143         return Response.ok().build();
7f7e0c 144     }
MP 145
57a6c1 146     private void sendSingleLogoutRequest(String logoutUrl, String serviceTicket) {
MP 147         try {
281a7e 148             HttpEntity requestEntity = LogoutHelper.buildSingleLogoutRequest(serviceTicket);
57a6c1 149             LogoutHelper.postWithRedirect(session, logoutUrl, requestEntity);
MP 150             logger.debug("Sent CAS single logout for service " + logoutUrl);
151         } catch (IOException e) {
152             logger.warn("Failed to call CAS service for logout: " + logoutUrl, e);
153         }
154     }
155
7f7e0c 156     @Override
f75caf 157     public Response frontchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
7f7e0c 158         // todo oidc redirect support
MP 159         throw new RuntimeException("NOT IMPLEMENTED");
160     }
161
162     @Override
d5f868 163     public Response finishBrowserLogout(UserSessionModel userSession, AuthenticationSessionModel logoutSession) {
4a6620 164         String redirectUri = userSession.getNote(CASLoginProtocol.LOGOUT_REDIRECT_URI);
MP 165
b88dc3 166         event.event(EventType.LOGOUT)
AP 167             .user(userSession.getUser())
168             .session(userSession)
169             .detail(Details.USERNAME, userSession.getUser().getUsername());
cbb2f2 170
4a6620 171         if (redirectUri != null) {
b88dc3 172             event.detail(Details.REDIRECT_URI, redirectUri);
AP 173             event.success();
cbb2f2 174             return Response.status(302).location(URI.create(redirectUri)).build();
4a6620 175         }
b88dc3 176
AP 177         event.success();
178
179         LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setSuccess("Logout successful");
180         infoPage.setAttribute("skipLink", true);
181         return infoPage.createInfoPage();
7f7e0c 182     }
MP 183
184     @Override
f75caf 185     public boolean requireReauthentication(UserSessionModel userSession, AuthenticationSessionModel authSession) {
MP 186         return "true".equals(authSession.getClientNote(CASLoginProtocol.RENEW_PARAM));
7f7e0c 187     }
MP 188
189     @Override
190     public void close() {
191
192     }
193 }