io.netty.handler.codec.http.cookie.ServerCookieDecoder Java Examples

The following examples show how to use io.netty.handler.codec.http.cookie.ServerCookieDecoder. 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: HarCaptureFilter.java    From Dream-Catcher with MIT License 6 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    Log.e("InnerHandle", "captureRequestCookies " + harEntry.getId());
    String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    for (Cookie cookie : cookies) {
        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());

        harRequest.getRequest().getCookies().add(harCookie);
        harRequest.addHeader(cookie.name(), cookie.value());
    }
}
 
Example #2
Source File: Utils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Collection<Cookie> getCookies(String name,
                                            HttpRequest request) {
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        List<Cookie> foundCookie = new ArrayList<>();
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        for (Cookie cookie : cookies) {
            if (cookie.name().equals(name)) {
                foundCookie.add(cookie);
            }
        }

        return foundCookie;
    }
    return null;
}
 
Example #3
Source File: SessionDao.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
public User getUserFromCookie(FullHttpRequest request) {
    String cookieString = request.headers().get(HttpHeaderNames.COOKIE);

    if (cookieString != null) {
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString);
        if (!cookies.isEmpty()) {
            for (Cookie cookie : cookies) {
                if (isValid(cookie)) {
                    String token = cookie.value();
                    return httpSession.get(token);
                }
            }
        }
    }

    return null;
}
 
Example #4
Source File: HarCaptureFilter.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    for (Cookie cookie : cookies) {
        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());

        harEntry.getRequest().getCookies().add(harCookie);
    }
}
 
Example #5
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
private void doTestStatus(HttpResponseStatus status) {
	EmbeddedChannel channel = new EmbeddedChannel();
	HttpServerOperations ops = new HttpServerOperations(
			Connection.from(channel),
			ConnectionObserver.emptyListener(),
			null,
			new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"),
			null,
			ServerCookieEncoder.STRICT,
			ServerCookieDecoder.STRICT);
	ops.status(status);
	HttpMessage response = ops.newFullBodyMessage(Unpooled.EMPTY_BUFFER);
	assertThat(((FullHttpResponse) response).status().reasonPhrase()).isEqualTo(status.reasonPhrase());
	// "FutureReturnValueIgnored" is suppressed deliberately
	channel.close();
}
 
Example #6
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
HttpServerOperations(Connection c,
		ConnectionObserver listener,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate,
		HttpRequest nettyRequest,
		@Nullable ConnectionInfo connectionInfo,
		ServerCookieEncoder encoder,
		ServerCookieDecoder decoder) {
	super(c, listener);
	this.nettyRequest = nettyRequest;
	this.path = resolvePath(nettyRequest.uri());
	this.nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	this.responseHeaders = nettyResponse.headers();
	this.responseHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
	this.compressionPredicate = compressionPredicate;
	this.cookieHolder = Cookies.newServerRequestHolder(requestHeaders(), decoder);
	this.connectionInfo = connectionInfo;
	this.cookieEncoder = encoder;
	this.cookieDecoder = decoder;
}
 
Example #7
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
H2OrHttp11Codec(
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		ChannelOperations.OnSetup opsFactory,
		@Nullable Function<String, String> uriTagValue) {
	super(ApplicationProtocolNames.HTTP_1_1);
	this.compressPredicate = compressPredicate;
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.decoder = decoder;
	this.forwarded = forwarded;
	this.http2Settings = http2Settings;
	this.listener = listener;
	this.metricsRecorder = metricsRecorder;
	this.minCompressionSize = minCompressionSize;
	this.opsFactory = opsFactory;
	this.uriTagValue = uriTagValue;
}
 
Example #8
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Http11OrH2CleartextCodec(
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean debug,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.forwarded = forwarded;
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (debug) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(
				LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}
	this.http2FrameCodec = http2FrameCodecBuilder.build();
	this.listener = listener;
	this.opsFactory = opsFactory;
}
 
Example #9
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void configureH2Pipeline(ChannelPipeline p,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	p.remove(NettyPipeline.ReactiveBridge);

	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}

	p.addLast(NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addLast(NettyPipeline.H2MultiplexHandler,
	          new Http2MultiplexHandler(new H2Codec(opsFactory, listener, forwarded, cookieEncoder, cookieDecoder)));
}
 
