Java Code Examples for io.undertow.server.HttpServerExchange#getQueryParameters()

The following examples show how to use io.undertow.server.HttpServerExchange#getQueryParameters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ModulesServiceActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            Map<String, Deque<String>> parameters = exchange.getQueryParameters();
            String action = parameters.get("action").getFirst();
            if (action.equals(ACTION_TEST_MODULE_RESOURCE)) {
                exchange.getResponseSender().send(ModuleResource.test());
                return;
            } else if (action.equals(ACTION_TEST_ABSOLUTE_RESOURCE)) {
                exchange.getResponseSender().send(AbsoluteResource.test());
                return;
            }
            exchange.getResponseSender().send("wrong reponse!");
        }
    };
}
 
Example 2
Source File: ListUserHandler.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleAsyncRequest(HttpServerExchange exchange, PooledByteBufferInputStream content)
		throws Exception {

	Map<String, Deque<String>> params = exchange.getQueryParameters();
	String pageNoStr = params.get("pageNo").getFirst();
	int pageNo = Integer.parseInt(pageNoStr);

	Page<User> userList = userService.listUser(pageNo);

	ByteBufferPool pool = exchange.getConnection().getByteBufferPool();
	PooledByteBufferOutputStream output = new PooledByteBufferOutputStream(pool);
	objectMapper.writeValue(output, userList);

	send(exchange, StatusCodes.OK, output);
}
 
Example 3
Source File: CommonsLoggingServiceActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            final Map<String, Deque<String>> params = exchange.getQueryParameters();
            String msg = DEFAULT_MESSAGE;
            if (params.containsKey("msg")) {
                msg = getFirstValue(params, "msg");
            }
            // Log all levels
            LOGGER.trace(msg);
            LOGGER.debug(msg);
            LOGGER.info(msg);
            LOGGER.warn(msg);
            LOGGER.error(msg);
            LOGGER.fatal(msg);
            exchange.getResponseSender().send("Response sent");
        }
    };
}
 
Example 4
Source File: Slf4jServiceActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            final Map<String, Deque<String>> params = exchange.getQueryParameters();
            String msg = DEFAULT_MESSAGE;
            if (params.containsKey("msg")) {
                msg = getFirstValue(params, "msg");
            }
            // Log all levels
            LOGGER.trace(msg);
            LOGGER.debug(msg);
            LOGGER.info(msg);
            LOGGER.warn(msg);
            LOGGER.error(msg);
            //LOGGER.fatal(msg);
            exchange.getResponseSender().send("Response sent");
        }
    };
}
 
Example 5
Source File: Log4jServiceActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final Map<String, Deque<String>> params = exchange.getQueryParameters();
            String msg = DEFAULT_MESSAGE;
            if (params.containsKey("msg")) {
                msg = getFirstValue(params, "msg");
            }
            boolean includeLevel = false;
            if (params.containsKey("includeLevel")) {
                includeLevel = Boolean.parseBoolean(getFirstValue(params, "includeLevel"));
            }
            for (Level level : LOG_LEVELS) {
                if (includeLevel) {
                    LOGGER.log(level, formatMessage(msg, level));
                } else {
                    LOGGER.log(level, msg);
                }
            }
            exchange.getResponseSender().send("Response sent");
        }
    };
}
 
Example 6
Source File: DomainApiHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private GetOperation getOperation(HttpServerExchange exchange) {
    Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();

    GetOperation operation = null;
    Deque<String> parameter = queryParameters.get(OP);
    if (parameter != null) {
        String value = parameter.getFirst();
        try {
            operation = GetOperation.valueOf(value.toUpperCase(Locale.ENGLISH).replace('-', '_'));
            value = operation.realOperation();
        } catch (Exception e) {
            throw HttpServerLogger.ROOT_LOGGER.invalidOperation(e, value);
        }
    }

    // This will now only occur if no operation at all was specified on the incoming request.
    if (operation == null) {
        operation = GetOperation.RESOURCE;
    }
    return operation;
}
 
