Instead of using hardcoded number, using proper constant/enum values

This commit is contained in:
Matthias Wessendorf 2014-01-27 12:37:40 +01:00
parent 3e15747836
commit 55388319cc
11 changed files with 52 additions and 50 deletions

View file

@ -14,6 +14,7 @@ import org.keycloak.representations.SkeletonKeyToken;
import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
@ -67,7 +68,7 @@ public class AuthenticatedActionsValve extends ValveBase {
protected void queryBearerToken(Request request, Response response, SkeletonKeySession session) throws IOException, ServletException {
log.debugv("queryBearerToken {0}", request.getRequestURI());
if (abortTokenResponse(request, response, session)) return;
response.setStatus(200);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain");
response.getOutputStream().write(session.getTokenString().getBytes());
response.getOutputStream().flush();
@ -77,15 +78,15 @@ public class AuthenticatedActionsValve extends ValveBase {
protected boolean abortTokenResponse(Request request, Response response, SkeletonKeySession session) throws IOException {
if (session == null) {
log.debugv("session was null, sending back 401: {0}", request.getRequestURI());
response.sendError(401);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return true;
}
if (!config.isExposeToken()) {
response.setStatus(200);
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
if (!config.isCors() && request.getHeader("Origin") != null) {
response.setStatus(200);
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
return false;
@ -110,7 +111,7 @@ public class AuthenticatedActionsValve extends ValveBase {
log.debugv("allowedOrigins did not contain origin");
}
response.sendError(403);
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return true;
}
log.debugv("returning origin: {0}", origin);

View file

@ -90,14 +90,14 @@ public class CatalinaBearerTokenAuthenticator {
String surrogate = null;
if (verifyCaller) {
if (token.getTrustedCertificates() == null || token.getTrustedCertificates().size() == 0) {
response.sendError(400);
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
throw new LoginException("No trusted certificates in token");
}
// for now, we just make sure JBoss Web did two-way SSL
// assume JBoss Web verifies the client cert
X509Certificate[] chain = request.getCertificateChain();
if (chain == null || chain.length == 0) {
response.sendError(400);
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
throw new LoginException("No certificates provided by jboss web to verify the caller");
}
surrogate = chain[0].getSubjectX500Principal().getName();
@ -124,7 +124,7 @@ public class CatalinaBearerTokenAuthenticator {
}
response.setHeader("WWW-Authenticate", header.toString());
try {
response.sendError(401);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} catch (IOException e) {
throw new RuntimeException(e);
}

View file

@ -5,6 +5,8 @@ import org.apache.catalina.connector.Response;
import org.jboss.logging.Logger;
import org.keycloak.representations.adapters.config.AdapterConfig;
import javax.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
@ -29,7 +31,7 @@ public class CorsPreflightChecker {
return false;
}
log.debug("Preflight request returning");
response.setStatus(200);
response.setStatus(HttpServletResponse.SC_OK);
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");

View file

@ -126,7 +126,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
String token = StreamUtil.readString(request.getInputStream());
if (token == null) {
log.warn("admin request failed, no token");
response.sendError(403, "no token");
response.sendError(HttpServletResponse.SC_FORBIDDEN, "no token");
return null;
}
@ -138,7 +138,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
}
if (!verified) {
log.warn("admin request failed, unable to verify token");
response.sendError(403, "verification failed");
response.sendError(HttpServletResponse.SC_FORBIDDEN, "verification failed");
return null;
}
return input;
@ -150,12 +150,12 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
LogoutAction action = JsonSerialization.readValue(token.getContent(), LogoutAction.class);
if (action.isExpired()) {
log.warn("admin request failed, expired token");
response.sendError(400, "Expired token");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expired token");
return;
}
if (!resourceMetadata.getResourceName().equals(action.getResource())) {
log.warn("Resource name does not match");
response.sendError(400, "Resource name does not match");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Resource name does not match");
return;
}
@ -169,9 +169,9 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
}
} catch (Exception e) {
log.warn("failed to logout", e);
response.sendError(500, "Failed to logout");
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to logout");
}
response.setStatus(204);
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
protected boolean bearer(boolean challenge, Request request, HttpServletResponse response) throws LoginException, IOException {
@ -208,7 +208,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
if (code == null) {
String error = oauth.getError();
if (error != null) {
response.sendError(400, "OAuth " + error);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "OAuth " + error);
return;
} else {
saveRequest(request, request.getSessionInternal(true));

View file

@ -170,7 +170,7 @@ public class ServletOAuthLogin {
Cookie stateCookie = getCookie(realmInfo.getStateCookieName());
if (stateCookie == null) {
sendError(400);
sendError(HttpServletResponse.SC_BAD_REQUEST);
log.warn("No state cookie");
return false;
}
@ -185,12 +185,12 @@ public class ServletOAuthLogin {
// its ok to call request.getParameter() because this should be a redirect
String state = request.getParameter("state");
if (state == null) {
sendError(400);
sendError(HttpServletResponse.SC_BAD_REQUEST);
log.warn("state parameter was null");
return false;
}
if (!state.equals(stateCookieValue)) {
sendError(400);
sendError(HttpServletResponse.SC_BAD_REQUEST);
log.warn("state parameter invalid");
log.warn("cookie: " + stateCookieValue);
log.warn("queryParam: " + state);
@ -229,7 +229,7 @@ public class ServletOAuthLogin {
} catch (TokenGrantRequest.HttpFailure failure) {
log.error("failed to turn code into token");
log.error("status from server: " + failure.getStatus());
if (failure.getStatus() == 400 && failure.getError() != null) {
if (failure.getStatus() == HttpServletResponse.SC_BAD_REQUEST && failure.getError() != null) {
log.error(" " + failure.getError());
}
sendError(HttpServletResponse.SC_FORBIDDEN);

View file

@ -42,7 +42,7 @@ public class JaxrsBearerTokenFilter implements ContainerRequestFilter {
if (description != null) {
header.append(", error_description=\"").append(description).append("\"");
}
request.abortWith(Response.status(401).header("WWW-Authenticate", header.toString()).build());
request.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, header.toString()).build());
return;
}

View file

@ -3,6 +3,7 @@ package org.keycloak.adapters.undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.SkeletonKeySession;
import org.keycloak.adapters.AdapterConstants;
@ -56,7 +57,7 @@ public class AuthenticatedActionsHandler implements HttpHandler {
protected void queryBearerToken(HttpServerExchange exchange, SkeletonKeySession session) throws IOException, ServletException {
log.debugv("queryBearerToken {0}",exchange.getRequestURI());
if (abortTokenResponse(exchange, session)) return;
exchange.setResponseCode(200);
exchange.setResponseCode(StatusCodes.OK);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send(session.getTokenString());
exchange.endExchange();
@ -70,12 +71,12 @@ public class AuthenticatedActionsHandler implements HttpHandler {
return true;
}
if (!adapterConfig.isExposeToken()) {
exchange.setResponseCode(200);
exchange.setResponseCode(StatusCodes.OK);
exchange.endExchange();
return true;
}
if (!adapterConfig.isCors() && exchange.getRequestHeaders().getFirst(Headers.ORIGIN) != null) {
exchange.setResponseCode(200);
exchange.setResponseCode(StatusCodes.OK);
exchange.endExchange();
return true;
}
@ -101,12 +102,12 @@ public class AuthenticatedActionsHandler implements HttpHandler {
log.debugv("allowedOrigins did not contain origin");
}
exchange.setResponseCode(403);
exchange.setResponseCode(StatusCodes.FORBIDDEN);
exchange.endExchange();
return true;
}
log.debugv("returning origin: {0}", origin);
exchange.setResponseCode(200);
exchange.setResponseCode(StatusCodes.OK);
exchange.getResponseHeaders().put(PreflightCorsHandler.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
exchange.getResponseHeaders().put(PreflightCorsHandler.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
} else {

View file

@ -6,6 +6,7 @@ import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.Cookie;
import io.undertow.server.handlers.CookieImpl;
import io.undertow.util.Headers;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.RSATokenVerifier;
import org.keycloak.adapters.config.RealmConfiguration;
@ -129,14 +130,14 @@ public class OAuthAuthenticator {
@Override
public AuthenticationMechanism.ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
if (redirect == null) {
return new AuthenticationMechanism.ChallengeResult(true, 403);
return new AuthenticationMechanism.ChallengeResult(true, StatusCodes.FORBIDDEN);
}
CookieImpl cookie = new CookieImpl(realmInfo.getStateCookieName(), state);
//cookie.setPath(getDefaultCookiePath()); todo I don't think we need to set state cookie path as it will be the same redirect
cookie.setSecure(realmInfo.isSslRequired());
exchange.setResponseCookie(cookie);
exchange.getResponseHeaders().put(Headers.LOCATION, redirect);
return new AuthenticationMechanism.ChallengeResult(true, 302);
return new AuthenticationMechanism.ChallengeResult(true, StatusCodes.FOUND);
}
};
}
@ -146,7 +147,7 @@ public class OAuthAuthenticator {
if (stateCookie == null) {
log.warn("No state cookie");
return challenge(400);
return challenge(StatusCodes.BAD_REQUEST);
}
// reset the cookie
log.info("** reseting application state cookie");
@ -160,13 +161,13 @@ public class OAuthAuthenticator {
String state = getQueryParamValue("state");
if (state == null) {
log.warn("state parameter was null");
return challenge(400);
return challenge(StatusCodes.BAD_REQUEST);
}
if (!state.equals(stateCookieValue)) {
log.warn("state parameter invalid");
log.warn("cookie: " + stateCookieValue);
log.warn("queryParam: " + state);
return challenge(400);
return challenge(StatusCodes.BAD_REQUEST);
}
return null;
@ -180,7 +181,7 @@ public class OAuthAuthenticator {
if (error != null) {
// todo how do we send a response?
log.warn("There was an error: " + error);
challenge = challenge(400);
challenge = challenge(StatusCodes.BAD_REQUEST);
return AuthenticationMechanism.AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
} else {
log.info("redirecting to auth server");
@ -223,7 +224,7 @@ public class OAuthAuthenticator {
// abort if not HTTPS
if (realmInfo.isSslRequired() && !isRequestSecure()) {
log.error("SSL is required");
return challenge(403);
return challenge(StatusCodes.FORBIDDEN);
}
log.info("checking state cookie for after code");
@ -237,14 +238,14 @@ public class OAuthAuthenticator {
} catch (TokenGrantRequest.HttpFailure failure) {
log.error("failed to turn code into token");
log.error("status from server: " + failure.getStatus());
if (failure.getStatus() == 400 && failure.getError() != null) {
if (failure.getStatus() == StatusCodes.BAD_REQUEST && failure.getError() != null) {
log.error(" " + failure.getError());
}
return challenge(403);
return challenge(StatusCodes.FORBIDDEN);
} catch (IOException e) {
log.error("failed to turn code into token");
return challenge(403);
return challenge(StatusCodes.FORBIDDEN);
}
tokenString = tokenResponse.getToken();
@ -253,7 +254,7 @@ public class OAuthAuthenticator {
log.debug("Token Verification succeeded!");
} catch (VerificationException e) {
log.error("failed verification of token");
return challenge(403);
return challenge(StatusCodes.FORBIDDEN);
}
log.info("successful authenticated");
return null;

View file

@ -4,6 +4,7 @@ import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.representations.adapters.config.AdapterConfig;
@ -54,7 +55,7 @@ public class PreflightCorsHandler implements HttpHandler {
return;
}
log.debug("Preflight request returning");
exchange.setResponseCode(200);
exchange.setResponseCode(StatusCodes.OK);
String origin = exchange.getRequestHeaders().getFirst("Origin");
exchange.getResponseHeaders().put(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
exchange.getResponseHeaders().put(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

View file

@ -5,6 +5,7 @@ import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.session.SessionManager;
import io.undertow.servlet.handlers.ServletRequestContext;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.adapters.AdapterConstants;
import org.keycloak.adapters.config.RealmConfiguration;
@ -53,7 +54,7 @@ public class ServletAdminActionsHandler implements HttpHandler {
String token = StreamUtil.readString(request.getInputStream());
if (token == null) {
log.warn("admin request failed, no token");
response.sendError(403, "no token");
response.sendError(StatusCodes.FORBIDDEN, "no token");
return null;
}
@ -65,7 +66,7 @@ public class ServletAdminActionsHandler implements HttpHandler {
}
if (!verified) {
log.warn("admin request failed, unable to verify token");
response.sendError(403, "verification failed");
response.sendError(StatusCodes.FORBIDDEN, "verification failed");
return null;
}
return input;

View file

@ -6,24 +6,19 @@ import io.undertow.server.session.Session;
import io.undertow.server.session.SessionListener;
import io.undertow.server.session.SessionManager;
import io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.SkeletonKeySession;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.representations.adapters.action.LogoutAction;
import org.keycloak.util.JsonSerialization;
import org.keycloak.util.StreamUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ -50,12 +45,12 @@ public class UserSessionManagement implements SessionListener {
LogoutAction action = JsonSerialization.readValue(token.getContent(), LogoutAction.class);
if (action.isExpired()) {
log.warn("admin request failed, expired token");
response.sendError(400, "Expired token");
response.sendError(StatusCodes.BAD_REQUEST, "Expired token");
return;
}
if (!realmInfo.getMetadata().getResourceName().equals(action.getResource())) {
log.warn("Resource name does not match");
response.sendError(400, "Resource name does not match");
response.sendError(StatusCodes.BAD_REQUEST, "Resource name does not match");
return;
}
@ -69,9 +64,9 @@ public class UserSessionManagement implements SessionListener {
}
} catch (Exception e) {
log.warn("failed to logout", e);
response.sendError(500, "Failed to logout");
response.sendError(StatusCodes.INTERNAL_SERVER_ERROR, "Failed to logout");
}
response.setStatus(204);
response.setStatus(StatusCodes.NO_CONTENT);
}
public void login(SessionManager manager, HttpSession session, String username) {