Example #10
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void addStreamHandlers(Channel ch, ChannelOperations.OnSetup opsFactory,
		ConnectionObserver listener, boolean readForwardHeaders,
		ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
	if (ACCESS_LOG) {
		ch.pipeline()
		  .addLast(NettyPipeline.AccessLogHandler, new AccessLogHandlerH2());
	}
	ch.pipeline()
	  .addLast(NettyPipeline.H2ToHttp11Codec, new Http2StreamFrameToHttpObjectCodec(true))
	  .addLast(NettyPipeline.HttpTrafficHandler,
	           new Http2StreamBridgeServerHandler(listener, readForwardHeaders, encoder, decoder));

	ChannelOperations.addReactiveBridge(ch, opsFactory, listener);

	if (log.isDebugEnabled()) {
		log.debug(format(ch, "Initialized HTTP/2 stream pipeline {}"), ch.pipeline());
	}
}
 
Example #11
Source File: HttpResponse.java    From lannister with Apache License 2.0 6 votes vote down vote up
public static HttpResponse createServerDefault(String requestCookie) {
	HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());

	ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");

	if (requestCookie == null) { return ret; }

	Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie);
	if (cookies.isEmpty()) { return ret; }

	// Reset the cookies if necessary.
	for (Cookie cookie : cookies) {
		ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie));
	}

	return ret;
}
 
Example #12
Source File: HttpUtils.java    From riposte with Apache License 2.0 6 votes vote down vote up
public static @NotNull Set<Cookie> extractCookies(@Nullable HttpRequest request) {
    if (request == null) {
        return Collections.emptySet();
    }

    HttpHeaders trailingHeaders = extractTrailingHeadersIfPossible(request);

    String cookieString = request.headers().get(COOKIE);
    if (cookieString == null && trailingHeaders != null) {
        cookieString = trailingHeaders.get(COOKIE);
    }

    if (cookieString != null) {
        return new HashSet<>(ServerCookieDecoder.LAX.decode(cookieString));
    }

    return Collections.emptySet();
}
 
Example #13
Source File: HttpRequestDecoder.java    From timely with Apache License 2.0 6 votes vote down vote up
public static String getSessionId(FullHttpRequest msg) {
    Multimap<String, String> headers = HttpHeaderUtils.toMultimap(msg.headers());
    Collection<String> cookies = headers.get(HttpHeaderNames.COOKIE.toString());
    final StringBuilder buf = new StringBuilder();
    cookies.forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    if (buf.length() == 0) {
        return null;
    } else {
        return buf.toString();
    }
}
 
Example #14
Source File: GrafanaRequestDecoder.java    From timely with Apache License 2.0 6 votes vote down vote up
public static String getSessionId(FullHttpRequest msg) {
    Multimap<String, String> headers = HttpHeaderUtils.toMultimap(msg.headers());
    Collection<String> cookies = headers.get(HttpHeaderNames.COOKIE.toString());
    final StringBuilder buf = new StringBuilder();
    cookies.forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    if (buf.length() == 0) {
        return null;
    } else {
        return buf.toString();
    }
}
 
Example #15
Source File: HttpRequestDecoder.java    From qonduit with Apache License 2.0 6 votes vote down vote up
public static String getSessionId(FullHttpRequest msg, boolean anonymousAccessAllowed) {
    final StringBuilder buf = new StringBuilder();
    msg.headers().getAll(HttpHeaderNames.COOKIE).forEach(h -> {
        ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
            if (c.name().equals(Constants.COOKIE_NAME)) {
                if (buf.length() == 0) {
                    buf.append(c.value());
                }
            }
        });
    });
    String sessionId = buf.toString();
    if (sessionId.length() == 0 && anonymousAccessAllowed) {
        sessionId = NO_AUTHORIZATIONS;
    } else if (sessionId.length() == 0) {
        sessionId = null;
    }
    return sessionId;
}
 
