Java Code Examples for org.springframework.http.server.ServletServerHttpRequest#getServletRequest()

The following examples show how to use org.springframework.http.server.ServletServerHttpRequest#getServletRequest() . 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: WebsocketConfiguration.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

    // Set ip attribute to WebSocket session
    attributes.put("ip", request.getRemoteAddress());

    // Set servlet request attribute to WebSocket session
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletServerRequest = (ServletServerHttpRequest) request;
        HttpServletRequest servletRequest = servletServerRequest.getServletRequest();
        attributes.put(UNDERLYING_SERVLET_REQUEST, servletRequest);
    }

    return true;
}
 
Example 2
Source File: AbstractMessageConverterMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 3
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 4
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 5
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 6
Source File: WebSocketInterceptor.java    From SpringBootBucket with MIT License 5 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1,
                               WebSocketHandler arg2, Map<String, Object> arg3) throws Exception {
    // 将ServerHttpRequest转换成request请求相关的类,用来获取request域中的用户信息
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpServletRequest httpRequest = servletRequest.getServletRequest();
    }
    logger.info("beforeHandshake完成");
    return true;
}
 
Example 7
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 8
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(inputMessage.getServletRequest(), outputMessage.getServletResponse());
	HttpHeaders responseHeaders = outputMessage.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (inputMessage.getMethod() == HttpMethod.GET || inputMessage.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 9
Source File: ServerWebSocketInterceptor.java    From Jpom with MIT License 4 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
        HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest();
        // 判断用户
        String userId = httpServletRequest.getParameter("userId");
        UserService userService = SpringUtil.getBean(UserService.class);
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        UserModel userModel = userService.checkUser(userId);
        if (userModel == null) {
            return false;
        }
        String nodeId = httpServletRequest.getParameter("nodeId");
        if (!JpomApplication.SYSTEM_ID.equals(nodeId)) {
            NodeService nodeService = SpringUtil.getBean(NodeService.class);
            NodeModel nodeModel = nodeService.getItem(nodeId);
            if (nodeModel == null || roleService.errorDynamicPermission(userModel, ClassFeature.NODE, nodeId)) {
                return false;
            }
            //
            attributes.put("nodeInfo", nodeModel);
        }
        // 判断拦截类型
        String type = httpServletRequest.getParameter("type");
        HandlerType handlerType;
        try {
            handlerType = HandlerType.valueOf(type);
        } catch (Exception e) {
            throw new JpomRuntimeException("type 错误:" + type);
        }
        switch (handlerType) {
            case console:
                //控制台
                String projectId = httpServletRequest.getParameter("projectId");
                // 判断权限
                if (roleService.errorDynamicPermission(userModel, ClassFeature.PROJECT, projectId)) {
                    return false;
                }
                attributes.put("projectId", projectId);
                break;
            case script:
                // 脚本模板
                String scriptId = httpServletRequest.getParameter("scriptId");
                if (roleService.errorDynamicPermission(userModel, ClassFeature.SCRIPT, scriptId)) {
                    return false;
                }
                attributes.put("scriptId", scriptId);
                break;
            case tomcat:
                String tomcatId = httpServletRequest.getParameter("tomcatId");
                if (roleService.errorDynamicPermission(userModel, ClassFeature.TOMCAT, tomcatId)) {
                    return false;
                }
                attributes.put("tomcatId", tomcatId);
                break;
            case ssh:
                String sshId = httpServletRequest.getParameter("sshId");
                if (roleService.errorDynamicPermission(userModel, ClassFeature.SSH, sshId)) {
                    return false;
                }
                SshService bean = SpringUtil.getBean(SshService.class);
                SshModel sshModel = bean.getItem(sshId);
                if (sshModel == null) {
                    return false;
                }
                Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
                attributes.put("parameterMap", parameterMap);
                attributes.put("sshItem", sshModel);
                break;
            default:
                return false;
        }
        //
        String ip = ServletUtil.getClientIP(httpServletRequest);
        attributes.put("ip", ip);
        //
        String userAgent = ServletUtil.getHeaderIgnoreCase(httpServletRequest, HttpHeaders.USER_AGENT);
        attributes.put(HttpHeaders.USER_AGENT, userAgent);
        attributes.put("userInfo", userModel);
        return true;
    }
    return false;
}
 