Example 7
Source File: LoggerGetHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {

    Map<String, Deque<String>> parameters = exchange.getQueryParameters();
    String loggerName = parameters.get(LOGGER_NAME).getFirst();
    LoggerConfig config = (LoggerConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, LoggerConfig.class);

    if (config.isEnabled()) {
        ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName);
        LoggerInfo loggerInfo = new LoggerInfo();
        loggerInfo.setName(logger.getName());
        loggerInfo.setLevel(logger.getLevel().toString());

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
        exchange.getResponseSender().send(mapper.writeValueAsString(loggerInfo));
    } else {
        logger.error("Logging is disabled in logging.yml");
        setExchangeStatus(exchange, STATUS_LOGGER_INFO_DISABLED);
    }
}
 
Example 8
Source File: SymjaServer.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
	String jsonStr;
	HeaderMap responseHeaders = exchange.getResponseHeaders();
	responseHeaders.put(new HttpString("Access-Control-Allow-Origin"), "*");
	responseHeaders.put(Headers.CONTENT_TYPE, "application/json");

	Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();
	String appid = getAppID(queryParameters, "appid");
	if (appid != null) {
		if (appid.equals("DEMO")) {
			String inputStr = SymjaServer.getParam(queryParameters, "input", "i", "");
			String[] formformatStrs = SymjaServer.getParams(queryParameters, "format", "f", Pods.PLAIN_STR);
			int formats = Pods.internFormat(formformatStrs);
			ObjectNode messageJSON = Pods.createResult(inputStr, formats);
			jsonStr = messageJSON.toString();
		} else {
			jsonStr = Pods.errorJSONString("1", "Invalid appid");
		}
	} else {
		jsonStr = Pods.errorJSONString("2", "Appid missing");
	}
	exchange.getResponseSender().send(jsonStr);
}
 
Example 9
Source File: DomainApiHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ModelNode convertGetRequest(HttpServerExchange exchange, GetOperation operation) {
    ArrayList<String> pathSegments = decodePath(exchange.getRelativePath());
    Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();

    ModelNode dmr = new ModelNode();
    for (Entry<String, Deque<String>> entry : queryParameters.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue().getFirst();
        ModelNode valueNode = null;
        if (key.startsWith("operation-header-")) {
            String header = key.substring("operation-header-".length());
            //Remove the same headers as the native interface (ModelControllerClientOperationHandler)
            if (!header.equals(SYNC_REMOVED_FOR_READD) &&
                    !header.equals(EXECUTE_FOR_COORDINATOR) && !header.equals(DOMAIN_UUID)) {
                valueNode = dmr.get(OPERATION_HEADERS, header);
            }
        } else {
            valueNode = dmr.get(key);
        }
        if (valueNode != null) {
            valueNode.set(!value.equals("") ? value : "true");
        }
    }
    dmr.get(OP).set(operation.realOperation);

    ModelNode list = dmr.get(OP_ADDR).setEmptyList();
    for (int i = 0; i < pathSegments.size() - 1; i += 2) {
        list.add(pathSegments.get(i), pathSegments.get(i + 1));
    }
    return dmr;
}
 
Example 10
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static int getStreamIndex(final HttpServerExchange exchange, final HeaderMap requestHeaders) {
    // First check for an HTTP header
    int result = getStreamIndex(requestHeaders.get(USE_STREAM_AS_RESPONSE_HEADER));
    if (result == -1) {
        // Nope. Now check for a URL query parameter
        Map<String, Deque<String>> queryParams = exchange.getQueryParameters();
        result = getStreamIndex(queryParams.get(USE_STREAM_AS_RESPONSE));
    }
    return result;
}
 
