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

Doccrazy
2017-11-14 541aa23b71af594da8f576495fabb3c0fa429aae
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
139         ClientSessionCode.ParseResult<AuthenticatedClientSessionModel> parseResult = ClientSessionCode.parseResult(code, session, realm, AuthenticatedClientSessionModel.class);
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) {
146                 clientSession.setUserSession(null);
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
f75caf 154         if (!parseResult.getCode().isValid(AuthenticatedClientSessionModel.Action.CODE_TO_TOKEN.name(), ClientSessionCode.ActionType.CLIENT)) {
7f7e0c 155             event.error(Errors.INVALID_CODE);
352436 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         parseResult.getCode().setAction(null);
MP 161
7124d2 162         if (requireReauth && AuthenticationManager.isSSOAuthentication(clientSession)) {
MP 163             event.error(Errors.SESSION_EXPIRED);
164             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Interactive authentication was requested but not performed", Response.Status.BAD_REQUEST);
165         }
166
7f7e0c 167         UserSessionModel userSession = clientSession.getUserSession();
MP 168
169         if (userSession == null) {
170             event.error(Errors.USER_SESSION_NOT_FOUND);
352436 171             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User session not found", Response.Status.BAD_REQUEST);
7f7e0c 172         }
MP 173
174         UserModel user = userSession.getUser();
175         if (user == null) {
176             event.error(Errors.USER_NOT_FOUND);
352436 177             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User not found", Response.Status.BAD_REQUEST);
7f7e0c 178         }
MP 179         if (!user.isEnabled()) {
180             event.error(Errors.USER_DISABLED);
352436 181             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "User disabled", Response.Status.BAD_REQUEST);
7f7e0c 182         }
MP 183
184         event.user(userSession.getUser());
185         event.session(userSession.getId());
186
187         if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
188             event.error(Errors.INVALID_CODE);
352436 189             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Auth error", Response.Status.BAD_REQUEST);
7f7e0c 190         }
MP 191
192         if (!AuthenticationManager.isSessionValid(realm, userSession)) {
193             event.error(Errors.USER_SESSION_NOT_FOUND);
352436 194             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Session not active", Response.Status.BAD_REQUEST);
7f7e0c 195         }
MP 196
197     }
198 }