Java Code Examples for org.apache.catalina.connector.Request#getCoyoteRequest()

The following examples show how to use org.apache.catalina.connector.Request#getCoyoteRequest() . 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: UrlMapperValve.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public void requestRewriteForService(Request request, String filterUri) throws Exception {
    //rewriting the request with actual service url in order to retrieve the resource
    MappingData mappingData = request.getMappingData();
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();

    MessageBytes requestPath = MessageBytes.newInstance();
    requestPath.setString(filterUri);
    mappingData.requestPath = requestPath;
    MessageBytes pathInfo = MessageBytes.newInstance();
    pathInfo.setString(filterUri);
    mappingData.pathInfo = pathInfo;

    coyoteRequest.requestURI().setString(filterUri);
    coyoteRequest.decodedURI().setString(filterUri);
    if (request.getQueryString() != null) {
        coyoteRequest.unparsedURI().setString(filterUri + "?" + request.getQueryString());
    } else {
        coyoteRequest.unparsedURI().setString(filterUri);
    }
    request.getConnector().
            getMapper().map(request.getCoyoteRequest().serverName(),
            request.getCoyoteRequest().decodedURI(), null,
            mappingData);
    //connectorReq.setHost((Host)DataHolder.getInstance().getCarbonTomcatService().getTomcat().getEngine().findChild("testapp.wso2.com"));
    request.setCoyoteRequest(coyoteRequest);
}
 
Example 2
Source File: BasicAuthAuthenticator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandle(Request request) {
    /*
    This is done to avoid every endpoint being able to use basic auth. Add the following to
    the required web.xml of the web app.
    <context-param>
        <param-name>basicAuth</param-name>
        <param-value>true</param-value>
 </context-param>
     */
    if (!isAuthenticationSupported(request)) {
        return false;
    }
    if (request.getCoyoteRequest() == null || request.getCoyoteRequest().getMimeHeaders() == null) {
        return false;
    }
    MessageBytes authorization =
            request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authBC = authorization.getByteChunk();
        if (authBC.startsWithIgnoreCase(AUTH_HEADER, 0)) {
            return true;
        }
    }
    return false;
}
 
Example 3
Source File: BSTAuthenticator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private String getBSTHeader(Request request) throws IOException, XMLStreamException {
    org.apache.coyote.Request coyoteReq = request.getCoyoteRequest();
    InputBuffer buf = coyoteReq.getInputBuffer();
    ByteChunk bc = new ByteChunk();

    buf.doRead(bc, coyoteReq);
    try (InputStream is = new ByteArrayInputStream(getUTF8Bytes(bc.toString()))) {
        XMLStreamReader reader = StAXUtils.createXMLStreamReader(is);
        StAXBuilder builder = new StAXSOAPModelBuilder(reader);
        SOAPEnvelope envelope = (SOAPEnvelope) builder.getDocumentElement();
        envelope.build();

        SOAPHeader header = envelope.getHeader();
        Iterator headerEls = header.getChildrenWithLocalName("Security");
        if (!headerEls.hasNext()) {
            return null;
        }
        OMElement securityHeader = (OMElement) headerEls.next();
        Iterator securityHeaderEls = securityHeader.getChildrenWithLocalName("BinarySecurityToken");
        if (!securityHeaderEls.hasNext()) {
            return null;
        }
        OMElement bstHeader = (OMElement) securityHeaderEls.next();
        bstHeader.build();
        return bstHeader.getText();
    }
}
 
Example 4
Source File: WebappAuthenticationValve.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private boolean isNonSecuredEndPoint(Request request) {
    if (request.getCoyoteRequest() != null && request.getCoyoteRequest().getMimeHeaders() !=
            null && request.getCoyoteRequest().getMimeHeaders().getValue(Constants
            .HTTPHeaders.HEADER_HTTP_AUTHORIZATION) != null) {
        //This is to handle the DEP behaviours of the same endpoint being non-secured in the
        // first call and then being secured in the second call which comes with the basic
        // auth header.
        return false;
    }
    String uri = request.getRequestURI();
    if (uri == null) {
        uri = "";
    }
    if (!uri.endsWith("/")) {
        uri = uri + "/";
    }
    String contextPath = request.getContextPath();
    //Check the contextPath in nonSecuredEndpoints. If so it means cache is not populated for this web-app.
    if (!nonSecuredEndpoints.containsKey(contextPath)) {
        String param = request.getContext().findParameter("nonSecuredEndPoints");
        String skippedEndPoint;
        if (param != null && !param.isEmpty()) {
            //Add the nonSecured end-points to cache
            StringTokenizer tokenizer = new StringTokenizer(param, ",");
            nonSecuredEndpoints.put(contextPath, "true");
            while (tokenizer.hasMoreTokens()) {
                skippedEndPoint = tokenizer.nextToken();
                skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim();
                if (!skippedEndPoint.endsWith("/")) {
                    skippedEndPoint = skippedEndPoint + "/";
                }
                nonSecuredEndpoints.put(skippedEndPoint, "true");
            }
        }
    }
    return nonSecuredEndpoints.containsKey(uri);
}
 
