Search in sources :

Example 56 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class ServletInitialHandler method dispatchMockRequest.

@Override
public void dispatchMockRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    final DefaultByteBufferPool bufferPool = new DefaultByteBufferPool(false, 1024, 0, 0);
    MockServerConnection connection = new MockServerConnection(bufferPool);
    HttpServerExchange exchange = new HttpServerExchange(connection);
    exchange.setRequestScheme(request.getScheme());
    exchange.setRequestMethod(new HttpString(request.getMethod()));
    exchange.setProtocol(Protocols.HTTP_1_0);
    exchange.setResolvedPath(request.getContextPath());
    String relative;
    if (request.getPathInfo() == null) {
        relative = request.getServletPath();
    } else {
        relative = request.getServletPath() + request.getPathInfo();
    }
    exchange.setRelativePath(relative);
    final ServletPathMatch info = paths.getServletHandlerByPath(request.getServletPath());
    final HttpServletResponseImpl oResponse = new HttpServletResponseImpl(exchange, servletContext);
    final HttpServletRequestImpl oRequest = new HttpServletRequestImpl(exchange, servletContext);
    final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), oRequest, oResponse, info);
    servletRequestContext.setServletRequest(request);
    servletRequestContext.setServletResponse(response);
    //set the max request size if applicable
    if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) {
        exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize());
    }
    exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);
    exchange.startBlocking(new ServletBlockingHttpExchange(exchange));
    servletRequestContext.setServletPathMatch(info);
    try {
        dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new ServletException(e);
    }
}
Also used : DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) HttpString(io.undertow.util.HttpString) HttpServletResponseImpl(io.undertow.servlet.spec.HttpServletResponseImpl) ServletBlockingHttpExchange(io.undertow.servlet.core.ServletBlockingHttpExchange) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) ServletException(javax.servlet.ServletException) HttpServletRequestImpl(io.undertow.servlet.spec.HttpServletRequestImpl) HttpString(io.undertow.util.HttpString)

Example 57 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class PushBuilderImpl method push.

@Override
public void push() {
    if (path == null) {
        throw UndertowServletMessages.MESSAGES.pathWasNotSet();
    }
    ServerConnection con = servletRequest.getExchange().getConnection();
    if (con.isPushSupported()) {
        HeaderMap newHeaders = new HeaderMap();
        for (HeaderValues entry : headers) {
            newHeaders.addAll(entry.getHeaderName(), entry);
        }
        if (conditional) {
            if (etag != null) {
                newHeaders.put(Headers.IF_NONE_MATCH, etag);
            } else if (lastModified != null) {
                newHeaders.put(Headers.IF_MODIFIED_SINCE, lastModified);
            }
        }
        if (sessionId != null) {
            //TODO: do this properly, may be a different tracking method or a different cookie name
            newHeaders.put(Headers.COOKIE, "JSESSIONID=" + sessionId);
        }
        String path = this.path;
        if (queryString != null && !queryString.isEmpty()) {
            path += "?" + queryString;
        }
        con.pushResource(path, new HttpString(method), newHeaders);
    }
    path = null;
    etag = null;
    lastModified = null;
}
Also used : HeaderMap(io.undertow.util.HeaderMap) HeaderValues(io.undertow.util.HeaderValues) ServerConnection(io.undertow.server.ServerConnection) HttpString(io.undertow.util.HttpString) HttpString(io.undertow.util.HttpString)

Example 58 with HttpString

use of io.undertow.util.HttpString in project wildfly by wildfly.

the class ListenerAdd method performRuntime.

