Example usage for javax.servlet ServletRequest getRemoteHost

List of usage examples for javax.servlet ServletRequest getRemoteHost

Introduction

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

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

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

/**
 * Run the authentication filter//from  w  w  w.j a va2s  .  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/*from  w  w  w  . ja va 2s .  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);
}