Search in sources :

Example 1 with Cookie

use of jakarta.servlet.http.Cookie in project atmosphere by Atmosphere.

the class JSR356Endpoint method onOpen.

@Override
public void onOpen(Session session, final EndpointConfig endpointConfig) {
    if (framework.isDestroyed())
        return;
    if (!session.isOpen()) {
        logger.trace("Session Closed {}", session);
        return;
    }
    if (maxBinaryBufferSize != -1)
        session.setMaxBinaryMessageBufferSize(maxBinaryBufferSize);
    if (webSocketWriteTimeout != -1)
        session.setMaxIdleTimeout(webSocketWriteTimeout);
    if (maxTextBufferSize != -1)
        session.setMaxTextMessageBufferSize(maxTextBufferSize);
    webSocket = new JSR356WebSocket(session, framework.getAtmosphereConfig());
    Map<String, String> headers = new HashMap<>();
    // TODO: We don't support multi map header, which cause => https://github.com/Atmosphere/atmosphere/issues/1945
    for (Map.Entry<String, List<String>> e : handshakeHeaders.entrySet()) {
        headers.put(e.getKey(), !e.getValue().isEmpty() ? e.getValue().get(0) : "");
    }
    // Force WebSocket. Hack for https://github.com/Atmosphere/atmosphere/issues/1944
    headers.put("Connection", "Upgrade");
    String servletPath = framework.getAtmosphereConfig().getInitParameter(ApplicationConfig.JSR356_MAPPING_PATH);
    if (servletPath == null) {
        servletPath = IOUtils.guestServletPath(framework.getAtmosphereConfig());
    }
    boolean recomputeForBackwardCompat = false;
    URI uri = session.getRequestURI();
    String rawPath = uri.getPath();
    String contextPath = framework.getAtmosphereConfig().getServletContext().getContextPath();
    int pathInfoStartAt = rawPath.indexOf(servletPath) + servletPath.length();
    String pathInfo = null;
    if (rawPath.length() >= pathInfoStartAt) {
        pathInfo = rawPath.substring(pathInfoStartAt);
    } else {
        recomputeForBackwardCompat = true;
    }
    if (recomputeForBackwardCompat) {
        // DON"T SCREAM this code is for broken/backward compatible
        String[] paths = uri.getPath() != null ? uri.getPath().split("/") : new String[] {};
        int pathInfoStartIndex = 3;
        if ("".equals(contextPath) || "".equals(servletPath)) {
            pathInfoStartIndex = 2;
        }
        // /contextPath / servletPath / pathInfo or / servletPath / pathInfo
        StringBuilder b = new StringBuilder("/");
        for (int i = 0; i < paths.length; i++) {
            if (i >= pathInfoStartIndex) {
                b.append(paths[i]).append("/");
            }
        }
        if (b.length() > 1) {
            b.deleteCharAt(b.length() - 1);
        }
        pathInfo = b.toString();
    }
    if (pathInfo.equals("/")) {
        pathInfo = null;
    }
    try {
        String requestURL = uri.toASCIIString();
        if (requestURL.contains("?")) {
            requestURL = requestURL.substring(0, requestURL.indexOf("?"));
        }
        // https://java.net/jira/browse/WEBSOCKET_SPEC-228
        if ((!requestURL.startsWith("http://")) || (!requestURL.startsWith("https://"))) {
            if (requestURL.startsWith("/")) {
                List<String> l = handshakeHeaders.get("origin");
                if (l == null) {
                    // https://issues.jboss.org/browse/UNDERTOW-252
                    l = handshakeHeaders.get("Origin");
                }
                String origin = null;
                if (l != null && !l.isEmpty()) {
                    origin = l.get(0);
                }
                // become something like 'null/path/to/resource'.
                if (origin == null || origin.equalsIgnoreCase("null")) {
                    // Broken WebSocket Spec
                    logger.trace("Unable to retrieve the `origin` header for websocket {}", session);
                    origin = "http" + (session.isSecure() ? "s" : "") + "://0.0.0.0:80";
                }
                requestURL = origin + requestURL;
            } else if (requestURL.startsWith("ws://")) {
                requestURL = requestURL.replace("ws://", "http://");
            } else if (requestURL.startsWith("wss://")) {
                requestURL = requestURL.replace("wss://", "https://");
            }
        }
        List<String> cookieHeaders = handshakeHeaders.get("cookie");
        if (cookieHeaders == null) {
            cookieHeaders = handshakeHeaders.get("Cookie");
        }
        Set<Cookie> cookies = null;
        if (cookieHeaders != null) {
            cookies = new HashSet<>();
            for (String cookieHeader : cookieHeaders) cookies.addAll(CookieUtil.ServerCookieDecoder.STRICT.decode(cookieHeader));
        }
        request = new AtmosphereRequestImpl.Builder().requestURI(uri.getPath()).requestURL(requestURL).headers(headers).cookies(cookies).session(handshakeSession).servletPath(servletPath).contextPath(framework.getServletContext().getContextPath()).pathInfo(pathInfo).destroyable(false).userPrincipal(session.getUserPrincipal()).remoteInetSocketAddress((Callable<InetSocketAddress>) () -> (InetSocketAddress) endpointConfig.getUserProperties().get(JAVAX_WEBSOCKET_ENDPOINT_REMOTE_ADDRESS)).localInetSocketAddress((Callable<InetSocketAddress>) () -> (InetSocketAddress) endpointConfig.getUserProperties().get(JAVAX_WEBSOCKET_ENDPOINT_LOCAL_ADDRESS)).build().queryString(session.getQueryString());
        if (!webSocketProcessor.handshake(request)) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Handshake not accepted."));
            } catch (IOException e) {
                logger.trace("", e);
            }
            return;
        }
        // TODO: Fix this crazy code.
        framework.addInitParameter(ALLOW_QUERYSTRING_AS_REQUEST, "false");
        webSocketProcessor.open(webSocket, request, AtmosphereResponseImpl.newInstance(framework.getAtmosphereConfig(), request, webSocket));
        framework.addInitParameter(ALLOW_QUERYSTRING_AS_REQUEST, "true");
        if (session.isOpen()) {
            // https://bz.apache.org/bugzilla/show_bug.cgi?format=multiple&id=57788
            session.addMessageHandler(new MessageHandler.Whole<String>() {

                @Override
                public void onMessage(String s) {
                    webSocketProcessor.invokeWebSocketProtocol(webSocket, s);
                }
            });
            session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {

                @Override
                public void onMessage(ByteBuffer bb) {
                    byte[] b = bb.hasArray() ? bb.array() : new byte[((Buffer) bb).limit()];
                    bb.get(b);
                    webSocketProcessor.invokeWebSocketProtocol(webSocket, b, 0, b.length);
                }
            });
        } else {
            logger.trace("Session closed during onOpen {}", session);
            onClose(session, new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "Session closed already"));
        }
    } catch (Throwable e) {
        if (session.isOpen()) {
            logger.error("", e);
        } else {
            logger.trace("Session closed during onOpen", e);
        }
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, e.getMessage()));
        } catch (IOException e1) {
            logger.trace("", e);
        }
    }
}
Also used : MessageHandler(jakarta.websocket.MessageHandler) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) Callable(java.util.concurrent.Callable) CloseReason(jakarta.websocket.CloseReason) List(java.util.List) Cookie(jakarta.servlet.http.Cookie) ByteBuffer(java.nio.ByteBuffer) Buffer(java.nio.Buffer) IOException(java.io.IOException) JSR356WebSocket(org.atmosphere.container.version.JSR356WebSocket) ByteBuffer(java.nio.ByteBuffer) Endpoint(jakarta.websocket.Endpoint) AtmosphereRequestImpl(org.atmosphere.cpr.AtmosphereRequestImpl) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with Cookie