Example 5
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "This method tests the authenticate method of BST Authenticator when all the relevant "
        + "details", dependsOnMethods = "testInitWithRemote")
public void testAuthenticate() throws NoSuchFieldException, IllegalAccessException, IOException {
    Request request = createSoapRequest("CorrectBST.xml");
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
    Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
    uriMB.setAccessible(true);
    MessageBytes bytes = MessageBytes.newInstance();
    bytes.setString("test");
    uriMB.set(coyoteRequest, bytes);
    request.setCoyoteRequest(coyoteRequest);
    bstAuthenticator.canHandle(request);
    AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
            "Authentication status of authentication info is wrong");
    Assert.assertEquals(authenticationInfo.getUsername(), "admin",
            "User name in the authentication info is different than original user");
    OAuth2TokenValidationResponseDTO unAuthorizedValidationRespose = new OAuth2TokenValidationResponseDTO();
    unAuthorizedValidationRespose.setValid(false);
    unAuthorizedValidationRespose.setErrorMsg("User is not authorized");
    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(unAuthorizedValidationRespose);
    AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
    authenticationInfo = bstAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
            "Un-authorized user got authenticated with BST");
}
 
Example 6
Source File: TomcatInvokeInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void collectHttpParam(Request request, AbstractSpan span) {
    final Map<String, String[]> parameterMap = new HashMap<>();
    final org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
    final Parameters parameters = coyoteRequest.getParameters();
    for (final Enumeration<String> names = parameters.getParameterNames(); names.hasMoreElements(); ) {
        final String name = names.nextElement();
        parameterMap.put(name, parameters.getParameterValues(name));
    }

    if (!parameterMap.isEmpty()) {
        String tagValue = CollectionUtil.toString(parameterMap);
        tagValue = Config.Plugin.Http.HTTP_PARAMS_LENGTH_THRESHOLD > 0 ? StringUtil.cut(tagValue, Config.Plugin.Http.HTTP_PARAMS_LENGTH_THRESHOLD) : tagValue;
        Tags.HTTP.PARAMS.set(span, tagValue);
    }
}
 
