Search in sources :

Example 1 with BasicAuthCredentials

use of org.alfresco.repo.web.auth.BasicAuthCredentials in project alfresco-remote-api by Alfresco.

the class AuthenticationFilter method doFilter.

// Various services required by NTLM authenticator
/**
 * Run the authentication filter
 *
 * @param context ServletContext
 * @param req ServletRequest
 * @param resp ServletResponse
 * @param chain FilterChain
 * @exception ServletException
 * @exception IOException
 */
@Override
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());
                        if (authenticationListener != null) {
                            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());
                }
                if (logger.isDebugEnabled())
                    logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);
                // Validate the ticket
                authenticationService.validate(ticket);
                if (authenticationListener != null) {
                    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);
            }
        }
        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 {
        if (authenticationListener != null) {
            authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket()));
        }
    }
    // Chain other filters
    chain.doFilter(req, resp);
}
Also used : TicketCredentials(org.alfresco.repo.web.auth.TicketCredentials) CharsetDecoder(java.nio.charset.CharsetDecoder) BasicAuthCredentials(org.alfresco.repo.web.auth.BasicAuthCredentials) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) NoSuchPersonException(org.alfresco.service.cmr.security.NoSuchPersonException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CharacterCodingException(java.nio.charset.CharacterCodingException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authorization(org.alfresco.repo.security.authentication.Authorization) SessionUser(org.alfresco.repo.SessionUser) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 2 with BasicAuthCredentials

use of org.alfresco.repo.web.auth.BasicAuthCredentials in project acs-community-packaging by Alfresco.

the class BasicAuthenticationHandler method isUserAuthenticated.

/**
 * Returns <code>true</code> if the user is authenticated and their details are cached in the session
 *
 * @param context
 *            the servlet context
 * @param request
 *            the servlet request
 * @return <code>true</code>, if the user is authenticated
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             On other errors.
 */
public boolean isUserAuthenticated(ServletContext context, HttpServletRequest request) throws IOException, ServletException {
    String authHdr = request.getHeader(HEADER_AUTHORIZATION);
    HttpSession session = request.getSession(false);
    SessionUser sessionUser = session == null ? null : (SessionUser) session.getAttribute(USER_SESSION_ATTRIBUTE);
    if (sessionUser == null) {
        if (remoteUserMapper != null && (!(remoteUserMapper instanceof ActivateableBean) || ((ActivateableBean) remoteUserMapper).isActive())) {
            String userId = remoteUserMapper.getRemoteUser(request);
            if (userId != null) {
                // authenticated by other
                authenticationComponent.setCurrentUser(userId);
                request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(userId, authenticationService.getCurrentTicket(), personService.getPerson(userId)));
                return true;
            }
        }
        if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase(BASIC_START)) {
            String basicAuth = new String(Base64.decodeBase64(authHdr.substring(5).getBytes()));
            String username = null;
            String password = null;
            int pos = basicAuth.indexOf(":");
            if (pos != -1) {
                username = basicAuth.substring(0, pos);
                password = basicAuth.substring(pos + 1);
            } else {
                username = basicAuth;
                password = "";
            }
            try {
                if (logger.isDebugEnabled())
                    logger.debug("Authenticating user '" + username + "'");
                authenticationService.authenticate(username, password.toCharArray());
                // Normalize the user ID taking into account case sensitivity settings
                username = authenticationService.getCurrentUserName();
                if (logger.isDebugEnabled())
                    logger.debug("Authenticated user '" + username + "'");
                authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
                request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(username, authenticationService.getCurrentTicket(), personService.getPerson(username)));
                return true;
            } catch (AuthenticationException ex) {
                authenticationListener.authenticationFailed(new BasicAuthCredentials(username, password), ex);
            }
        }
    } else {
        try {
            authenticationService.validate(sessionUser.getTicket());
            authenticationListener.userAuthenticated(new TicketCredentials(sessionUser.getTicket()));
            return true;
        } catch (AuthenticationException ex) {
            authenticationListener.authenticationFailed(new TicketCredentials(sessionUser.getTicket()), ex);
            session.invalidate();
        }
    }
    return false;
}
Also used : TicketCredentials(org.alfresco.repo.web.auth.TicketCredentials) SessionUser(org.alfresco.repo.SessionUser) SessionUser(org.alfresco.repo.SessionUser) User(org.alfresco.web.bean.repository.User) BasicAuthCredentials(org.alfresco.repo.web.auth.BasicAuthCredentials) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) ActivateableBean(org.alfresco.repo.management.subsystems.ActivateableBean)

Example 3 with BasicAuthCredentials

use of org.alfresco.repo.web.auth.BasicAuthCredentials in project alfresco-remote-api by Alfresco.

the class AuthenticationFilter method doFilterInternal.

protected void doFilterInternal(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    if (logger.isTraceEnabled()) {
        logger.trace("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());
                        if (authenticationListener != null) {
                            authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
                        }
                    }
                    user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), authenticationService.getCurrentTicket(), false);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Successfully created user environment, login using basic auth or ROLE_TICKET for user: " + AuthenticationUtil.maskUsername(user.getUserName()));
                    }
                    // 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());
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);
                }
                // Validate the ticket
                authenticationService.validate(ticket);
                if (authenticationListener != null) {
                    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);
                if (logger.isTraceEnabled()) {
                    logger.trace("Successfully created user environment, login using TICKET for user: " + AuthenticationUtil.maskUsername(user.getUserName()));
                }
            }
        }
        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 {
        if (authenticationListener != null) {
            authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket()));
        }
        if (logger.isTraceEnabled()) {
            logger.trace("User already set to: " + AuthenticationUtil.maskUsername(user.getUserName()));
        }
    }
    // Chain other filters
    chain.doFilter(req, resp);
}
Also used : TicketCredentials(org.alfresco.repo.web.auth.TicketCredentials) CharsetDecoder(java.nio.charset.CharsetDecoder) BasicAuthCredentials(org.alfresco.repo.web.auth.BasicAuthCredentials) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) NoSuchPersonException(org.alfresco.service.cmr.security.NoSuchPersonException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CharacterCodingException(java.nio.charset.CharacterCodingException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authorization(org.alfresco.repo.security.authentication.Authorization) SessionUser(org.alfresco.repo.SessionUser) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

SessionUser (org.alfresco.repo.SessionUser)3 AuthenticationException (org.alfresco.repo.security.authentication.AuthenticationException)3 BasicAuthCredentials (org.alfresco.repo.web.auth.BasicAuthCredentials)3 TicketCredentials (org.alfresco.repo.web.auth.TicketCredentials)3 CharacterCodingException (java.nio.charset.CharacterCodingException)2 CharsetDecoder (java.nio.charset.CharsetDecoder)2 HashSet (java.util.HashSet)2 LinkedHashSet (java.util.LinkedHashSet)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Authorization (org.alfresco.repo.security.authentication.Authorization)2 NoSuchPersonException (org.alfresco.service.cmr.security.NoSuchPersonException)2 HttpSession (javax.servlet.http.HttpSession)1 ActivateableBean (org.alfresco.repo.management.subsystems.ActivateableBean)1 User (org.alfresco.web.bean.repository.User)1