use of jakarta.servlet.http.Cookie in project atmosphere by Atmosphere.

the class AtmosphereRequestImpl method cloneRequest.

/**
 * Copy the HttpServletRequest content inside an AtmosphereRequest. By default the returned AtmosphereRequest
 * is not destroyable.
 *
 * @param request {@link HttpServletRequest}
 * @return an {@link AtmosphereRequest}
 */
public static final AtmosphereRequest cloneRequest(HttpServletRequest request, boolean loadInMemory, boolean copySession, boolean isDestroyable, boolean createSession) {
    Builder b;
    HttpServletRequest r;
    Cookie[] cs = request.getCookies();
    Set<Cookie> hs = Collections.synchronizedSet(new HashSet<>());
    if (cs != null) {
        Collections.addAll(hs, cs);
    }
    boolean isWrapped = false;
    if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {
        b = ((AtmosphereRequestImpl) request).b;
        isWrapped = true;
    } else {
        b = new Builder();
        b.request(request);
    }
    HttpSession session = request.getSession(false);
    if (copySession) {
        session = request.getSession(createSession);
        if (session != null) {
            session = new FakeHttpSession(session);
        } else {
            session = new FakeHttpSession("", null, System.currentTimeMillis(), -1);
        }
    }
    b.servletPath(request.getServletPath()).pathInfo(request.getPathInfo()).contextPath(request.getContextPath()).requestURI(request.getRequestURI()).requestURL(request.getRequestURL().toString()).method(request.getMethod()).serverName(request.getServerName()).serverPort(request.getServerPort()).remoteAddr(request.getRemoteAddr()).remoteHost(request.getRemoteHost()).remotePort(request.getRemotePort()).destroyable(isDestroyable).cookies(hs).session(session).principal(request.getUserPrincipal()).authType(request.getAuthType()).isSSecure(request.isSecure());
    if (loadInMemory) {
        String s = (String) attributeWithoutException(request, FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST);
        boolean throwException = Boolean.parseBoolean(s);
        r = new NoOpsRequest(throwException);
        if (isWrapped) {
            load(b.request, b);
        } else {
            load(request, b);
        }
        b.request(r);
    }
    return isWrapped ? (AtmosphereRequestImpl) request : b.build();
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Cookie(jakarta.servlet.http.Cookie) FakeHttpSession(org.atmosphere.util.FakeHttpSession) HttpSession(jakarta.servlet.http.HttpSession) FakeHttpSession(org.atmosphere.util.FakeHttpSession)

Example 3 with Cookie

use of jakarta.servlet.http.Cookie in project atmosphere by Atmosphere.

the class WebSocketProcessorTest method basicWebSocketCookieTest.

@Test
public void basicWebSocketCookieTest() throws IOException, ServletException, ExecutionException, InterruptedException {
    final AtomicReference<Cookie> cValue = new AtomicReference<Cookie>();
    final AtomicReference<AtmosphereResource> r = new AtomicReference<AtmosphereResource>();
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    WebSocket w = new ArrayBaseWebSocket(b);
    final WebSocketProcessor processor = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(framework);
    framework.addAtmosphereHandler("/*", new AtmosphereHandler() {

        @Override
        public void onRequest(AtmosphereResource resource) throws IOException {
            r.set(resource);
            resource.getBroadcaster().addAtmosphereResource(resource);
        }

        @Override
        public void onStateChange(AtmosphereResourceEvent event) throws IOException {
            Cookie[] c = event.getResource().getRequest().getCookies();
            cValue.set(c[0]);
        }

        @Override
        public void destroy() {
        }
    });
    Set<Cookie> c = new HashSet<Cookie>();
    c.add(new Cookie("yo", "man"));
    AtmosphereRequest request = new AtmosphereRequestImpl.Builder().cookies(c).pathInfo("/a").build();
    processor.open(w, request, AtmosphereResponseImpl.newInstance(framework.getAtmosphereConfig(), request, w));
    r.get().getBroadcaster().broadcast("yo").get();
    assertNotNull(cValue.get());
    Cookie i = c.iterator().next();
    assertEquals(i.getName(), cValue.get().getName());
    assertEquals(i.getValue(), cValue.get().getValue());
}
Also used : Cookie(jakarta.servlet.http.Cookie) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) WebSocket(org.atmosphere.websocket.WebSocket) WebSocketProcessor(org.atmosphere.websocket.WebSocketProcessor) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 4 with Cookie