Example 11
Source File: HttpServerExchangeParameterExtractor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String extractParameter(HttpServerExchange request) {
    final Map<String, Deque<String>> parameterMap = request.getQueryParameters();
    final StringBuilder params = new StringBuilder(64);
    for (Map.Entry<String, Deque<String>> entry : parameterMap.entrySet()) {
        if (params.length() != 0) {
            params.append('&');
        }
        // skip appending parameters if parameter size is bigger than totalLimit
        if (params.length() > totalLimit) {
            params.append("...");
            return params.toString();
        }
        final String key = entry.getKey();
        if (!StringUtils.hasLength(key)) {
            // skip empty or null header name
            continue;
        }
        // append key
        params.append(StringUtils.abbreviate(key, eachLimit));
        params.append('=');
        // append value
        Deque<String> values = entry.getValue();
        if (CollectionUtils.isEmpty(values)) {
            // skip empty or null header value
            continue;
        }
        for (String value : values) {
            if (value != null) {
                params.append(StringUtils.abbreviate(StringUtils.toString(value), eachLimit));
            }
        }
    }
    return params.toString();
}
 
Example 12
Source File: ListUserHandler.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
	Map<String, Deque<String>> params = exchange.getQueryParameters();
	String pageNoStr = params.get("pageNo").getFirst();
	int pageNo = Integer.parseInt(pageNoStr);

	Page<User> userList = userService.listUser(pageNo);

	byte[] bytes = objectMapper.writeValueAsBytes(userList);
	ByteBuffer buffer = ByteBufferUtils.allocate(bytes);

	exchange.getResponseSender().send(buffer);
}
 
Example 13
Source File: UserExistHandler.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleAsyncRequest(HttpServerExchange exchange, PooledByteBufferInputStream content)
		throws Exception {

	Map<String, Deque<String>> params = exchange.getQueryParameters();
	String email = params.get("email").getFirst();

	if (userService.existUser(email)) {
		send(exchange, StatusCodes.OK, "true");
	} else {
		send(exchange, StatusCodes.OK, "false");
	}
}
 
Example 14
Source File: UserExistHandler.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
	Map<String, Deque<String>> params = exchange.getQueryParameters();
	String email = params.get("email").getFirst();

	if (userService.existUser(email)) {
		exchange.getResponseSender().send(trueResult.duplicate());
	} else {
		exchange.getResponseSender().send(falseResult.duplicate());
	}
}
 
Example 15
Source File: GetUserHandler.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
	Map<String, Deque<String>> params = exchange.getQueryParameters();
	String idStr = params.get("id").getFirst();
	long id = Integer.parseInt(idStr);

	User user = userService.getUser(id);

	byte[] bytes = objectMapper.writeValueAsBytes(user);
	ByteBuffer buffer = ByteBufferUtils.allocate(bytes);

	exchange.getResponseSender().send(buffer);
}
 
