Example usage for javax.servlet ServletRequest getRemotePort

List of usage examples for javax.servlet ServletRequest getRemotePort

Introduction

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

Prototype

public int getRemotePort();

Source Link

Document

Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.

Usage

From source file:ro.cs.cm.web.filter.GeneralFilter.java

private void log(ServletRequest req) {
    logger.debug("-------------------------------------------------------------");
    logger.debug(req.getRemoteHost() + "(" + req.getRemoteAddr() + "):" + req.getRemotePort());
}

From source file:org.everit.jetty.server.ecm.tests.EchoRemoteInfoServlet.java

@Override
public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException {
    PrintWriter writer = res.getWriter();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("remoteAddr", req.getRemoteAddr());
    jsonObject.put("remoteHost", req.getRemoteHost());
    jsonObject.put("remotePort", req.getRemotePort());
    jsonObject.put("serverName", req.getServerName());
    jsonObject.put("serverPort", req.getServerPort());
    jsonObject.put("protocol", req.getProtocol());
    jsonObject.put("secure", req.isSecure());

    writer.write(jsonObject.toString());

}

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 www  .  jav a  2s .  co m
        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.alfresco.repo.webdav.auth.HTTPRequestAuthenticationFilter.java

/**
 * Run the authentication filter// w  w  w  .  j  av  a 2s. c  o m
 * 
 * @param req
 *            ServletRequest
 * @param resp
 *            ServletResponse
 * @param chain
 *            FilterChain
 * @exception ServletException
 * @exception IOException
 */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    // Assume it's an HTTP request

    final HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;

    // Get the user details object from the session

    SessionUser user = (SessionUser) httpReq.getSession().getAttribute(AUTHENTICATION_USER);

    if (user == null) {
        // Check for the auth header

        String authHdr = httpReq.getHeader(httpServletRequestAuthHeaderName);
        if (logger.isDebugEnabled()) {
            if (authHdr == null) {
                logger.debug("Header not found: " + httpServletRequestAuthHeaderName);
            } else {
                logger.debug("Header is <" + authHdr + ">");
            }
        }

        // Throw an error if we have an unknown authentication

        if ((authHdr != null) && (authHdr.length() > 0)) {

            // Get the user

            final String userName;
            if (m_authPattern != null) {
                Matcher matcher = m_authPattern.matcher(authHdr);
                if (matcher.matches()) {
                    userName = matcher.group();
                    if ((userName == null) || (userName.length() < 1)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Extracted null or empty user name from pattern " + m_authPatternString
                                    + " against " + authHdr);
                        }
                        reject(httpReq, httpResp);
                        return;
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("no pattern match for " + m_authPatternString + " against " + authHdr);
                    }
                    reject(httpReq, httpResp);
                    return;
                }
            } else {
                userName = authHdr;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("User = " + userName);
            }

            // Get the authorization header

            user = transactionService.getRetryingTransactionHelper()
                    .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<SessionUser>() {

                        public SessionUser execute() throws Throwable {
                            try {
                                // Authenticate the user

                                m_authComponent.clearCurrentSecurityContext();
                                m_authComponent.setCurrentUser(userName);

                                return createUserEnvironment(httpReq.getSession(), userName,
                                        authenticationService.getCurrentTicket(), true);
                            } catch (AuthenticationException ex) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Failed", ex);
                                }
                                return null;
                                // Perhaps auto-creation/import is disabled
                            }
                        }
                    });

        } else {
            // Check if the request includes an authentication ticket

            String ticket = req.getParameter(ARG_TICKET);

            if (ticket != null && ticket.length() > 0) {
                // Debug

                if (logger.isDebugEnabled())
                    logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr()
                            + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);

                try {
                    // Validate the ticket
                    authenticationService.validate(ticket);

                    // Need to create the User instance if not already available
                    user = createUserEnvironment(httpReq.getSession(),
                            authenticationService.getCurrentUserName(), ticket, true);
                } catch (AuthenticationException authErr) {
                    // Clear the user object to signal authentication failure
                    if (logger.isDebugEnabled()) {
                        logger.debug("Failed", authErr);
                    }
                    user = null;
                }
            }
        }

        // Check if the user is authenticated, if not then prompt again

        if (user == null) {
            // No user/ticket, force the client to prompt for logon details
            reject(httpReq, httpResp);
            return;
        }
    }

    // Chain other filters

    chain.doFilter(req, resp);
}