use of jakarta.servlet.http.Cookie in project atmosphere by Atmosphere.

the class CookieTest method basicHandlerTest.

@Test
public void basicHandlerTest() throws IOException, ServletException, ExecutionException, InterruptedException {
    final AtomicReference<Cookie> cValue = new AtomicReference<Cookie>();
    final AtomicReference<AtmosphereResource> r = new AtomicReference<AtmosphereResource>();
    framework.addAtmosphereHandler("/*", new AtmosphereHandler() {

        @Override
        public void onRequest(AtmosphereResource resource) throws IOException {
            r.set(resource);
            resource.getBroadcaster().addAtmosphereResource(resource);
        }

        @Override
        public void onStateChange(AtmosphereResourceEvent event) throws IOException {
            Cookie[] c = event.getResource().getRequest().getCookies();
            cValue.set(c[0]);
        }

        @Override
        public void destroy() {
        }
    });
    Set<Cookie> c = new HashSet<Cookie>();
    c.add(new Cookie("yo", "man"));
    AtmosphereRequest request = new AtmosphereRequestImpl.Builder().cookies(c).pathInfo("/a").build();
    framework.doCometSupport(request, AtmosphereResponseImpl.newInstance());
    r.get().getBroadcaster().broadcast("yo").get();
    assertNotNull(cValue.get());
    Cookie i = c.iterator().next();
    assertEquals(i.getName(), cValue.get().getName());
    assertEquals(i.getValue(), cValue.get().getValue());
}
Also used : Cookie(jakarta.servlet.http.Cookie) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 5 with Cookie