@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
    final PathAddress address = context.getCurrentAddress();
    final PathAddress parent = address.getParent();
    final String name = context.getCurrentAddressValue();
    final String bindingRef = ListenerResourceDefinition.SOCKET_BINDING.resolveModelAttribute(context, model).asString();
    final String workerName = ListenerResourceDefinition.WORKER.resolveModelAttribute(context, model).asString();
    final String bufferPoolName = ListenerResourceDefinition.BUFFER_POOL.resolveModelAttribute(context, model).asString();
    final boolean enabled = ListenerResourceDefinition.ENABLED.resolveModelAttribute(context, model).asBoolean();
    final boolean peerHostLookup = ListenerResourceDefinition.RESOLVE_PEER_ADDRESS.resolveModelAttribute(context, model).asBoolean();
    final boolean secure = ListenerResourceDefinition.SECURE.resolveModelAttribute(context, model).asBoolean();
    OptionMap listenerOptions = OptionList.resolveOptions(context, model, ListenerResourceDefinition.LISTENER_OPTIONS);
    OptionMap socketOptions = OptionList.resolveOptions(context, model, ListenerResourceDefinition.SOCKET_OPTIONS);
    String serverName = parent.getLastElement().getValue();
    final ServiceName listenerServiceName = UndertowService.listenerName(name);
    final ListenerService service = createService(name, serverName, context, model, listenerOptions, socketOptions);
    if (peerHostLookup) {
        service.addWrapperHandler(new HandlerWrapper() {

            @Override
            public HttpHandler wrap(HttpHandler handler) {
                return new PeerNameResolvingHandler(handler);
            }
        });
    }
    service.setEnabled(enabled);
    if (secure) {
        service.addWrapperHandler(MarkSecureHandler.WRAPPER);
    }
    List<String> disallowedMethods = ListenerResourceDefinition.DISALLOWED_METHODS.unwrap(context, model);
    if (!disallowedMethods.isEmpty()) {
        final Set<HttpString> methodSet = new HashSet<>();
        for (String i : disallowedMethods) {
            methodSet.add(new HttpString(i.trim()));
        }
        service.addWrapperHandler(new HandlerWrapper() {

            @Override
            public HttpHandler wrap(HttpHandler handler) {
                return new DisallowedMethodsHandler(handler, methodSet);
            }
        });
    }
    final ServiceName socketBindingServiceName = context.getCapabilityServiceName(ListenerResourceDefinition.SOCKET_CAPABILITY, bindingRef, SocketBinding.class);
    final ServiceName workerServiceName = context.getCapabilityServiceName(ListenerResourceDefinition.IO_WORKER_CAPABILITY, workerName, XnioWorker.class);
    final ServiceName bufferPoolServiceName = context.getCapabilityServiceName(ListenerResourceDefinition.IO_BUFFER_POOL_CAPABILITY, bufferPoolName, Pool.class);
    final ServiceBuilder<? extends UndertowListener> serviceBuilder = context.getServiceTarget().addService(listenerServiceName, service);
    serviceBuilder.addDependency(workerServiceName, XnioWorker.class, service.getWorker()).addDependency(socketBindingServiceName, SocketBinding.class, service.getBinding()).addDependency(bufferPoolServiceName, (Injector) service.getBufferPool()).addDependency(UndertowService.SERVER.append(serverName), Server.class, service.getServerService()).addAliases(ListenerResourceDefinition.LISTENER_CAPABILITY.getCapabilityServiceName(name));
    configureAdditionalDependencies(context, serviceBuilder, model, service);
    serviceBuilder.install();
}
Also used : SocketBinding(org.jboss.as.network.SocketBinding) HttpHandler(io.undertow.server.HttpHandler) DisallowedMethodsHandler(io.undertow.server.handlers.DisallowedMethodsHandler) PeerNameResolvingHandler(io.undertow.server.handlers.PeerNameResolvingHandler) HttpString(io.undertow.util.HttpString) HandlerWrapper(io.undertow.server.HandlerWrapper) ServiceName(org.jboss.msc.service.ServiceName) PathAddress(org.jboss.as.controller.PathAddress) OptionMap(org.xnio.OptionMap) HashSet(java.util.HashSet) HttpString(io.undertow.util.HttpString)

Example 59 with HttpString

use of io.undertow.util.HttpString in project indy by Commonjava.

the class BasicAuthenticationOAuthTranslator method authenticate.

@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    if (!enabled) {
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    logger.debug("BASIC authenticate injector checking for " + AUTHORIZATION_HEADER + " header.");
    final HeaderMap headers = exchange.getRequestHeaders();
    final Collection<String> vals = headers.remove(AUTHORIZATION_HEADER);
    String basicAuth = null;
    String bearerAuth = null;
    final List<String> resultValues = new ArrayList<>();
    if (vals != null) {
        for (final String value : vals) {
            logger.debug("Found Authorization header: '{}'", value);
            if (value.toLowerCase().startsWith(BASIC_AUTH_PREFIX)) {
                logger.debug("detected basic auth");
                basicAuth = value;
            } else if (value.toLowerCase().startsWith(BEARER_AUTH_PREFIX)) {
                bearerAuth = value;
                resultValues.add(value);
            } else {
                resultValues.add(value);
            }
        }
    }
    if (bearerAuth == null && basicAuth != null) {
        final UserPass userPass = UserPass.parse(basicAuth);
        logger.debug("Parsed BASIC authorization: {}", userPass);
        if (userPass != null) {
            final AccessTokenResponse token = lookupToken(userPass);
            if (token != null) {
                final String encodedToken = token.getToken();
                logger.debug("Raw token: {}", encodedToken);
                final String value = BEARER_AUTH_PREFIX + " " + encodedToken;
                logger.debug("Adding {} value: {}", AUTHORIZATION_HEADER, value);
                logger.info("BASIC authentication translated into OAuth 2.0 bearer token. Handing off to Keycloak.");
                resultValues.add(value);
                KeycloakBearerTokenDebug.debugToken(encodedToken);
                exchange.getResponseHeaders().add(new HttpString(INDY_BEARER_TOKEN), encodedToken);
            }
        }
    }
    logger.debug("Re-adding {} values: {}", AUTHORIZATION_HEADER, resultValues);
    headers.addAll(new HttpString(AUTHORIZATION_HEADER), resultValues);
    // The best we can do is lookup the token for the given basic auth fields, and inject it for keycloak to use.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : HeaderMap(io.undertow.util.HeaderMap) ArrayList(java.util.ArrayList) UserPass(org.commonjava.indy.subsys.http.util.UserPass) HttpString(io.undertow.util.HttpString) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) HttpString(io.undertow.util.HttpString)

Aggregations

HttpString (io.undertow.util.HttpString)59 IOException (java.io.IOException)18 HttpServerExchange (io.undertow.server.HttpServerExchange)16 HeaderMap (io.undertow.util.HeaderMap)15 HttpHandler (io.undertow.server.HttpHandler)9 ByteBuffer (java.nio.ByteBuffer)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)6 HeaderValues (io.undertow.util.HeaderValues)6 ClientRequest (io.undertow.client.ClientRequest)5 Session (io.undertow.server.session.Session)5 URISyntaxException (java.net.URISyntaxException)5 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)4 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)4 SessionManager (io.undertow.server.session.SessionManager)4 List (java.util.List)4 TypeConverter (org.apache.camel.TypeConverter)4