Example 16
Source File: Oauth2AuthorizeGetHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    // parse all the parameters here as this is a redirected get request.
    Map<String, String> params = new HashMap<>();
    Map<String, Deque<String>> pnames = exchange.getQueryParameters();
    for (Map.Entry<String, Deque<String>> entry : pnames.entrySet()) {
        String pname = entry.getKey();
        Iterator<String> pvalues = entry.getValue().iterator();
        if(pvalues.hasNext()) {
            params.put(pname, pvalues.next());
        }
    }
    if(logger.isDebugEnabled()) logger.debug("params", params);
    String clientId = params.get("client_id");
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        String code = Util.getUUID();
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("userId", userId);
        String scope = params.get("scope");
        if(scope != null) {
            codeMap.put("scope", scope);
        }
        String redirectUri = params.get("redirect_uri");
        if(redirectUri == null) {
            redirectUri = client.getRedirectUri();
        } else {
            codeMap.put("redirectUri", redirectUri);
        }
        // https://tools.ietf.org/html/rfc7636#section-4 PKCE
        String codeChallenge = params.get(OAuth2Constants.CODE_CHALLENGE);
        String codeChallengeMethod = params.get(OAuth2Constants.CODE_CHALLENGE_METHOD);
        if (codeChallenge == null) {
            // PKCE is not used by this client.
            // Do we need to force native client to use PKCE?
        } else {
            if(codeChallengeMethod != null) {
                // https://tools.ietf.org/html/rfc7636#section-4.2
                // plain or S256
                if (!codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_S256) &&
                        !codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN)) {
                    setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_METHOD, codeChallengeMethod);
                    processAudit(exchange);
                    return;
                }
            } else {
                // https://tools.ietf.org/html/rfc7636#section-4.3
                // default code_challenge_method is plain
                codeChallengeMethod = CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN;
            }
            // validate codeChallenge.
            if(codeChallenge.length() < CodeVerifierUtil.MIN_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_SHORT, codeChallenge);
                processAudit(exchange);
                return;
            }
            if(codeChallenge.length() > CodeVerifierUtil.MAX_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_LONG, codeChallenge);
                processAudit(exchange);
                return;
            }
            // check the format
            Matcher m = CodeVerifierUtil.VALID_CODE_CHALLENGE_PATTERN.matcher(codeChallenge);
            if(!m.matches()) {
                setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_FORMAT, codeChallenge);
                processAudit(exchange);
                return;
            }
            // put the code challenge and method into the codes map.
            codeMap.put(OAuth2Constants.CODE_CHALLENGE, codeChallenge);
            codeMap.put(OAuth2Constants.CODE_CHALLENGE_METHOD, codeChallengeMethod);
        }

        CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);
        redirectUri = redirectUri + "?code=" + code;
        String state = params.get("state");
        if(state != null) {
            redirectUri = redirectUri + "&state=" + state;
        }
        if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
        // now redirect here.
        exchange.setStatusCode(StatusCodes.FOUND);
        exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
        exchange.endExchange();
        processAudit(exchange);
    }
}
 
Example 17
Source File: Oauth2CodeGetHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    // parse all the parameters here as this is a redirected get request.
    Map<String, String> params = new HashMap<>();
    Map<String, Deque<String>> pnames = exchange.getQueryParameters();
    for (Map.Entry<String, Deque<String>> entry : pnames.entrySet()) {
        String pname = entry.getKey();
        Iterator<String> pvalues = entry.getValue().iterator();
        if(pvalues.hasNext()) {
            params.put(pname, pvalues.next());
        }
    }
    if(logger.isDebugEnabled()) logger.debug("params", params);
    String clientId = params.get("client_id");
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        String code = Util.getUUID();
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        Set<String> roles = context.getAuthenticatedAccount().getRoles();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("userId", userId);
        if(roles != null && !roles.isEmpty()) {
            codeMap.put("roles", String.join(" ", roles));
        }
        String scope = params.get("scope");
        if(scope != null) {
            codeMap.put("scope", scope);
        }
        String redirectUri = params.get("redirect_uri");
        if(redirectUri == null) {
            redirectUri = client.getRedirectUri();
        } else {
            codeMap.put("redirectUri", redirectUri);
        }
        // https://tools.ietf.org/html/rfc7636#section-4 PKCE
        String codeChallenge = params.get(OAuth2Constants.CODE_CHALLENGE);
        String codeChallengeMethod = params.get(OAuth2Constants.CODE_CHALLENGE_METHOD);
        if (codeChallenge == null) {
            // PKCE is not used by this client.
            // Do we need to force native client to use PKCE?
        } else {
            if(codeChallengeMethod != null) {
                // https://tools.ietf.org/html/rfc7636#section-4.2
                // plain or S256
                if (!codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_S256) &&
                        !codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN)) {
                    setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_METHOD, codeChallengeMethod);
                    processAudit(exchange);
                    return;
                }
            } else {
                // https://tools.ietf.org/html/rfc7636#section-4.3
                // default code_challenge_method is plain
                codeChallengeMethod = CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN;
            }
            // validate codeChallenge.
            if(codeChallenge.length() < CodeVerifierUtil.MIN_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_SHORT, codeChallenge);
                processAudit(exchange);
                return;
            }
            if(codeChallenge.length() > CodeVerifierUtil.MAX_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_LONG, codeChallenge);
                processAudit(exchange);
                return;
            }
            // check the format
            Matcher m = CodeVerifierUtil.VALID_CODE_CHALLENGE_PATTERN.matcher(codeChallenge);
            if(!m.matches()) {
                setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_FORMAT, codeChallenge);
                processAudit(exchange);
                return;
            }
            // put the code challenge and method into the codes map.
            codeMap.put(OAuth2Constants.CODE_CHALLENGE, codeChallenge);
            codeMap.put(OAuth2Constants.CODE_CHALLENGE_METHOD, codeChallengeMethod);
        }

        CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);
        redirectUri = redirectUri + "?code=" + code;
        String state = params.get("state");
        if(state != null) {
            redirectUri = redirectUri + "&state=" + state;
        }
        if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
        // now redirect here.
        exchange.setStatusCode(StatusCodes.FOUND);
        exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
        exchange.endExchange();
        processAudit(exchange);
    }
}
 
