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

Unknown
2017-07-26 8c9be26e6a05af07a7439ea29afd67e29b97fd5f
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;
46     protected ClientSessionModel clientSession;
47
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
134         ClientSessionCode.ParseResult parseResult = ClientSessionCode.parseResult(code, session, realm);
135         if (parseResult.isClientSessionNotFound() || parseResult.isIllegalHash()) {
136             String[] parts = code.split("\\.");
137             if (parts.length == 2) {
138                 event.detail(Details.CODE_ID, parts[1]);
139             }
140             event.error(Errors.INVALID_CODE);
141             if (parseResult.getClientSession() != null) {
142                 session.sessions().removeClientSession(realm, parseResult.getClientSession());
143             }
352436 144             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Code not valid", Response.Status.BAD_REQUEST);
7f7e0c 145         }
MP 146
147         clientSession = parseResult.getClientSession();
148         event.detail(Details.CODE_ID, clientSession.getId());
149
150         if (!parseResult.getCode().isValid(ClientSessionModel.Action.CODE_TO_TOKEN.name(), ClientSessionCode.ActionType.CLIENT)) {
151             event.error(Errors.INVALID_CODE);
352436 152             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Code is expired", Response.Status.BAD_REQUEST);
7f7e0c 153         }
MP 154
57a6c1 155         clientSession.setNote(CASLoginProtocol.SESSION_SERVICE_TICKET, ticket);
7f7e0c 156         parseResult.getCode().setAction(null);
MP 157
7124d2 158         if (requireReauth && AuthenticationManager.isSSOAuthentication(clientSession)) {
MP 159             event.error(Errors.SESSION_EXPIRED);
160             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Interactive authentication was requested but not performed", Response.Status.BAD_REQUEST);
161         }
162
7f7e0c 163         UserSessionModel userSession = clientSession.getUserSession();
MP 164
165         if (userSession == null) {
166             event.error(Errors.USER_SESSION_NOT_FOUND);
352436 167             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User session not found", Response.Status.BAD_REQUEST);
7f7e0c 168         }
MP 169
170         UserModel user = userSession.getUser();
171         if (user == null) {
172             event.error(Errors.USER_NOT_FOUND);
352436 173             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User not found", Response.Status.BAD_REQUEST);
7f7e0c 174         }
MP 175         if (!user.isEnabled()) {
176             event.error(Errors.USER_DISABLED);
352436 177             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User disabled", Response.Status.BAD_REQUEST);
7f7e0c 178         }
MP 179
180         event.user(userSession.getUser());
181         event.session(userSession.getId());
182
183         if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
184             event.error(Errors.INVALID_CODE);
352436 185             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Auth error", Response.Status.BAD_REQUEST);
7f7e0c 186         }
MP 187
188         if (!AuthenticationManager.isSessionValid(realm, userSession)) {
189             event.error(Errors.USER_SESSION_NOT_FOUND);
352436 190             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Session not active", Response.Status.BAD_REQUEST);
7f7e0c 191         }
MP 192
193     }
194 }