io.undertow.server.handlers.form.FormDataParser Java Examples

The following examples show how to use io.undertow.server.handlers.form.FormDataParser. 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: SikulixServer.java    From SikuliX1 with MIT License 6 votes vote down vote up
private String[] getScriptArgs(final HttpServerExchange exchange) {
  String[] args = {};
  Optional<String> argsString = Optional.empty();
  String queryString = exchange.getQueryString();
  if (queryString != null) {
    Matcher matcher = PATTERN_QUERY_ARGS.matcher(queryString);
    if (matcher.find()) {
      argsString = Optional.of(matcher.group("args"));
    }
  }
  if (exchange.getRequestMethod().equals(Methods.POST)) {
    FormData form = exchange.getAttachment(FormDataParser.FORM_DATA);
    if (form != null) {
      argsString = Optional.ofNullable(form.getLast("args")).map(fVal -> fVal.getValue());
    }
  }
  if (argsString.isPresent()) {
    StringBuilder buf = new StringBuilder();
    String[] tokens = argsString.get().split(";");
    args = new String[tokens.length];
    for (int i=0; i<tokens.length; i++) {
      args[i] = URLUtils.decode(tokens[i], "UTF-8", true, buf);
    }
  }
  return args;
}
 
Example #2
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
private void parseForm(RequestImpl request, HttpServerExchange exchange) throws IOException {
    FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA);
    if (formData == null) return;

    for (String name : formData) {
        FormData.FormValue value = formData.getFirst(name);
        if (value.isFileItem()) {
            String fileName = value.getFileName();
            if (!Strings.isBlank(fileName)) {    // browser passes blank file name if not choose file in form
                FormData.FileItem item = value.getFileItem();
                logger.debug("[request:file] {}={}, size={}", name, fileName, item.getFileSize());
                request.files.put(name, new MultipartFile(item.getFile(), fileName, value.getHeaders().getFirst(Headers.CONTENT_TYPE)));
            }
        } else {
            logger.debug("[request:form] {}={}", name, new FieldLogParam(name, value.getValue()));
            request.formParams.put(name, value.getValue());
        }
    }
}
 
Example #3
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setCharacterEncoding(final String env) throws UnsupportedEncodingException {
    if (readStarted) {
        return;
    }
    try {
        characterEncoding = Charset.forName(env);

        final ManagedServlet originalServlet = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getOriginalServletPathMatch().getServletChain().getManagedServlet();
        final FormDataParser parser = originalServlet.getFormParserFactory().createParser(exchange);
        if (parser != null) {
            parser.setCharacterEncoding(env);
        }
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException();
    }
}
 
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: FormHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the form parameter from a request
 *
 * @param exchange The Undertow HttpServerExchange
 *
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
protected Form getForm(HttpServerExchange exchange) throws IOException {
    final Form form = Application.getInstance(Form.class);
    if (RequestUtils.isPostPutPatch(exchange)) {
        final Builder builder = FormParserFactory.builder();
        builder.setDefaultCharset(StandardCharsets.UTF_8.name());
        try (final FormDataParser formDataParser = builder.build().createParser(exchange)) {
            if (formDataParser != null) {
                exchange.startBlocking();
                final FormData formData = formDataParser.parseBlocking();
                for (String data : formData) {
                    Deque<FormValue> deque = formData.get(data);
                    if (deque != null) {
                        FormValue formValue = deque.element();
                        if (formValue != null) {
                            if (formValue.isFileItem() && formValue.getFileItem().getFile() != null) {
                                form.addFile(Files.newInputStream(formValue.getFileItem().getFile()));
                            } else {
                                if (data.contains("[]")) {
                                    String key = StringUtils.replace(data, "[]", "");
                                    for (Iterator iterator = deque.iterator(); iterator.hasNext();)  {
                                        form.addValueList(new HttpString(key).toString(), ((FormValue) iterator.next()).getValue());
                                    }
                                } else {
                                    form.addValue(new HttpString(data).toString(), formValue.getValue());
                                }
                            }    
                        }
                    }
                }
            }
        }
        
        form.setSubmitted(true);
    }

    return form;
}
 
