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

Matthias Piepkorn
2018-06-17 b8d686069c3249e4bd11eb5eef95f5bd51ea58fb
commit | author | age
7f7e0c 1 package org.keycloak.protocol.cas.endpoints;
MP 2
3 import org.jboss.logging.Logger;
4 import org.jboss.resteasy.annotations.cache.NoCache;
5 import org.jboss.resteasy.spi.HttpRequest;
6 import org.keycloak.common.ClientConnection;
7 import org.keycloak.events.Details;
8 import org.keycloak.events.Errors;
9 import org.keycloak.events.EventBuilder;
10 import org.keycloak.events.EventType;
11 import org.keycloak.models.*;
12 import org.keycloak.protocol.cas.CASLoginProtocol;
352436 13 import org.keycloak.protocol.cas.representations.CASErrorCode;
MP 14 import org.keycloak.protocol.cas.utils.CASValidationException;
7f7e0c 15 import org.keycloak.protocol.oidc.utils.RedirectUtils;
MP 16 import org.keycloak.services.managers.AuthenticationManager;
17 import org.keycloak.services.managers.ClientSessionCode;
18
19 import javax.ws.rs.GET;
20 import javax.ws.rs.core.*;
21
22 public class ValidateEndpoint {
57a6c1 23     protected static final Logger logger = Logger.getLogger(ValidateEndpoint.class);
7f7e0c 24
MP 25     private static final String RESPONSE_OK = "yes\n";
26     private static final String RESPONSE_FAILED = "no\n";
27
28     @Context
29     protected KeycloakSession session;
30
31     @Context
32     protected ClientConnection clientConnection;
33
34     @Context
35     protected HttpRequest request;
36
37     @Context
38     protected HttpHeaders headers;
39
40     @Context
41     protected UriInfo uriInfo;
42
43     protected RealmModel realm;
44     protected EventBuilder event;
45     protected ClientModel client;
f75caf 46     protected AuthenticatedClientSessionModel clientSession;
7f7e0c 47
MP 48     public ValidateEndpoint(RealmModel realm, EventBuilder event) {
49         this.realm = realm;
50         this.event = event;
51     }
52
53     @GET
54     @NoCache
55     public Response build() {
56         MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
57         String service = params.getFirst(CASLoginProtocol.SERVICE_PARAM);
58         String ticket = params.getFirst(CASLoginProtocol.TICKET_PARAM);
7124d2 59         boolean renew = params.containsKey(CASLoginProtocol.RENEW_PARAM);
7f7e0c 60
MP 61         event.event(EventType.CODE_TO_TOKEN);
62
63         try {
64             checkSsl();
65             checkRealm();
66             checkClient(service);
67
68             checkTicket(ticket, renew);
69
70             event.success();
71             return successResponse();
352436 72         } catch (CASValidationException e) {
7f7e0c 73             return errorResponse(e);
MP 74         }
75     }
76
77     protected Response successResponse() {
78         return Response.ok(RESPONSE_OK).type(MediaType.TEXT_PLAIN).build();
79     }
80
352436 81     protected Response errorResponse(CASValidationException e) {
MP 82         return Response.status(e.getStatus()).entity(RESPONSE_FAILED).type(MediaType.TEXT_PLAIN).build();
7f7e0c 83     }
MP 84
85     private void checkSsl() {
86         if (!uriInfo.getBaseUri().getScheme().equals("https") && realm.getSslRequired().isRequired(clientConnection)) {
352436 87             throw new CASValidationException(CASErrorCode.INVALID_REQUEST, "HTTPS required", Response.Status.FORBIDDEN);
7f7e0c 88         }
MP 89     }
90
91     private void checkRealm() {
92         if (!realm.isEnabled()) {
352436 93             throw new CASValidationException(CASErrorCode.INTERNAL_ERROR, "Realm not enabled", Response.Status.FORBIDDEN);
7f7e0c 94         }
MP 95     }
96
97     private void checkClient(String service) {
98         if (service == null) {
99             event.error(Errors.INVALID_REQUEST);
352436 100             throw new CASValidationException(CASErrorCode.INVALID_REQUEST, "Missing parameter: " + CASLoginProtocol.SERVICE_PARAM, Response.Status.BAD_REQUEST);
7f7e0c 101         }
MP 102
103         client = realm.getClients().stream()
104                 .filter(c -> CASLoginProtocol.LOGIN_PROTOCOL.equals(c.getProtocol()))
105                 .filter(c -> RedirectUtils.verifyRedirectUri(uriInfo, service, realm, c) != null)
106                 .findFirst().orElse(null);
107         if (client == null) {
108             event.error(Errors.CLIENT_NOT_FOUND);
352436 109             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Client not found", Response.Status.BAD_REQUEST);
7f7e0c 110         }
MP 111
112         if (!client.isEnabled()) {
113             event.error(Errors.CLIENT_DISABLED);
352436 114             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Client disabled", Response.Status.BAD_REQUEST);
7f7e0c 115         }
MP 116
117         event.client(client.getClientId());
118
119         session.getContext().setClient(client);
120     }
121
122     private void checkTicket(String ticket, boolean requireReauth) {
352436 123         if (ticket == null) {
7f7e0c 124             event.error(Errors.INVALID_CODE);
352436 125             throw new CASValidationException(CASErrorCode.INVALID_REQUEST, "Missing parameter: " + CASLoginProtocol.TICKET_PARAM, Response.Status.BAD_REQUEST);
MP 126         }
127         if (!ticket.startsWith(CASLoginProtocol.SERVICE_TICKET_PREFIX)) {
128             event.error(Errors.INVALID_CODE);
129             throw new CASValidationException(CASErrorCode.INVALID_TICKET_SPEC, "Malformed service ticket", Response.Status.BAD_REQUEST);
7f7e0c 130         }
MP 131
132         String code = ticket.substring(CASLoginProtocol.SERVICE_TICKET_PREFIX.length());
133
f75caf 134         String[] parts = code.split("\\.");
MP 135         if (parts.length == 4) {
136             event.detail(Details.CODE_ID, parts[2]);
137         }
138
6638b8 139         ClientSessionCode.ParseResult<AuthenticatedClientSessionModel> parseResult = ClientSessionCode.parseResult(code, null, session, realm, client, event, AuthenticatedClientSessionModel.class);
f75caf 140         if (parseResult.isAuthSessionNotFound() || parseResult.isIllegalHash()) {
7f7e0c 141             event.error(Errors.INVALID_CODE);
f75caf 142
MP 143             // Attempt to use same code twice should invalidate existing clientSession
144             AuthenticatedClientSessionModel clientSession = parseResult.getClientSession();
145             if (clientSession != null) {
6638b8 146                 clientSession.detachFromUserSession();
7f7e0c 147             }
f75caf 148
352436 149             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Code not valid", Response.Status.BAD_REQUEST);
7f7e0c 150         }
MP 151
152         clientSession = parseResult.getClientSession();
153
6638b8 154         if (parseResult.isExpiredToken()) {
MP 155             event.error(Errors.EXPIRED_CODE);
156             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Code is expired", Response.Status.BAD_REQUEST);
7f7e0c 157         }
MP 158
57a6c1 159         clientSession.setNote(CASLoginProtocol.SESSION_SERVICE_TICKET, ticket);
7f7e0c 160
7124d2 161         if (requireReauth && AuthenticationManager.isSSOAuthentication(clientSession)) {
MP 162             event.error(Errors.SESSION_EXPIRED);
163             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Interactive authentication was requested but not performed", Response.Status.BAD_REQUEST);
164         }
165
7f7e0c 166         UserSessionModel userSession = clientSession.getUserSession();
MP 167
168         if (userSession == null) {
169             event.error(Errors.USER_SESSION_NOT_FOUND);
352436 170             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User session not found", Response.Status.BAD_REQUEST);
7f7e0c 171         }
MP 172
173         UserModel user = userSession.getUser();
174         if (user == null) {
175             event.error(Errors.USER_NOT_FOUND);
352436 176             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User not found", Response.Status.BAD_REQUEST);
7f7e0c 177         }
MP 178         if (!user.isEnabled()) {
179             event.error(Errors.USER_DISABLED);
352436 180             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User disabled", Response.Status.BAD_REQUEST);
7f7e0c 181         }
MP 182
183         event.user(userSession.getUser());
184         event.session(userSession.getId());
185
186         if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
187             event.error(Errors.INVALID_CODE);
352436 188             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Auth error", Response.Status.BAD_REQUEST);
7f7e0c 189         }
MP 190
191         if (!AuthenticationManager.isSessionValid(realm, userSession)) {
192             event.error(Errors.USER_SESSION_NOT_FOUND);
352436 193             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Session not active", Response.Status.BAD_REQUEST);
7f7e0c 194         }
MP 195
196     }
197 }