Example #16
Source File: HttpRequestOperationTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTransformStyxRequestToNettyRequestWithAllRelevantInformation() {
    LiveHttpRequest request = new LiveHttpRequest.Builder()
            .method(GET)
            .header("X-Forwarded-Proto", "https")
            .cookies(
                    requestCookie("HASESSION_V3", "asdasdasd"),
                    requestCookie("has", "123456789")
            )
            .uri("https://www.example.com/foo%2Cbar?foo,baf=2")
            .build();

    DefaultHttpRequest nettyRequest = HttpRequestOperation.toNettyRequest(request);
    assertThat(nettyRequest.method(), is(io.netty.handler.codec.http.HttpMethod.GET));
    assertThat(nettyRequest.uri(), is("https://www.example.com/foo%2Cbar?foo%2Cbaf=2"));
    assertThat(nettyRequest.headers().get("X-Forwarded-Proto"), is("https"));

    assertThat(ServerCookieDecoder.LAX.decode(nettyRequest.headers().get("Cookie")),
            containsInAnyOrder(
                    new DefaultCookie("HASESSION_V3", "asdasdasd"),
                    new DefaultCookie("has", "123456789")));

}
 
Example #17
Source File: AuthController.java    From leo-im-server with Apache License 2.0 6 votes vote down vote up
/**
 * 从cookie中得到Session Id
 * @param request
 * @return
 */
private String getJSessionId(FullHttpRequest request) {
    try {
        String cookieStr = request.headers().get("Cookie");
        if(cookieStr == null || cookieStr.trim().isEmpty()) {
            return null;
        }
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieStr);
        Iterator<Cookie> it = cookies.iterator();

        while (it.hasNext()) {
            Cookie cookie = it.next();
            if (cookie.name().equals(CacheKeys.JSESSIONID)) {
                if (CacheManagerFactory.getCacheManager().get(cookie.value()) != null) {
                    return cookie.value();
                }
            }
        }
    } catch (Exception e1) {
        return null;
    }
    return null;
}
 
Example #18
Source File: UserController.java    From leo-im-server with Apache License 2.0 6 votes vote down vote up
/**
 * 从cookie中得到Session Id
 * @return
 */
private String getJSessionId(FullHttpRequest request) {
    try {
        String cookieStr = request.headers().get("Cookie");
        if(cookieStr == null || cookieStr.trim().isEmpty()) {
            return null;
        }
        Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieStr);
        Iterator<Cookie> it = cookies.iterator();

        while (it.hasNext()) {
            Cookie cookie = it.next();
            if (cookie.name().equals(CacheKeys.JSESSIONID)) {
                if (CacheManagerFactory.getCacheManager().get(cookie.value()) != null) {
                    return cookie.value();
                }
            }
        }
    } catch (Exception e1) {
        return null;
    }
    return null;
}
 
Example #19
Source File: OAuthBindClientContextHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private String extractFromCookies(String cookieHeader) {
   // look for auth cookie
   if(cookieHeader == null) {
      return null;
   }

   String sessionId = null;
   logger.trace("Found cookies: value = {}", cookieHeader);
   Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
   for (Cookie cookie : cookies) {
      if (cookieConfig.getAuthCookieName().equals(cookie.name())) {
         logger.trace("Found {} cookie: value = {}", cookieConfig.getAuthCookieName(), cookie.value());
         sessionId = cookie.value();
         if (StringUtils.isNotEmpty(sessionId)) {
            logger.trace("Token {} found in {} cookie.", sessionId, cookieConfig.getAuthCookieName());
         } else {
            sessionId = null;
         }
      }
   }
   return sessionId;
}
 
Example #20
Source File: BindClientContextHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private String extractFromCookies(String cookieHeader) {
   // look for auth cookie
   if(cookieHeader == null) {
      return null;
   }
   
   String sessionId = null;
   logger.trace("Found cookies: value = {}", cookieHeader);
   Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
   for (Cookie cookie : cookies) {
      if (cookieConfig.getAuthCookieName().equals(cookie.name())) {
         logger.trace("Found {} cookie: value = {}", cookieConfig.getAuthCookieName(), cookie.value());
         sessionId = cookie.value();
         if (StringUtils.isNotEmpty(sessionId)) {
            logger.trace("Token {} found in {} cookie.", sessionId, cookieConfig.getAuthCookieName());
         } else {
            sessionId = null;
         }
      }
   }
   return sessionId;
}
 
Example #21
Source File: HarCaptureFilter.java    From CapturePacket with MIT License 6 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    for (Cookie cookie : cookies) {
        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());

        harEntry.getRequest().getCookies().add(harCookie);
    }
}
 
