Example usage for javax.servlet ServletRequest getLocalPort

List of usage examples for javax.servlet ServletRequest getLocalPort

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getLocalPort.

Prototype

public int getLocalPort();

Source Link

Document

Returns the Internet Protocol (IP) port number of the interface on which the request was received.

Usage

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.support.RequestUtils.java

/**
 * Returns the url to access HQ locally, i.e. without routing through any proxy or load balancer which may be in
 * front of HQ.//from  ww  w. j  ava2  s  .com
 * 
 * @param request A request received by the HQ server from which the HQ URL will be determined
 * @return the local URL for the HQ server hosting the web app
 */
public static String getLocalHqUrl(ServletRequest request) {
    StringBuilder serverUrl = new StringBuilder();

    serverUrl.append(request.getScheme());
    serverUrl.append("://");
    String hostName = request.getLocalName();
    if (hostName.contains(":")) {
        hostName = "[" + hostName + "]";
    }
    serverUrl.append(hostName);
    serverUrl.append(":");
    serverUrl.append(request.getLocalPort());
    if (request.isSecure()) {
        LOGGER.debug("Registering protocol.");
        UntrustedSSLProtocolSocketFactory.register();
    }
    return serverUrl.toString();
}

From source file:org.apache.cxf.fediz.service.idp.STSPortFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    Assert.isTrue(applicationContext != null, "Application context must not be null");
    STSAuthenticationProvider authProvider = authenticationProvider;
    if (authProvider == null) {
        authProvider = applicationContext.getBean(STSAuthenticationProvider.class);
    }//from   w  w  w  . java 2  s .  co m
    Assert.isTrue(authProvider != null, "STSAuthenticationProvider must be configured");

    //Only update the port if HTTPS is used, otherwise ignored (like retrieving the WADL over HTTP)
    if (!isPortSet && request.isSecure()) {
        try {
            URL url = new URL(authProvider.getWsdlLocation());
            if (url.getPort() == 0) {
                URL updatedUrl = new URL(url.getProtocol(), url.getHost(), request.getLocalPort(),
                        url.getFile());
                setSTSWsdlUrl(authProvider, updatedUrl.toString());
                LOG.info("STSAuthenticationProvider.wsdlLocation set to " + updatedUrl.toString());
            } else {
                setSTSWsdlUrl(authProvider, url.toString());
            }
        } catch (MalformedURLException e) {
            LOG.error("Invalid Url '" + authProvider.getWsdlLocation() + "': " + e.getMessage());
        }
    }

    chain.doFilter(request, response);
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception {
    final Authenticator authenticator = authenticatorProvider.getAuthenticator();

    final String authMethod;
    switch (authProps.getAuthType()) {
    case BASIC://from   w w w  .  j av a 2 s.c  om
        authMethod = Constraint.__BASIC_AUTH;
        break;
    case DIGEST:
        authMethod = Constraint.__DIGEST_AUTH;
        break;
    default:
        authMethod = "customauth";
    }

    Constraint constraint = new Constraint();
    constraint.setName(authMethod);
    constraint.setRoles(new String[] { "user" });
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() {
        @Override
        public void setConfiguration(AuthConfiguration configuration) {
        }

        @Override
        public String getAuthMethod() {
            return authMethod;
        }

        @Override
        public void prepareRequest(ServletRequest request) {
        }

        @Override
        public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory)
                throws ServerAuthException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr());
            int remotePort = request.getRemotePort();
            String localAddress = StringUtils.trimToEmpty(request.getLocalAddr());
            int localPort = request.getLocalPort();
            String protocol = StringUtils.trimToEmpty(request.getProtocol());
            String method = StringUtils.trimToEmpty(request.getMethod());
            String requestURI = StringUtils.trimToEmpty(request.getRequestURI());
            Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request);

            Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>();
            for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
                queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue()));
            }

            EntityProvider entityProvider = new EntityProvider() {
                @Override
                public byte[] getEntity() throws IOException {
                    byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME);
                    if (entity == null) {
                        entity = IOUtils.toByteArray(req.getInputStream());
                        req.setAttribute(ATTRIBUTE_NAME, entity);
                    }
                    return entity;
                }
            };

            RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort,
                    protocol, method, requestURI, headers, queryParameters, entityProvider,
                    configuration.getRequestInformation(request));

            try {
                AuthenticationResult result = authenticator.authenticate(requestInfo);

                for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) {
                    if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().size(); i++) {
                            if (i == 0) {
                                response.setHeader(entry.getKey(), entry.getValue().get(i));
                            } else {
                                response.addHeader(entry.getKey(), entry.getValue().get(i));
                            }
                        }
                    }
                }

                switch (result.getStatus()) {
                case CHALLENGED:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_CONTINUE;
                case SUCCESS:
                    Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()),
                            null);
                    Subject subject = new Subject();
                    subject.getPrincipals().add(userPrincipal);
                    return new UserAuthentication(getAuthMethod(),
                            new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" }));
                case FAILURE:
                default:
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return org.eclipse.jetty.server.Authentication.SEND_FAILURE;
                }
            } catch (Throwable t) {
                logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " ("
                        + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(),
                        "Error in HTTP authentication for " + connectorProperties.getName(), t));
                throw new ServerAuthException(t);
            }
        }

        @Override
        public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory,
                User validatedUser) throws ServerAuthException {
            return true;
        }
    });
    securityHandler.addConstraintMapping(constraintMapping);

    securityHandler.setHandler(handler);
    return securityHandler;
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

