/** * Override default implementation to ensure that TRACE is correctly * handled. * * @param req the {@link HttpServletRequest} object that * contains the request the client made of * the servlet * * @param resp the {@link HttpServletResponse} object that * contains the response the servlet returns * to the client * * @exception IOException if an input or output error occurs * while the servlet is handling the * OPTIONS request * * @exception ServletException if the request for the * OPTIONS cannot be handled */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder allow = new StringBuilder(); // There is a doGet method allow.append("GET, HEAD"); // There is a doPost allow.append(", POST"); // There is a doPut allow.append(", PUT"); // There is a doDelete allow.append(", DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { allow.append(", TRACE"); } // Always allow options allow.append(", OPTIONS"); resp.setHeader("Allow", allow.toString()); }
/** * Override default implementation to ensure that TRACE is correctly * handled. * * @param req * the {@link HttpServletRequest} object that contains the * request the client made of the servlet * * @param resp * the {@link HttpServletResponse} object that contains the * response the servlet returns to the client * * @exception IOException * if an input or output error occurs while the servlet is * handling the OPTIONS request * * @exception ServletException * if the request for the OPTIONS cannot be handled */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder allow = new StringBuilder(); // There is a doGet method allow.append("GET, HEAD"); // There is a doPost allow.append(", POST"); // There is a doPut allow.append(", PUT"); // There is a doDelete allow.append(", DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { allow.append(", TRACE"); } // Always allow options allow.append(", OPTIONS"); resp.setHeader("Allow", allow.toString()); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String method = ((RequestFacade) request).getMethod(); if (REQUIRE_AUTHORIZATION_METHODS.contains(method)){ String token = null; String authorizationHeader = ((RequestFacade) request).getHeader("Authorization"); if (authorizationHeader != null){ token = authorizationHeader.replaceAll("Token\\s+", "").trim(); }else{ token = request.getParameter("token"); } if (token == null || token.equals("") || tokenManager.fromToken(token) == null){ unauthorizedResponse(response); return; } } chain.doFilter(request, response); }
/** * {@inheritDoc} */ @Override public Set<Credential> extract(ServletRequest source) { Set<Credential> credentials = new HashSet<Credential>(); if (source != null) { credentials.addAll(super.extract(source)); Request request = null; if (source instanceof Request) { request = (Request)source; } else if (source instanceof RequestFacade && REQUEST_ACCESS != null) { request = REQUEST_ACCESS.read((RequestFacade)source); } if (request != null && PRINCIPAL_ACCESS != null) { Principal principal = PRINCIPAL_ACCESS.read(request); if (principal instanceof JBossGenericPrincipal) { Subject subject = ((JBossGenericPrincipal)principal).getSubject(); if (subject != null) { credentials.add(new SubjectCredential(subject)); } } } } return credentials; }
/** * Unwrap the request if we have wrapped it. */ private void unwrapRequest(State state) { if (state.wrapRequest == null) return; if (state.outerRequest.isAsyncStarted()) { if (!state.outerRequest.getAsyncContext().hasOriginalRequestAndResponse()) { return; } } ServletRequest previous = null; ServletRequest current = state.outerRequest; while (current != null) { // If we run into the container request we are done if ((current instanceof Request) || (current instanceof RequestFacade)) break; // Remove the current request if it is our wrapper if (current == state.wrapRequest) { ServletRequest next = ((ServletRequestWrapper) current).getRequest(); if (previous == null) state.outerRequest = next; else ((ServletRequestWrapper) previous).setRequest(next); break; } // Advance to the next request in the chain previous = current; current = ((ServletRequestWrapper) current).getRequest(); } }
/** * Unwrap the request if we have wrapped it. */ private void unwrapRequest(State state) { if (state.wrapRequest == null) return; ServletRequest previous = null; ServletRequest current = state.outerRequest; while (current != null) { // If we run into the container request we are done if ((current instanceof Request) || (current instanceof RequestFacade)) break; // Remove the current request if it is our wrapper if (current == state.wrapRequest) { ServletRequest next = ((ServletRequestWrapper) current).getRequest(); if (previous == null) state.outerRequest = next; else ((ServletRequestWrapper) previous).setRequest(next); break; } // Advance to the next request in the chain previous = current; current = ((ServletRequestWrapper) current).getRequest(); } }
/** * Unwrap the request if we have wrapped it. */ private void unwrapRequest() { if (wrapRequest == null) return; ServletRequest previous = null; ServletRequest current = outerRequest; while (current != null) { // If we run into the container request we are done if ((current instanceof Request) || (current instanceof RequestFacade)) break; // Remove the current request if it is our wrapper if (current == wrapRequest) { ServletRequest next = ((ServletRequestWrapper) current).getRequest(); if (previous == null) outerRequest = next; else ((ServletRequestWrapper) previous).setRequest(next); break; } // Advance to the next request in the chain previous = current; current = ((ServletRequestWrapper) current).getRequest(); } }
/** * Determines the methods normally allowed for the resource. * */ private StringBuilder determineMethodsAllowed(DirContext dirContext, HttpServletRequest req) { StringBuilder methodsAllowed = new StringBuilder(); boolean exists = true; Object object = null; try { String path = getRelativePath(req); object = dirContext.lookup(path); } catch (NamingException e) { exists = false; } if (!exists) { methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK"); return methodsAllowed; } methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE"); // Trace - assume disabled unless we can prove otherwise if (req instanceof RequestFacade && ((RequestFacade) req).getAllowTrace()) { methodsAllowed.append(", TRACE"); } methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK"); if (listings) { methodsAllowed.append(", PROPFIND"); } if (!(object instanceof DirContext)) { methodsAllowed.append(", PUT"); } return methodsAllowed; }
public void handleBodyRequest(String executionId, RequestFacade requestFacade, String receiveData, boolean withAuth) { JSONObject requestData = JSON.parseObject(receiveData); String data = requestData.getString("data"); String mode = requestData.getString("_mode"); String auth = requestData.getString("_auth"); commonHandleLogic(executionId, requestFacade, withAuth, data, mode, auth); }
public void commonHandleLogic(String executionId, RequestFacade requestFacade, boolean withAuth, String data, String mode, String auth) { try { logger.debug("[请求预处理][方法执行ID:" + executionId + "][data参数为][" + data + "][mode参数为][" + mode + "][auth参数为][" + auth + "]"); //判断data是否合法 checkNotNull(data, ResponseDict.ILLEGAL_REQUEST); checkArgument(!data.isEmpty(), ResponseDict.ILLEGAL_REQUEST); //判断是否需要对data进行解密 data = !"debug".equals(mode) ? AESLocker.decryptBase64(data) : data; checkNotNull(data, ResponseDict.ILLEGAL_ENTRYPT_MESSAGE); //获取验证登录的必要信息 JSONObject dataMap = JSON.parseObject(data); if (withAuth) { String token = dataMap.getString("token"); String deviceId = dataMap.getString("deviceId"); logger.debug("[请求预处理][正在执行方法访问校验][token][" + token + "][deviceId][" + deviceId + "]"); //token验证 if (!"debug".equals(auth)) { TokenCheckUtil.checkLoginToken(token, mode, deviceId, requestFacade); } } logger.debug("[请求预处理][方法执行ID:" + executionId + "][完成请求预处理]"); requestFacade.setAttribute("dataMap", dataMap); } catch (DecryptException de) { logger.error("[请求预处理][方法执行ID:" + executionId + "][出现异常][解密失败]"); requestFacade.setAttribute("dataMap", null); requestFacade.setAttribute("errorResponse", Response.getInstance(false).setReturnMsg(ResponseDict.ILLEGAL_ENTRYPT_MESSAGE)); de.printStackTrace(); } catch (Exception e) { logger.error("[请求预处理][方法执行ID:" + executionId + "][出现异常][异常信息][" + e.getMessage() + "]"); requestFacade.setAttribute("dataMap", null); requestFacade.setAttribute("errorResponse", Response.getInstance(false).setReturnMsg(e.getMessage())); e.printStackTrace(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Information required to send the server handshake message String key; String subProtocol = null; List<String> extensions = Collections.emptyList(); if (!headerContainsToken(req, "upgrade", "websocket")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "connection", "upgrade")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, "sec-websocket-version", "13")) { resp.setStatus(426); resp.setHeader("Sec-WebSocket-Version", "13"); return; } key = req.getHeader("Sec-WebSocket-Key"); if (key == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String origin = req.getHeader("Origin"); if (!verifyOrigin(origin)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } List<String> subProtocols = getTokensFromHeader(req, "Sec-WebSocket-Protocol"); if (!subProtocols.isEmpty()) { subProtocol = selectSubProtocol(subProtocols); } // TODO Read client handshake - Sec-WebSocket-Extensions // TODO Extensions require the ability to specify something (API TBD) // that can be passed to the Tomcat internals and process extension // data present when the frame is fragmented. // If we got this far, all is good. Accept the connection. resp.setHeader("Upgrade", "websocket"); resp.setHeader("Connection", "upgrade"); resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key)); if (subProtocol != null) { resp.setHeader("Sec-WebSocket-Protocol", subProtocol); } if (!extensions.isEmpty()) { // TODO } WsHttpServletRequestWrapper wrapper = new WsHttpServletRequestWrapper(req); StreamInbound inbound = createWebSocketInbound(subProtocol, wrapper); wrapper.invalidate(); // Small hack until the Servlet API provides a way to do this. ServletRequest inner = req; // Unwrap the request while (inner instanceof ServletRequestWrapper) { inner = ((ServletRequestWrapper) inner).getRequest(); } if (inner instanceof RequestFacade) { ((RequestFacade) inner).doUpgrade(inbound); } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("servlet.reqUpgradeFail")); } }
public void handleUrlParameterRequest(String executionId, RequestFacade requestFacade, boolean withAuth) { String data = requestFacade.getParameter("data"); String mode = requestFacade.getParameter("_mode"); String auth = requestFacade.getParameter("_auth"); commonHandleLogic(executionId, requestFacade, withAuth, data, mode, auth); }
@Override public CmisService getService(CallContext context) { //Called for each service request, context contains username, password etc. //The registry clients are stored in the map "sessions" //If there is an existing session, use it. Otherwise make a new one. CMISRepository repository = null; //String username = "test"; String ip = ((RequestFacade)context.get(context.HTTP_SERVLET_REQUEST)).getRemoteAddr(); String url = ((RequestFacade)context.get(context.HTTP_SERVLET_REQUEST)).getRequestURL().toString(); String tenant = MultitenantUtils.getTenantDomain((RequestFacade)context.get(context.HTTP_SERVLET_REQUEST)); String username = context.getUsername(); if (username != null) { username = MultitenantUtils.getTenantAwareUsername(username); } UserInfo userInfoObj = new UserInfo(ip, username, tenant); if(url.contains(uriPart)) { repository = getRepo(userInfoObj); if (repository == null) throw new CmisRuntimeException("User is not authenticated to the repository to view the content"); } else if(sessions.containsKey(userInfoObj)) { repository = sessions.get(userInfoObj); //TODO check for session timeout } else { try { repository = new CMISRepository(acquireGregRepository(context, tenant, username), pathManager, typeManager); //put to sessions for future reference sessions.put(new UserInfo(ip, username, tenant), repository); } catch (RegistryException e) { e.printStackTrace(); throw new CmisRuntimeException(e.getMessage(), e); } catch (AxisFault axisFault) { axisFault.printStackTrace(); throw new CmisRuntimeException(axisFault.getMessage()); } } CmisServiceWrapper<CMISService> serviceWrapper = new CmisServiceWrapper<CMISService>( createGregService(repository, context), DEFAULT_MAX_ITEMS_TYPES, DEFAULT_DEPTH_TYPES, DEFAULT_MAX_ITEMS_OBJECTS, DEFAULT_DEPTH_OBJECTS); serviceWrapper.getWrappedService().setCallContext(context); return serviceWrapper; }