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

The following examples show how to use io.undertow.server.handlers.form.FormData. 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: HttpServletRequestImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public Enumeration<String> getParameterNames() {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final Set<String> parameterNames = new HashSet<>(queryParameters.keySet());
    if (exchange.getRequestMethod().equals(HttpMethodNames.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Iterator<String> it = parsedFormData.iterator();
            while (it.hasNext()) {
                String name = it.next();
                for (FormData.FormValue param : parsedFormData.get(name)) {
                    if (!param.isFileItem()) {
                        parameterNames.add(name);
                        break;
                    }
                }
            }
        }
    }
    return new IteratorEnumeration<>(parameterNames.iterator());
}
 
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: 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 #4
Source File: BodyConverterTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldToGetConvertedFormDataInAMapGroupedByKey() {
    String aKey = "aKey";
    String aValue = "aValue";
    String anotherValue = "anotherValue";

    FormData formData = new FormData(99);
    formData.add(aKey, aValue);
    formData.add(aKey, anotherValue);

    Map<String, Object> bodyMap = BodyConverter.convert(formData);

    Assert.assertEquals(1, bodyMap.size());

    List<Object> aConvertedListvalue = (List<Object>) bodyMap.get(aKey);
    Assert.assertEquals(2, aConvertedListvalue.size());

    Assert.assertTrue(aConvertedListvalue.get(0) instanceof String);
    Assert.assertEquals(aValue, aConvertedListvalue.get(0));

    Assert.assertTrue(aConvertedListvalue.get(1) instanceof String);
    Assert.assertEquals(anotherValue, aConvertedListvalue.get(1));
}
 
Example #5
Source File: BodyConverterTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldToGetConvertedFormDataInAMap() {
    String aKey = "aKey";
    String aValue = "aValue";
    String anotherKey = "anotherKey";
    String anotherValue = "anotherValue";

    FormData formData = new FormData(99);
    formData.add(aKey, aValue);
    formData.add(anotherKey, anotherValue);

    Map<String, Object> bodyMap = BodyConverter.convert(formData);

    Assert.assertEquals(2, bodyMap.size());

    Object aConvertedListvalue = bodyMap.get(aKey);
    Assert.assertTrue(aConvertedListvalue instanceof String);
    Assert.assertEquals(aValue, aConvertedListvalue);

    Object anotherListvalues = bodyMap.get(anotherKey);
    Assert.assertTrue(anotherListvalues instanceof String);
    Assert.assertEquals(anotherValue, anotherListvalues);
}
 
Example #6
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getParameter(final String name) {
    if(queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    Deque<String> params = queryParameters.get(name);
    if (params == null) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            FormData.FormValue res = parsedFormData.getFirst(name);
            if (res == null || res.isFile()) {
                return null;
            } else {
                return res.getValue();
            }
        }
        return null;
    }
    return params.getFirst();
}
 
Example #7
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Enumeration<String> getParameterNames() {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final Set<String> parameterNames = new HashSet<>(queryParameters.keySet());
    if (exchange.getRequestMethod().equals(Methods.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Iterator<String> it = parsedFormData.iterator();
            while (it.hasNext()) {
                String name = it.next();
                for(FormData.FormValue param : parsedFormData.get(name)) {
                    if(!param.isFile()) {
                        parameterNames.add(name);
                        break;
                    }
                }
            }
        }
    }
    return new IteratorEnumeration<>(parameterNames.iterator());
}
 
Example #8
Source File: HttpServletRequestImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public String getParameter(final String name) {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    Deque<String> params = queryParameters.get(name);
    if (params == null) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            FormData.FormValue res = parsedFormData.getFirst(name);
            if (res == null || res.isFileItem()) {
                return null;
            } else {
                return res.getValue();
            }
        }
        return null;
    }
    return params.getFirst();
}
 
Example #9
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 #10
Source File: DomainApiGenericOperationHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private InputStream convertToStream(FormData.FormValue op) throws IOException {
    if (op.isFile()) {
        return Files.newInputStream(op.getPath());
    } else {
        return new ByteArrayInputStream(op.getValue().getBytes(StandardCharsets.UTF_8));
    }
}
 
Example #11
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 #12
Source File: BodyConverterTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldToGetEmptyMapWhenFormDataIsEmpty() {
    FormData formData = new FormData(99);
    Map<String, Object> bodyMap = BodyConverter.convert(formData);

    Assert.assertEquals(0, bodyMap.size());
}
 
