Java Code Examples for io.undertow.server.handlers.form.FormDataParser#parseBlocking()

The following examples show how to use io.undertow.server.handlers.form.FormDataParser#parseBlocking() . 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: ServerRequest.java    From proteus with Apache License 2.0 5 votes vote down vote up
private void parseMultipartForm() throws IOException
{
    this.exchange.startBlocking();

    final FormDataParser formDataParser = new MultiPartParserDefinition().setTempFileLocation(new File(TMP_DIR).toPath()).setDefaultEncoding(CHARSET).create(this.exchange);

    if (formDataParser != null) {
        final FormData formData = formDataParser.parseBlocking();

        this.exchange.putAttachment(FormDataParser.FORM_DATA, formData);

        extractFormParameters(formData);
    }
}
 
Example 2
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Transform the form data into an intermediate request data which can me used
 * by the web manager
 *
 * @param exchange    the http server exchange
 * @return
 * @throws IOException
 */
RequestData parseFormData(final HttpServerExchange exchange) throws IOException {
    // Read post parameters
    final FormDataParser parser = parserFactory.createParser(exchange);
    final FormData formData = parser.parseBlocking();
    final RequestData data = new RequestData();
    for (String name : formData) {
        final HttpString key = new HttpString(name);
        data.add(key, formData.get(name));
    }
    return data;
}
 
Example 3
Source File: BodyHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to parse the body into FormData and attach it into exchange
 *
 * @param exchange exchange to be attached
 * @throws IOException
 */
private void attachFormDataBody(final HttpServerExchange exchange) throws IOException {
    Object data;
    FormParserFactory formParserFactory = FormParserFactory.builder().build();
    FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser != null) {
        FormData formData = parser.parseBlocking();
        data = BodyConverter.convert(formData);
        exchange.putAttachment(REQUEST_BODY, data);
    }
}
 
Example 4
Source File: UndertowHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getFirstParam(String param) {
    Deque<String> values = exchange.getQueryParameters().get(param);

    if (values != null && !values.isEmpty()) {
        return values.getFirst();
    }

    if (formData == null && "post".equalsIgnoreCase(getMethod())) {
        FormDataParser parser = formParserFactory.createParser(exchange);
        try {
            formData = parser.parseBlocking();
        } catch (IOException cause) {
            throw new RuntimeException("Failed to parse form parameters", cause);
        }
    }

    if (formData != null) {
        Deque<FormValue> formValues = formData.get(param);

        if (formValues != null && !formValues.isEmpty()) {
            FormValue firstValue = formValues.getFirst();

            if (!firstValue.isFile()) {
                return firstValue.getValue();
            }
        }
    }

    return null;
}
 
Example 5
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        if (data == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: LightFormAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
        final FormDataParser parser = formParserFactory.createParser(exchange);
        if (parser == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        try {
            final FormData data = parser.parseBlocking();
            final FormData.FormValue jUsername = data.getFirst("j_username");
            final FormData.FormValue jPassword = data.getFirst("j_password");
            final FormData.FormValue jClientId = data.getFirst("client_id");
            final FormData.FormValue jUserType = data.getFirst("user_type");
            if (jUsername == null || jPassword == null) {
                UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
            final String userName = jUsername.getValue();
            final String password = jPassword.getValue();
            final String userType = jUserType.getValue();
            final String clientId = jClientId.getValue();

            // get clientAuthClass and userType
            String clientAuthClass = null;
            IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
            Client client = clients.get(clientId);
            if(client != null) {
                clientAuthClass = client.getAuthenticateClass();
            }

            AuthenticationMechanismOutcome outcome = null;
            LightPasswordCredential credential = new LightPasswordCredential(password.toCharArray(), clientAuthClass, userType, exchange);
            try {
                IdentityManager identityManager = getIdentityManager(securityContext);
                Account account = identityManager.verify(userName, credential);
                if (account != null) {
                    securityContext.authenticationComplete(account, name, true);
                    UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                    outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
                } else {
                    securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
                }
            } finally {
//                if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
//                    handleRedirectBack(exchange);
//                    exchange.endExchange();
//                }
                return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 8
Source File: DomainApiUploadHandler.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 FormDataParser parser = formParserFactory.createParser(exchange);
    FormData data = parser.parseBlocking();
    for (String fieldName : data) {
        //Get all the files
        FormValue value = data.getFirst(fieldName);
        if (value.isFile()) {
            ModelNode response = null;
            InputStream in = new BufferedInputStream(new FileInputStream(value.getPath().toFile()));
            try {
                final ModelNode dmr = new ModelNode();
                dmr.get("operation").set("upload-deployment-stream");
                dmr.get("address").setEmptyList();
                dmr.get("input-stream-index").set(0);
                ModelNode headers = dmr.get(OPERATION_HEADERS);
                headers.get(ACCESS_MECHANISM).set(AccessMechanism.HTTP.toString());
                headers.get(CALLER_TYPE).set(USER);

                OperationBuilder operation = new OperationBuilder(dmr);
                operation.addInputStream(in);
                response = modelController.execute(dmr, OperationMessageHandler.logging, ModelController.OperationTransactionControl.COMMIT, operation.build());
                if (!response.get(OUTCOME).asString().equals(SUCCESS)){
                    Common.sendError(exchange, false, response);
                    return;
                }
            } catch (Throwable t) {
                // TODO Consider draining input stream
                ROOT_LOGGER.uploadError(t);
                Common.sendError(exchange, false, t.getLocalizedMessage());
                return;
            } finally {
                IoUtils.safeClose(in);
            }

            // TODO Determine what format the response should be in for a deployment upload request.
            writeResponse(exchange, response, Common.TEXT_HTML);
            return; //Ignore later files
        }
    }
    Common.sendError(exchange, false, "No file found"); //TODO i18n
}