Example #22
Source File: RequestCookie.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes a "Cookie" header value into a set of {@link RequestCookie} objects.
 *
 * @param headerValue "Cookie" header value
 * @return cookies
 */
public static Set<RequestCookie> decode(String headerValue) {
    if (headerValue == null) {
        return emptySet();
    }

    return ServerCookieDecoder.LAX.decode(headerValue).stream()
            .map(RequestCookie::convert)
            .collect(toSet());
}
 
Example #23
Source File: HarCaptureFilter.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    String cookieHeader = httpRequest.headers().get(HttpHeaderNames.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    cookies.forEach(cookie -> {
        HarCookie harCookie = new HarCookie();
        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());
        harEntry.getRequest().getCookies().add(harCookie);
    });
}
 
Example #24
Source File: BaseTransport.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
static MultiMap removeCookieHeaders(MultiMap headers) {
  // We don't want to remove the JSESSION cookie.
  String cookieHeader = headers.get(COOKIE);
  if (cookieHeader != null) {
    headers.remove(COOKIE);
    Set<Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
    for (Cookie cookie: nettyCookies) {
      if (cookie.name().equals("JSESSIONID")) {
        headers.add(COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
        break;
      }
    }
  }
  return headers;
}
 
Example #25
Source File: SessionAwareWebClientTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Cookie getCookieValue(HttpServerRequest req, String name) {
  List<String> cookies = req.headers().getAll("cookie");
  for (String h : cookies) {
    Set<Cookie> all = ServerCookieDecoder.STRICT.decode(h);
    for (Cookie c : all) {
      if (c.name().equals(name)) {
        return c;
      }
    }
  }
  return null;
}
 
Example #26
Source File: HttpSessionManager.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Nullable
String getSessionId(CommonRequest request) throws Exception {
    String cookieHeader = request.getHeader(HttpHeaderNames.COOKIE);
    if (cookieHeader == null) {
        return null;
    }
    Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
    for (Cookie cookie : cookies) {
        if (cookie.name().equals(configRepository.getWebConfig().sessionCookieName())) {
            return cookie.value();
        }
    }
    return null;
}
 
Example #27
Source File: HttpRequest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Cookie> cookies() {
    if (!initCookie) {
        initCookie = true;
        String cookie = header(HttpConst.COOKIE_STRING);
        if (StringKit.isNotEmpty(cookie)) {
            ServerCookieDecoder.LAX.decode(cookie).forEach(this::parseCookie);
        }
    }
    return this.cookies;
}
 
Example #28
Source File: ArmeriaServerHttpRequest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
    final MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
    final List<String> values = req.headers().getAll(HttpHeaderNames.COOKIE);
    values.stream()
          .map(ServerCookieDecoder.LAX::decode)
          .flatMap(Collection::stream)
          .forEach(c -> cookies.add(c.name(), new HttpCookie(c.name(), c.value())));
    return cookies;
}
 
Example #29
Source File: HttpTrafficHandler.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
HttpTrafficHandler(ConnectionObserver listener, boolean readForwardHeaders,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compress,
		ServerCookieEncoder encoder, ServerCookieDecoder decoder) {
	this.listener = listener;
	this.readForwardHeaders = readForwardHeaders;
	this.compress = compress;
	this.cookieEncoder = encoder;
	this.cookieDecoder = decoder;
}
 
Example #30
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
HttpServerChannelInitializer(
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		Http2Settings http2Settings,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		ChannelOperations.OnSetup opsFactory,
		int protocols,
		ProxyProtocolSupportType proxyProtocolSupportType,
		@Nullable SslProvider sslProvider,
		@Nullable Function<String, String> uriTagValue) {
	this.compressPredicate = compressPredicate;
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.decoder = decoder;
	this.forwarded = forwarded;
	this.http2Settings = http2Settings;
	this.metricsRecorder = metricsRecorder;
	this.minCompressionSize = minCompressionSize;
	this.opsFactory = opsFactory;
	this.protocols = protocols;
	this.proxyProtocolSupportType = proxyProtocolSupportType;
	this.sslProvider = sslProvider;
	this.uriTagValue = uriTagValue;
}