From source file:org.alfresco.repo.webdav.auth.AuthenticationFilter.java

/**
 * Run the authentication filter// ww w.jav a2 s .c  o  m
 * 
 * @param context ServletContext
 * @param req ServletRequest
 * @param resp ServletResponse
 * @param chain FilterChain
 * @exception ServletException
 * @exception IOException
 */
public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled())
        logger.debug("Entering AuthenticationFilter.");

    // Assume it's an HTTP request

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;

    // Get the user details object from the session
    SessionUser user = getSessionUser(context, httpReq, httpResp, false);

    if (user == null) {
        if (logger.isDebugEnabled())
            logger.debug("There is no user in the session.");
        // Get the authorization header

        String authHdr = httpReq.getHeader("Authorization");

        if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) {
            if (logger.isDebugEnabled())
                logger.debug("Basic authentication details present in the header.");
            byte[] encodedString = Base64.decodeBase64(authHdr.substring(5).getBytes());

            // ALF-13621: Due to browser inconsistencies we have to try a fallback path of encodings
            Set<String> attemptedAuths = new HashSet<String>(ENCODINGS.length * 2);
            for (String encoding : ENCODINGS) {
                CharsetDecoder decoder = Charset.forName(encoding).newDecoder()
                        .onMalformedInput(CodingErrorAction.REPORT);
                try {
                    // Attempt to decode using this charset 
                    String basicAuth = decoder.decode(ByteBuffer.wrap(encodedString)).toString();

                    // It decoded OK but we may already have tried this string.
                    if (!attemptedAuths.add(basicAuth)) {
                        // Already tried - no need to try again
                        continue;
                    }

                    String username = null;
                    String password = null;

                    // Split the username and password
                    int pos = basicAuth.indexOf(":");
                    if (pos != -1) {
                        username = basicAuth.substring(0, pos);
                        password = basicAuth.substring(pos + 1);
                    } else {
                        username = basicAuth;
                        password = "";
                    }

                    // Go to the repo and authenticate
                    Authorization auth = new Authorization(username, password);
                    if (auth.isTicket()) {
                        authenticationService.validate(auth.getTicket());
                    } else {
                        authenticationService.authenticate(username, password.toCharArray());
                        authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
                    }

                    user = createUserEnvironment(httpReq.getSession(),
                            authenticationService.getCurrentUserName(),
                            authenticationService.getCurrentTicket(), false);

                    // Success so break out
                    break;
                } catch (CharacterCodingException e) {
                    if (logger.isDebugEnabled())
                        logger.debug("Didn't decode using " + decoder.getClass().getName(), e);
                } catch (AuthenticationException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication error ", ex);
                } catch (NoSuchPersonException e) {
                    if (logger.isDebugEnabled())
                        logger.debug("There is no such person error ", e);
                }
            }
        } else {
            // Check if the request includes an authentication ticket

            String ticket = req.getParameter(ARG_TICKET);

            if (ticket != null && ticket.length() > 0) {
                // PowerPoint bug fix
                if (ticket.endsWith(PPT_EXTN)) {
                    ticket = ticket.substring(0, ticket.length() - PPT_EXTN.length());
                }

                // Debug

                if (logger.isDebugEnabled())
                    logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr()
                            + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);

                // Validate the ticket

                authenticationService.validate(ticket);
                authenticationListener.userAuthenticated(new TicketCredentials(ticket));

                // Need to create the User instance if not already available

                String currentUsername = authenticationService.getCurrentUserName();

                user = createUserEnvironment(httpReq.getSession(), currentUsername, ticket, false);
            }
        }

        // Check if the user is authenticated, if not then prompt again

        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("No user/ticket, force the client to prompt for logon details.");

            httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"Alfresco DAV Server\"");
            httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            httpResp.flushBuffer();
            return;
        }
    } else {
        authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket()));
    }

    // Chain other filters

    chain.doFilter(req, resp);
}