private boolean authenticateRequest(ServletRequest request, ServletResponse response,
        final AtomicReference<ServletRequest> wrappedRequest) throws IOException {
    boolean requestContinues = false;
    final AtomicBoolean isAuthenticated = new AtomicBoolean(false);
    AuthenticationPlugin authenticationPlugin = cores.getAuthenticationPlugin();
    if (authenticationPlugin == null) {
        return true;
    } else {/*from w  ww .  j  a va2s  . com*/
        // /admin/info/key must be always open. see SOLR-9188
        // tests work only w/ getPathInfo
        //otherwise it's just enough to have getServletPath()
        if (PKIAuthenticationPlugin.PATH.equals(((HttpServletRequest) request).getServletPath())
                || PKIAuthenticationPlugin.PATH.equals(((HttpServletRequest) request).getPathInfo()))
            return true;
        String header = ((HttpServletRequest) request).getHeader(PKIAuthenticationPlugin.HEADER);
        if (header != null && cores.getPkiAuthenticationPlugin() != null)
            authenticationPlugin = cores.getPkiAuthenticationPlugin();
        try {
            log.debug("Request to authenticate: {}, domain: {}, port: {}", request, request.getLocalName(),
                    request.getLocalPort());
            // upon successful authentication, this should call the chain's next filter.
            requestContinues = authenticationPlugin.doAuthenticate(request, response, (req, rsp) -> {
                isAuthenticated.set(true);
                wrappedRequest.set(req);
            });
        } catch (Exception e) {
            log.info("Error authenticating", e);
            throw new SolrException(ErrorCode.SERVER_ERROR, "Error during request authentication, ", e);
        }
    }
    // requestContinues is an optional short circuit, thus we still need to check isAuthenticated.
    // This is because the AuthenticationPlugin doesn't always have enough information to determine if
    // it should short circuit, e.g. the Kerberos Authentication Filter will send an error and not
    // call later filters in chain, but doesn't throw an exception.  We could force each Plugin
    // to implement isAuthenticated to simplify the check here, but that just moves the complexity to
    // multiple code paths.
    if (!requestContinues || !isAuthenticated.get()) {
        response.flushBuffer();
        return false;
    }
    return true;
}

From source file:org.apache.ambari.server.security.SecurityFilter.java

@Override
public void doFilter(ServletRequest serReq, ServletResponse serResp, FilterChain filtCh)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) serReq;
    String reqUrl = req.getRequestURL().toString();

    LOG.debug("Filtering " + reqUrl + " for security purposes");
    if (serReq.getLocalPort() != config.getTwoWayAuthPort()) {
        if (isRequestAllowed(reqUrl)) {
            filtCh.doFilter(serReq, serResp);
        } else {/*ww w.j a  v a 2s  .c om*/
            LOG.warn("This request is not allowed on this port: " + reqUrl);
        }
    } else {
        LOG.debug("Request can continue on secure port " + serReq.getLocalPort());
        filtCh.doFilter(serReq, serResp);
    }
}

From source file:org.forgerock.openidm.filter.AuthFilter.java

/**
 * Whether to allow authentication purely based on client certificates
 * Note that the checking of the certificates MUST be done by setting
 * jetty up for client auth required./*from w  w w. ja v  a2  s .  com*/
 * @return true if authentication via client certificate only is sufficient
 */
private boolean allowClientCertOnly(ServletRequest request) {
    return clientAuthOnly.contains(Integer.valueOf(request.getLocalPort()));
}

From source file:org.sipfoundry.sipxconfig.security.SipxFilterChainProxy.java

/**
 * If internal port is used, automatically authenticate using shared secret
 * If other sipxecs components need to call rest services in sipxconfig, no authentication
 * is needed/*from  w  ww .j a  v a  2  s  . c o m*/
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ServletRequest requestToFilter = request;
    int port = AdminContext.HTTP_ADDRESS.getCanonicalPort();
    if (request.getLocalPort() == port && request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        requestToFilter = new AuthorizedServletRequest(httpRequest);
        LOG.debug("Internal request port: " + port);
    }
    super.doFilter(requestToFilter, response, chain);
}