Example 18
Source File: LoggingServiceActivator.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@SuppressWarnings("Convert2Lambda")
@Override
protected HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            final Map<String, Deque<String>> params = new TreeMap<>(exchange.getQueryParameters());
            final String msg = getValue(params, MSG_KEY, DEFAULT_MESSAGE);
            final boolean includeLevel = getValue(params, INCLUDE_LEVEL_KEY, false);
            final int logCount = getValue(params, LOG_COUNT_KEY, 1);
            final boolean logInfoOnly = getValue(params, LOG_INFO_ONLY_KEY, false);
            final boolean logException = getValue(params, LOG_EXCEPTION_KEY, false);
            final String ndcValue = getValue(params, NDC_KEY, null);
            final Set<Logger.Level> logLevels = getLevels(params);
            final String loggerName = getValue(params, LOG_NAME_KEY, null);
            if (ndcValue != null) {
                NDC.push(ndcValue);
            }
            // Assume other parameters are MDC key/value pairs
            for (String key : params.keySet()) {
                MDC.put(key, params.get(key).getFirst());
            }
            final Logger logger = (loggerName == null ? LOGGER : Logger.getLogger(loggerName));
            for (int i = 0; i < logCount; i++) {
                if (logInfoOnly) {
                    logger.info(getMessage(msg, Logger.Level.INFO, includeLevel));
                } else {
                    for (Logger.Level level : logLevels) {
                        if (logException) {
                            logger.log(level, getMessage(msg, level, includeLevel), createMultiNestedCause());
                        } else {
                            logger.log(level, getMessage(msg, level, includeLevel));
                        }
                    }
                }
            }
            // Clear NDC and MDC
            NDC.clear();
            MDC.clear();
            exchange.getResponseSender().send("Response sent");
        }
    };
}
 