Example #6
Source File: HTTPIOHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (HEALTH_CHECK_PATH.equals(exchange.getRequestPath())) {      // not treat health-check as action
        exchange.endExchange(); // end exchange will send 200 / content-length=0
        return;
    }

    boolean shutdown = shutdownHandler.handle(new Exchange(exchange));
    if (shutdown) return;

    if (hasBody(exchange)) {    // parse body early, not process until body is read (e.g. for chunked), to save one blocking thread during read
        FormDataParser parser = formParserFactory.createParser(exchange);
        if (parser != null) {
            parser.parse(handler);
            return;
        }

        var reader = new RequestBodyReader(exchange, handler);
        StreamSourceChannel channel = exchange.getRequestChannel();
        reader.read(channel);  // channel will be null if getRequestChannel() is already called, but here should not be that case
        if (!reader.complete()) {
            channel.getReadSetter().set(reader);
            channel.resumeReads();
            return;
        }
    }

    exchange.dispatch(handler);
}
 
Example #7
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 #8
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 #9
Source File: RequestDumpingHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void dumpRequestBody(HttpServerExchange exchange, StringBuilder sb) {
    try {
        FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA);
        if (formData != null) {
            sb.append("body=\n");

            for (String formField : formData) {
                Deque<FormData.FormValue> formValues = formData.get(formField);

                sb.append(formField)
                        .append("=");
                for (FormData.FormValue formValue : formValues) {
                    sb.append(formValue.isFile() ? "[file-content]" : formValue.getValue());
                    sb.append("\n");

                    if (formValue.getHeaders() != null) {
                        sb.append("headers=\n");
                        for (HeaderValues header : formValue.getHeaders()) {
                            sb.append("\t")
                                    .append(header.getHeaderName()).append("=").append(header.getFirst()).append("\n");

                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: Extractors.java    From proteus with Apache License 2.0 5 votes vote down vote up
public static File file(final HttpServerExchange exchange, final String name) throws IllegalArgumentException
{
    try {
        return exchange.getAttachment(FormDataParser.FORM_DATA).get(name).getFirst().getFileItem().getFile().toFile();
    } catch (NullPointerException e) {
        throw new IllegalArgumentException("Missing parameter " + name, e);
    }
}
 
Example #11
Source File: Extractors.java    From proteus with Apache License 2.0 5 votes vote down vote up
public static Path filePath(final HttpServerExchange exchange, final String name) throws IllegalArgumentException
{
    try {
        return exchange.getAttachment(FormDataParser.FORM_DATA).get(name).getFirst().getFileItem().getFile();
    } catch (NullPointerException e) {
        throw new IllegalArgumentException("Missing parameter " + name, e);
    }
}
 
Example #12
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 #13
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 #14
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 #15
Source File: Oauth2CodePostHandler.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 {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");

    // get the form from the exchange
    final FormData data = exchange.getAttachment(FormDataParser.FORM_DATA);

    final FormData.FormValue jClientId = data.getFirst("client_id");
    final FormData.FormValue jRedirectUri = data.getFirst("redirect_uri");
    final FormData.FormValue jState = data.getFirst("state");
    final FormData.FormValue jRemember = data.getFirst("remember");
    final String clientId = jClientId.getValue();
    final String remember = jRemember == null ? null : jRemember.getValue();  // should be 'Y' or 'N' if not null.
    String redirectUri = jRedirectUri == null ? null : jRedirectUri.getValue();
    final String state = jState == null ? null : jState.getValue();
    if(logger.isDebugEnabled()) {
        logger.debug("client_id = " + clientId + " state = " + state + " redirectUri = " + redirectUri + " remember = " + remember);
    }
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        if(logger.isDebugEnabled()) logger.debug("client is not found for clientId = " + clientId);
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        if(logger.isDebugEnabled()) logger.debug("userId = " + userId);
        if("error".equals(userId)) {
            exchange.setStatusCode(StatusCodes.BAD_REQUEST);
            exchange.getResponseSender().send(context.getAuthenticatedAccount().getRoles().iterator().next());
            processAudit(exchange);
        } else {
            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));
            }
            // generate auth code
            String code = Util.getUUID();
            if(redirectUri == null) {
                redirectUri = client.getRedirectUri();
            } else {
                codeMap.put("redirectUri", redirectUri);
            }
            if(remember != null) codeMap.put("remember", remember); // pass the remember checkbox value to the token service
            CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);

            redirectUri = redirectUri + "?code=" + code;
            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 #16
Source File: Extractors.java    From proteus with Apache License 2.0 4 votes vote down vote up
public static java.util.Optional<File> file(final HttpServerExchange exchange, final String name)
{
    return java.util.Optional.ofNullable(exchange.getAttachment(FormDataParser.FORM_DATA).get(name)).map(Deque::getFirst).map(fv -> fv.getFileItem().getFile().toFile());
}
 
Example #17
Source File: Extractors.java    From proteus with Apache License 2.0 4 votes vote down vote up
public static java.util.Optional<Path> filePath(final HttpServerExchange exchange, final String name)
{
    return java.util.Optional.ofNullable(exchange.getAttachment(FormDataParser.FORM_DATA).get(name)).map(Deque::getFirst).map(fv -> fv.getFileItem().getFile());
}
 
Example #18
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
}
 
Example #19
Source File: ClaimInformationPointProviderTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void onBeforeClass() {
    httpService = Undertow.builder().addHttpListener(8989, "localhost").setHandler(exchange -> {
        if (exchange.isInIoThread()) {
            try {
                if (exchange.getRelativePath().equals("/post-claim-information-provider")) {
                    FormParserFactory parserFactory = FormParserFactory.builder().build();
                    FormDataParser parser = parserFactory.createParser(exchange);
                    FormData formData = parser.parseBlocking();

                    if (!"Bearer tokenString".equals(exchange.getRequestHeaders().getFirst("Authorization"))
                            || !"post".equalsIgnoreCase(exchange.getRequestMethod().toString())
                            || !"application/x-www-form-urlencoded".equals(exchange.getRequestHeaders().getFirst("Content-Type"))
                            || !exchange.getRequestHeaders().get("header-b").contains("header-b-value1")
                            || !exchange.getRequestHeaders().get("header-b").contains("header-b-value2")
                            || !formData.get("param-a").getFirst().getValue().equals("param-a-value1")
                            || !formData.get("param-a").getLast().getValue().equals("param-a-value2")
                            || !formData.get("param-subject").getFirst().getValue().equals("sub")
                            || !formData.get("param-user-name").getFirst().getValue().equals("username")
                            || !formData.get("param-other-claims").getFirst().getValue().equals("param-other-claims-value1")
                            || !formData.get("param-other-claims").getLast().getValue().equals("param-other-claims-value2")) {
                        exchange.setStatusCode(400);
                        return;
                    }

                    exchange.setStatusCode(200);
                } else if (exchange.getRelativePath().equals("/get-claim-information-provider")) {
                    if (!"Bearer idTokenString".equals(exchange.getRequestHeaders().getFirst("Authorization"))
                            || !"get".equalsIgnoreCase(exchange.getRequestMethod().toString())
                            || !exchange.getRequestHeaders().get("header-b").contains("header-b-value1")
                            || !exchange.getRequestHeaders().get("header-b").contains("header-b-value2")
                            || !exchange.getQueryParameters().get("param-a").contains("param-a-value1")
                            || !exchange.getQueryParameters().get("param-a").contains("param-a-value2")
                            || !exchange.getQueryParameters().get("param-subject").contains("sub")
                            || !exchange.getQueryParameters().get("param-user-name").contains("username")) {
                        exchange.setStatusCode(400);
                        return;
                    }

                    exchange.setStatusCode(200);
                } else {
                    exchange.setStatusCode(404);
                }
            } finally {
                if (exchange.getStatusCode() == 200) {
                    try {
                        ObjectMapper mapper = JsonSerialization.mapper;
                        JsonParser jsonParser = mapper.getFactory().createParser("{\"a\": \"a-value1\", \"b\": \"b-value1\", \"d\": [\"d-value1\", \"d-value2\"]}");
                        TreeNode treeNode = mapper.readTree(jsonParser);
                        exchange.getResponseSender().send(treeNode.toString());
                    } catch (Exception ignore) {
                        ignore.printStackTrace();
                    }
                }
                exchange.endExchange();
            }
        }
    }).build();

    httpService.start();
}
 
Example #20
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 #21
Source File: ServerRequest.java    From proteus with Apache License 2.0 3 votes vote down vote up
private void parseEncodedForm() throws IOException
{
    this.exchange.startBlocking();

    final FormData formData = new FormEncodedDataDefinition().setDefaultEncoding(this.exchange.getRequestCharset()).create(exchange).parseBlocking();

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

    extractFormParameters(formData);
}