Example 10
Source File: WebSockeServerHandshakeInterceptor.java    From redtorch with MIT License 4 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

	if (request instanceof ServletServerHttpRequest) {
		ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
		HttpServletRequest servletRequest = serverRequest.getServletRequest();

		try {
			if (servletRequest.getSession().getAttribute(RtConstant.KEY_USER_PO) != null) {
				UserPo userPo = (UserPo) servletRequest.getSession().getAttribute(RtConstant.KEY_USER_PO);
				attributes.put(RtConstant.KEY_NODE_ID, userPo.getRecentlyNodeId());
				attributes.put(RtConstant.KEY_OPERATOR_ID, userPo.getOperatorId());
				attributes.put(WebSocketConstant.KEY_SKIP_LOGIN, true);
			} else {
				String nodeIdStr = servletRequest.getParameter(RtConstant.KEY_NODE_ID);
				String token = servletRequest.getParameter(RtConstant.KEY_TOKEN);
				String operatorId = servletRequest.getParameter(RtConstant.KEY_OPERATOR_ID);

				if (StringUtils.isBlank(nodeIdStr)) {
					logger.error("连接前校验登录字段失败,未获取到参数nodeId,远程地址{}", request.getRemoteAddress().toString());
					return false;
				}
				if (StringUtils.isBlank(token)) {
					logger.error("连接前校验登录字段失败,未获取到参数token,远程地址{}", request.getRemoteAddress().toString());
					return false;
				}
				if (StringUtils.isBlank(operatorId)) {
					logger.error("连接前校验登录字段失败,未获取到参数operatorId,远程地址{}", request.getRemoteAddress().toString());
					return false;
				}
				int nodeId = Integer.valueOf(nodeIdStr).intValue();
				attributes.put(RtConstant.KEY_TOKEN, token);
				attributes.put(RtConstant.KEY_NODE_ID, nodeId);
				attributes.put(RtConstant.KEY_OPERATOR_ID, operatorId);
			}

			String skipTradeEvents = servletRequest.getParameter(WebSocketConstant.KEY_SKIP_TRADE_EVENTS);
			if (!StringUtils.isBlank(skipTradeEvents) && "true".equals(skipTradeEvents)) {
				attributes.put(WebSocketConstant.KEY_SKIP_TRADE_EVENTS, true);
			}

		} catch (Exception e) {
			logger.error("连接前校验登录字段失败,发生异常!{}", request.getRemoteAddress().toString(), e);
			return false;
		}
		return super.beforeHandshake(request, response, wsHandler, attributes);

	} else {
		logger.error("连接前获取ServletServerHttpRequest失败!");
		return false;
	}
}
 
Example 11
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the given return type to the given output message.
 * @param returnValue the value to write to the output message
 * @param returnType the type of the value
 * @param inputMessage the input messages. Used to inspect the {@code Accept} header.
 * @param outputMessage the output message to write to
 * @throws IOException thrown in case of I/O errors
 * @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated by {@code Accept} header on
 * the request cannot be met by the message converters
 */
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,
		ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	Class<?> returnValueClass = getReturnValueType(returnValue, returnType);
	Type returnValueType = getGenericType(returnType);
	HttpServletRequest servletRequest = inputMessage.getServletRequest();
	List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
	List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass, returnValueType);

	if (returnValue != null && producibleMediaTypes.isEmpty()) {
		throw new IllegalArgumentException("No converter found for return value of type: " + returnValueClass);
	}

	Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
	for (MediaType requestedType : requestedMediaTypes) {
		for (MediaType producibleType : producibleMediaTypes) {
			if (requestedType.isCompatibleWith(producibleType)) {
				compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
			}
		}
	}
	if (compatibleMediaTypes.isEmpty()) {
		if (returnValue != null) {
			throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
		}
		return;
	}

	List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
	MediaType.sortBySpecificityAndQuality(mediaTypes);

	MediaType selectedMediaType = null;
	for (MediaType mediaType : mediaTypes) {
		if (mediaType.isConcrete()) {
			selectedMediaType = mediaType;
			break;
		}
		else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
			selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
			break;
		}
	}

	if (selectedMediaType != null) {
		selectedMediaType = selectedMediaType.removeQualityValue();
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				if (((GenericHttpMessageConverter<T>) messageConverter).canWrite(returnValueType,
						returnValueClass, selectedMediaType)) {
					returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
							(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
							inputMessage, outputMessage);
					if (returnValue != null) {
						addContentDispositionHeader(inputMessage, outputMessage);
						((GenericHttpMessageConverter<T>) messageConverter).write(returnValue,
								returnValueType, selectedMediaType, outputMessage);
						if (logger.isDebugEnabled()) {
							logger.debug("Written [" + returnValue + "] as \"" +
									selectedMediaType + "\" using [" + messageConverter + "]");
						}
					}
					return;
				}
			}
			else if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
				returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
						(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
						inputMessage, outputMessage);
				if (returnValue != null) {
					addContentDispositionHeader(inputMessage, outputMessage);
					((HttpMessageConverter<T>) messageConverter).write(returnValue,
							selectedMediaType, outputMessage);
					if (logger.isDebugEnabled()) {
						logger.debug("Written [" + returnValue + "] as \"" +
								selectedMediaType + "\" using [" + messageConverter + "]");
					}
				}
				return;
			}
		}
	}

	if (returnValue != null) {
		throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
	}
}
 
Example 12
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request,
		ServletServerHttpResponse response) {

	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// Ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}