Example #13
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 #14
Source File: SessionValidationPostHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws IOException {
    log.info("Handling POST request to validate session");

    String sid;
    String secret;
    String token;

    String contentType = getContentType(exchange).orElseThrow(() -> new IllegalArgumentException("Content type header is not set"));
    if (StringUtils.equals(contentType, "application/json")) { // FIXME use MIME parsing tools
        log.info("Parsing as JSON data");

        JsonObject body = parseJsonObject(exchange);
        sid = GsonUtil.getStringOrThrow(body, "sid");
        secret = GsonUtil.getStringOrThrow(body, "client_secret");
        token = GsonUtil.getStringOrThrow(body, "token");
    } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) { // FIXME use MIME parsing tools
        log.info("Parsing as Form data");

        FormData data = factory.createParser(exchange).parseBlocking();
        sid = getOrThrow(data, "sid");
        secret = getOrThrow(data, "client_secret");
        token = getOrThrow(data, "token");
    } else {
        log.info("Unsupported Content type: {}", contentType);
        throw new IllegalArgumentException("Unsupported Content type: " + contentType);
    }

    handleRequest(sid, secret, token);
    respondJson(exchange, new SuccessStatusJson(true));
}
 
Example #15
Source File: BasicHttpHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String getOrThrow(FormData data, String key) {
    FormData.FormValue value = data.getFirst(key);
    if (Objects.isNull(value)) {
        throw new IllegalArgumentException("Form key " + key + " is missing");
    }

    String object = value.getValue();
    if (Objects.isNull(object)) {
        throw new IllegalArgumentException("Form key " + key + " does not have a value");
    }

    return object;
}
 
Example #16
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
void add(final HttpString name, final FormData.FormValue value) {
    Deque<String> values = this.values.get(name);
    if (values == null) {
        this.values.put(name, values = new ArrayDeque<>(1));
    }
    String stringVal = value.getValue();
    checkStringForSuspiciousCharacters(stringVal);
    values.add(stringVal);
}
 
Example #17
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 #18
Source File: PartImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public PartImpl(final String name, final FormData.FormValue formValue, MultipartConfigElement config,
                ServletContextImpl servletContext, HttpServletRequestImpl servletRequest) {
    this.name = name;
    this.formValue = formValue;
    this.config = config;
    this.servletContext = servletContext;
    this.servletRequest = servletRequest;

}
 
Example #19
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String[] getParameterValues(final String name) {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final List<String> ret = new ArrayList<>();
    Deque<String> params = queryParameters.get(name);
    if (params != null) {
        for (String param : params) {
            ret.add(param);
        }
    }
    if (exchange.getRequestMethod().equals(Methods.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Deque<FormData.FormValue> res = parsedFormData.get(name);
            if (res != null) {
                for (FormData.FormValue value : res) {
                    if(!value.isFile()) {
                        ret.add(value.getValue());
                    }
                }
            }
        }
    }
    if (ret.isEmpty()) {
        return null;
    }
    return ret.toArray(new String[ret.size()]);
}
 
Example #20
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 #21
Source File: ServerRequest.java    From proteus with Apache License 2.0 5 votes vote down vote up
public Deque<FormData.FormValue> files(final String name)
{
    if (this.form != null) {
        return form.get(name);
    }

    return null;
}
 
Example #22
Source File: ServerRequest.java    From proteus with Apache License 2.0 5 votes vote down vote up
private void extractFormParameters(final FormData formData)
{
    if (formData != null) {
        for (String key : formData) {
            final Deque<FormData.FormValue> formValues = formData.get(key);
            final Deque<String> values = formValues.stream()
                    .filter(fv -> !fv.isFileItem())
                    .map(FormData.FormValue::getValue)
                    .collect(java.util.stream.Collectors.toCollection(FastConcurrentDirectDeque::new));

            exchange.getQueryParameters().put(key, values);
        }
    }
}
 
Example #23
Source File: PartImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public PartImpl(final String name, final FormData.FormValue formValue, MultipartConfigElement config,
                ServletContextImpl servletContext, HttpServletRequestImpl servletRequest) {
    this.name = name;
    this.formValue = formValue;
    this.config = config;
    this.servletContext = servletContext;
    this.servletRequest = servletRequest;

}
 
Example #24
Source File: HttpServletRequestImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getParameterValues(final String name) {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final List<String> ret = new ArrayList<>();
    Deque<String> params = queryParameters.get(name);
    if (params != null) {
        for (String param : params) {
            ret.add(param);
        }
    }
    if (exchange.getRequestMethod().equals(HttpMethodNames.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Deque<FormData.FormValue> res = parsedFormData.get(name);
            if (res != null) {
                for (FormData.FormValue value : res) {
                    if (!value.isFileItem()) {
                        ret.add(value.getValue());
                    }
                }
            }
        }
    }
    if (ret.isEmpty()) {
        return null;
    }
    return ret.toArray(new String[ret.size()]);
}
 
Example #25
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
void add(final HttpString name, Deque<FormData.FormValue> values) {
    checkStringForSuspiciousCharacters(name.toString());
    for (final FormData.FormValue value : values) {
        add(name, value);
    }
}
 
Example #26
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 #27
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 #28
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 #29
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 #30
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
}