Example 19
Source File: LightGSSAPIAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange,
                                                   final SecurityContext securityContext) {
    ServerConnection connection = exchange.getConnection();
    NegotiationContext negContext = connection.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext != null) {

        if(logger.isDebugEnabled()) logger.debug("Existing negotiation context found for %s", exchange);
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        if (negContext.isEstablished()) {
            IdentityManager identityManager = getIdentityManager(securityContext);
            // get the client authenticate class and user type from the exchange.
            String clientAuthClass = null;
            String userType = null;
            Map<String, Deque<String>> params = exchange.getQueryParameters();
            Deque<String> clientIdDeque = params.get("client_id");
            if(clientIdDeque != null) {
                String clientId = clientIdDeque.getFirst();
                IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                Client client = clients.get(clientId);
                if(client != null) {
                    clientAuthClass = client.getAuthenticateClass();
                }
            }
            Deque<String> userTypeDeque = params.get("user_type");
            if(userTypeDeque != null) {
                userType = userTypeDeque.getFirst();
            }

            final Account account = identityManager.verify(new LightGSSContextCredential(negContext.getGssContext(), clientAuthClass, userType));
            if (account != null) {
                securityContext.authenticationComplete(account, name, false);
                if(logger.isDebugEnabled()) logger.debug("Authenticated as user %s with existing GSSAPI negotiation context for %s", account.getPrincipal().getName(), exchange);
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                if(logger.isDebugEnabled()) logger.debug("Failed to authenticate with existing GSSAPI negotiation context for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.startsWith(NEGOTIATE_PREFIX)) {
                String base64Challenge = current.substring(NEGOTIATE_PREFIX.length());
                try {
                    ByteBuffer challenge = FlexBase64.decode(base64Challenge);
                    return runGSSAPI(exchange, challenge, securityContext);
                } catch (IOException e) {
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header was found so authentication was not even attempted.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 20
Source File: LogoutHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HeaderMap requestHeaders = exchange.getRequestHeaders();
    final HeaderMap responseHeaders = exchange.getResponseHeaders();

    String referrer = responseHeaders.getFirst(REFERER);
    String protocol = exchange.getRequestScheme();
    String host = null;
    if (referrer != null) {
        try {
            URI uri = new URI(referrer);
            protocol = uri.getScheme();
            host = uri.getHost() + portPortion(protocol, uri.getPort());
        } catch (URISyntaxException e) {
        }
    }
    if (host == null) {
        host = requestHeaders.getFirst(HOST);
        if (host == null) {
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            return;
        }
    }

    /*
     * Main sequence of events:
     *
     * 1. Redirect to self using user:pass@host form of authority. This forces Safari to overwrite its cache. (Also
     * forces FF and Chrome, but not absolutely necessary) Set the exit flag as a state signal for step 3
     *
     * 2. Send 401 digest without a nonce stale marker, this will force FF and Chrome and likely other browsers to
     * assume an invalid (old) password. In the case of Opera, which doesn't invalidate under such a circumstance,
     * send an invalid realm. This will overwrite its auth cache, since it indexes it by host and not realm.
     *
     * 3. The credentials in 307 redirect wlll be transparently accepted and a final redirect to the console is
     * performed. Opera ignores these, so the user must hit escape which will use javascript to perform the redirect
     *
     * In the case of Internet Explorer, all of this will be bypassed and will simply redirect to the console. The console
     * MUST use a special javascript call before redirecting to logout.
     */
    String userAgent = requestHeaders.getFirst(USER_AGENT);
    boolean opera = userAgent != null && userAgent.contains("Opera");
    boolean win = !opera && userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident"));

    String rawQuery = exchange.getQueryString();
    boolean exit = rawQuery != null && rawQuery.contains(EXIT);



    if (win) {
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } else {
        // Do the redirects to finish the logout
        String authorization = requestHeaders.getFirst(AUTHORIZATION);

        boolean digest = true;
        Map<String, Deque<String>> parameters = exchange.getQueryParameters();
        if (parameters.containsKey(MECHANISM)) {
            digest = !BASIC.equals(parameters.get(MECHANISM).getFirst());
        }
        if (authorization != null && authorization.length() > BASIC.length()
                && BASIC.equalsIgnoreCase(authorization.substring(0, BASIC.length()))) {
            digest = false;
            ByteBuffer decode = FlexBase64.decode(authorization.substring(6));
            authorization = new String(decode.array(), decode.arrayOffset(), decode.limit(), UTF_8);
        }

        if (authorization == null || !authorization.contains("enter-login-here")) {
            if (!exit) {
                responseHeaders.add(LOCATION, protocol + "://enter-login-here:blah@" + host + "/logout?" + EXIT + "&"
                        + MECHANISM + "=" + (digest ? DIGEST : BASIC));
                exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                return;
            }

            mechanism(opera, digest).sendChallenge(exchange, null);
            String reply = "<html><script type='text/javascript'>window.location=\"" + protocol + "://" + host
                    + "/\";</script></html>";
            exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
            exchange.getResponseSender().send(reply, IoCallback.END_EXCHANGE);
            return;
        }

        // Success, now back to the login screen
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    }
}