Example 7
Source File: ApplicationPushBuilder.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public ApplicationPushBuilder(Request catalinaRequest, HttpServletRequest request) {

        baseRequest = request;
        this.catalinaRequest = catalinaRequest;
        coyoteRequest = catalinaRequest.getCoyoteRequest();

        // Populate the initial list of HTTP headers
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> values = new ArrayList<>();
            headers.put(headerName, values);
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                values.add(headerValues.nextElement());
            }
        }

        // Remove the headers
        headers.remove("if-match");
        headers.remove("if-none-match");
        headers.remove("if-modified-since");
        headers.remove("if-unmodified-since");
        headers.remove("if-range");
        headers.remove("range");
        headers.remove("expect");
        headers.remove("authorization");
        headers.remove("referer");
        // Also remove the cookie header since it will be regenerated
        headers.remove("cookie");

        // set the referer header
        StringBuffer referer = request.getRequestURL();
        if (request.getQueryString() != null) {
            referer.append('?');
            referer.append(request.getQueryString());
        }
        addHeader("referer", referer.toString());

        // Session
        Context context = catalinaRequest.getContext();
        sessionCookieName = SessionConfig.getSessionCookieName(context);
        sessionPathParameterName = SessionConfig.getSessionUriParamName(context);

        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionId = session.getId();
        }
        if (sessionId == null) {
            sessionId = request.getRequestedSessionId();
        }
        if (!request.isRequestedSessionIdFromCookie() && !request.isRequestedSessionIdFromURL() &&
                sessionId != null) {
            Set<SessionTrackingMode> sessionTrackingModes =
                    request.getServletContext().getEffectiveSessionTrackingModes();
            addSessionCookie = sessionTrackingModes.contains(SessionTrackingMode.COOKIE);
            addSessionPathParameter = sessionTrackingModes.contains(SessionTrackingMode.URL);
        } else {
            addSessionCookie = request.isRequestedSessionIdFromCookie();
            addSessionPathParameter = request.isRequestedSessionIdFromURL();
        }

        // Cookies
        if (request.getCookies() != null) {
            for (Cookie requestCookie : request.getCookies()) {
                cookies.add(requestCookie);
            }
        }
        for (Cookie responseCookie : catalinaRequest.getResponse().getCookies()) {
            if (responseCookie.getMaxAge() < 0) {
                // Path information not available so can only remove based on
                // name.
                Iterator<Cookie> cookieIterator = cookies.iterator();
                while (cookieIterator.hasNext()) {
                    Cookie cookie = cookieIterator.next();
                    if (cookie.getName().equals(responseCookie.getName())) {
                        cookieIterator.remove();
                    }
                }
            } else {
                cookies.add(new Cookie(responseCookie.getName(), responseCookie.getValue()));
            }
        }
        List<String> cookieValues = new ArrayList<>(1);
        cookieValues.add(generateCookieHeader(cookies,
                catalinaRequest.getContext().getCookieProcessor()));
        headers.put("cookie", cookieValues);

        // Authentication
        if (catalinaRequest.getPrincipal() != null) {
            if ((session == null) || catalinaRequest.getSessionInternal(false).getPrincipal() == null
                    || !(context.getAuthenticator() instanceof AuthenticatorBase)
                    || !((AuthenticatorBase) context.getAuthenticator()).getCache()) {
                // Set a username only if there is no session cache for the principal
                userName = catalinaRequest.getPrincipal().getName();
            }
            setHeader("authorization", "x-push");
        }
    }
 
Example 8
Source File: OauthAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Test(description = "This method tests the authenticate under different parameters",
        dependsOnMethods = {"testInit"})
public void testAuthenticate() throws Exception {
    Request request = createOauthRequest(BEARER_HEADER);
    Assert.assertEquals(oAuthAuthenticator.authenticate(request, null).getStatus(),
            WebappAuthenticator.Status.CONTINUE, "Authentication status mismatched");
    request = createOauthRequest(BEARER_HEADER + "abc");
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
    Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
    uriMB.setAccessible(true);
    MessageBytes bytes = MessageBytes.newInstance();
    bytes.setString("test");
    uriMB.set(coyoteRequest, bytes);
    request.setCoyoteRequest(coyoteRequest);
    Field tokenValidator = OAuthAuthenticator.class.getDeclaredField("tokenValidator");
    tokenValidator.setAccessible(true);

    GenericObjectPool genericObjectPool = Mockito.mock(GenericObjectPool.class, Mockito.CALLS_REAL_METHODS);
    RemoteOAuthValidator remoteOAuthValidator = Mockito
            .mock(RemoteOAuthValidator.class, Mockito.CALLS_REAL_METHODS);
    tokenValidator.set(oAuthAuthenticator, remoteOAuthValidator);
    Field stubs = RemoteOAuthValidator.class.getDeclaredField("stubs");
    stubs.setAccessible(true);
    stubs.set(remoteOAuthValidator, genericObjectPool);
    OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO();
    oAuth2TokenValidationResponseDTO.setValid(true);
    oAuth2TokenValidationResponseDTO.setAuthorizedUser("[email protected]");
    OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO = Mockito
            .mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS);
    Mockito.doReturn(oAuth2TokenValidationResponseDTO).when(oAuth2ClientApplicationDTO)
            .getAccessTokenValidationResponse();
    OAuth2TokenValidationServiceStub oAuth2TokenValidationServiceStub = Mockito
            .mock(OAuth2TokenValidationServiceStub.class, Mockito.CALLS_REAL_METHODS);
    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationServiceStub)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    Mockito.doReturn(oAuth2TokenValidationServiceStub).when(genericObjectPool).borrowObject();
    oAuthAuthenticator.canHandle(request);
    AuthenticationInfo authenticationInfo = oAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getUsername(), "admin");

}