use of jakarta.servlet.http.Cookie in project spring-security by spring-projects.

the class RememberMeConfigTests method requestWithRememberMeWhenUsingCustomRememberMeParameterThenReauthenticates.

/**
 * SEC-2119
 */
@Test
public void requestWithRememberMeWhenUsingCustomRememberMeParameterThenReauthenticates() throws Exception {
    this.spring.configLocations(xml("WithRememberMeParameter")).autowire();
    // @formatter:off
    MockHttpServletRequestBuilder request = login("user", "password").param("custom-remember-me-parameter", "true").with(csrf());
    MvcResult result = this.mvc.perform(request).andExpect(redirectedUrl("/")).andReturn();
    // @formatter:on
    Cookie cookie = rememberMeCookie(result);
    // @formatter:off
    this.mvc.perform(get("/authenticated").cookie(cookie)).andExpect(status().isOk());
// @formatter:on
}
Also used : Cookie(jakarta.servlet.http.Cookie) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MvcResult(org.springframework.test.web.servlet.MvcResult) Test(org.junit.jupiter.api.Test)

Aggregations

Cookie (jakarta.servlet.http.Cookie)197 Test (org.junit.jupiter.api.Test)137 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)45 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)40 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)30 Locale (java.util.Locale)19 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)19 MvcResult (org.springframework.test.web.servlet.MvcResult)15 Authentication (org.springframework.security.core.Authentication)11 Test (org.junit.Test)10 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)9 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)9 IOException (java.io.IOException)8 LocaleContext (org.springframework.context.i18n.LocaleContext)8 SimpleLocaleContext (org.springframework.context.i18n.SimpleLocaleContext)8 SimpleTimeZoneAwareLocaleContext (org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext)8 TimeZoneAwareLocaleContext (org.springframework.context.i18n.TimeZoneAwareLocaleContext)8 Map (java.util.Map)6 SavedCookie (org.springframework.security.web.savedrequest.SavedCookie)6 ModelAndView (org.springframework.web.servlet.ModelAndView)6