Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:com.ikon.servlet.admin.ReportServlet.java

/**
 * Execute report//  www  . j a  v  a 2s .c om
 */
private void execute(String userId, HttpServletRequest request, HttpServletResponse response)
        throws IOException, DatabaseException, JRException, EvalError, ParseException {
    log.debug("execute({}, {}, {})", new Object[] { userId, request, response });
    int rpId = WebUtils.getInt(request, "rp_id");
    int format = WebUtils.getInt(request, "format", ReportUtils.OUTPUT_PDF);
    Report rp = ReportDAO.findByPk(rpId);

    // Set file name
    String fileName = rp.getFileName().substring(0, rp.getFileName().indexOf('.'))
            + ReportUtils.FILE_EXTENSION[format];

    // Set default report parameters
    Map<String, Object> params = new HashMap<String, Object>();
    String host = com.ikon.core.Config.APPLICATION_URL;
    params.put("host", host.substring(0, host.lastIndexOf("/") + 1));

    for (FormElement fe : ReportUtils.getReportParameters(rpId)) {
        params.put(fe.getName(), WebUtils.getString(request, fe.getName()));
    }

    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;

    try {
        baos = ReportUtils.execute(rp, params, format);
        bais = new ByteArrayInputStream(baos.toByteArray());
        WebUtils.sendFile(request, response, fileName, ReportUtils.FILE_MIME[format], false, bais);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
    }

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_REPORT_EXECUTE", Integer.toString(rpId), null,
            rp.toString());
    log.debug("execute: void");
}

From source file:org.ngrinder.script.controller.DavSvnController.java

private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());//from  www . ja v a  2s  . c  om
}

From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java

@Override
public Response createAction(String requestJson, HttpServletRequest servletRequest) {
    try {// ww w  .j  a  v a 2 s  .  c  om
        initializeRequestMDC(servletRequest, null, ActionRequest.CREATE_ACTION);
        log.debug(" entering API createAction ");
        Map<String, String> errorMap = validateRequestHeaders(servletRequest);
        Map<String, String> requestBodyErrors = validateRequestBody(REQUEST_TYPE_CREATE_ACTION, requestJson);
        errorMap.putAll(requestBodyErrors);
        ActionResponseDto actionResponseDto = new ActionResponseDto();
        if (errorMap.isEmpty()) {
            String user = servletRequest.getRemoteUser();
            Action action = JsonUtil.json2Object(requestJson, Action.class);
            action.setData(requestJson);
            Action responseAction = actionManager.createAction(action, user);
            MDC.put(SERVICE_INSTANCE_ID, responseAction.getActionInvariantUuId());
            new MapActionToActionResponseDto().doMapping(responseAction, actionResponseDto);
        } else {
            checkAndThrowError(errorMap);
        }
        actionLogPostProcessor(StatusCode.COMPLETE, true);
        log.debug(" exit API createAction with ActionInvariantUUID= " + MDC.get(SERVICE_INSTANCE_ID));
        return Response.ok(actionResponseDto).build();
    } catch (ActionException e) {
        actionLogPostProcessor(StatusCode.ERROR, e.getErrorCode(), e.getDescription(), true);
        actionErrorLogProcessor(CategoryLogLevel.ERROR, e.getErrorCode(), e.getDescription());
        log.error("");
        throw e;
    } catch (Exception e) {
        actionLogPostProcessor(StatusCode.ERROR, true);
        actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
                ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        log.error(e.getMessage());
        throw e;
    } finally {
        finalAuditMetricsLogProcessor(ActionRequest.CREATE_ACTION.name());
    }

}

From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java

@Override
public Response updateAction(String actionInvariantUuId, String requestJson,
        HttpServletRequest servletRequest) {
    try {/*from   ww w .  j  a  v  a  2 s  .c o  m*/
        initializeRequestMDC(servletRequest, actionInvariantUuId, ActionRequest.UPDATE_ACTION);
        log.debug(" entering API updateAction ");
        Map<String, String> errorMap = validateRequestHeaders(servletRequest);
        Map<String, String> requestBodyErrors = validateRequestBody(REQUEST_TYPE_UPDATE_ACTION, requestJson);
        errorMap.putAll(requestBodyErrors);
        ActionResponseDto actionResponseDto = new ActionResponseDto();
        if (errorMap.isEmpty()) {
            String user = servletRequest.getRemoteUser();
            Action action = JsonUtil.json2Object(requestJson, Action.class);
            action.setActionInvariantUuId(actionInvariantUuId);
            action.setData(requestJson);
            Action updatedAction = actionManager.updateAction(action, user);
            new MapActionToActionResponseDto().doMapping(updatedAction, actionResponseDto);
        } else {
            checkAndThrowError(errorMap);
        }
        actionLogPostProcessor(StatusCode.COMPLETE, true);
        log.debug(" exit API updateAction ");
        return Response.ok(actionResponseDto).build();
    } catch (ActionException e) {
        actionLogPostProcessor(StatusCode.ERROR, e.getErrorCode(), e.getDescription(), true);
        actionErrorLogProcessor(CategoryLogLevel.ERROR, e.getErrorCode(), e.getDescription());
        log.error("");
        throw e;
    } catch (Exception e) {
        actionLogPostProcessor(StatusCode.ERROR, true);
        actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
                ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        log.error(e.getMessage());
        throw e;
    } finally {
        finalAuditMetricsLogProcessor(ActionRequest.UPDATE_ACTION.name());
    }
}

From source file:cz.metacentrum.perun.oauth.PerunAuthenticator.java

private AuthenticatedPrincipal setupPrincipal(HttpServletRequest req) {
    String extSourceLoaString = null;
    String extLogin = null;//  w  ww  .  ja v a 2s. co m
    String extSourceName = null;
    String extSourceType = null;
    int extSourceLoa = 0;
    Map<String, String> additionalInformations = new HashMap<String, String>();

    // If we have header Shib-Identity-Provider, then the user uses identity federation to authenticate
    if (req.getHeader("Shib-Identity-Provider") != null && !req.getHeader("Shib-Identity-Provider").isEmpty()) {
        extSourceName = (String) req.getHeader("Shib-Identity-Provider");
        extSourceType = ExtSourcesManager.EXTSOURCE_IDP;
        if (req.getHeader("loa") != null && !req.getHeader("loa").isEmpty()) {
            extSourceLoaString = req.getHeader("loa");
        } else {
            extSourceLoaString = "2";
        }
        // FIXME: find better place where do the operation with attributes from federation
        if (req.getHeader("eppn") != null && !req.getHeader("eppn").isEmpty()) {
            try {
                String eppn = new String(req.getHeader("eppn").getBytes("ISO-8859-1"));

                // Remove scope from the eppn attribute
                additionalInformations.put("eppnwoscope", eppn.replaceAll("(.*)@.*", "$1"));
            } catch (UnsupportedEncodingException e) {
                log.error("Cannot encode header eppn with value from ISO-8859-1.");
            }
        }
        if (req.getRemoteUser() != null && !req.getRemoteUser().isEmpty()) {
            extLogin = req.getRemoteUser();
        }
    }

    // EXT_SOURCE was defined in Apache configuration (e.g. Kerberos or Local)
    else if (req.getAttribute("EXTSOURCE") != null) {
        extSourceName = (String) req.getAttribute("EXTSOURCE");
        extSourceType = (String) req.getAttribute("EXTSOURCETYPE");
        extSourceLoaString = (String) req.getAttribute("EXTSOURCELOA");

        if (req.getRemoteUser() != null && !req.getRemoteUser().isEmpty()) {
            extLogin = req.getRemoteUser();
        } else if (req.getAttribute("ENV_REMOTE_USER") != null
                && !((String) req.getAttribute("ENV_REMOTE_USER")).isEmpty()) {
            extLogin = (String) req.getAttribute("ENV_REMOTE_USER");
        } else if (extSourceName.equals(ExtSourcesManager.EXTSOURCE_NAME_LOCAL)) {
            /** LOCAL EXTSOURCE **/
            // If ExtSource is LOCAL then generate REMOTE_USER name on the fly
            extLogin = Long.toString(System.currentTimeMillis());
        }
    }

    // X509 cert was used
    // Cert must be last since Apache asks for certificate everytime and fills cert properties even when Kerberos is in place.
    else if (extLogin == null && req.getAttribute("SSL_CLIENT_VERIFY") != null
            && ((String) req.getAttribute("SSL_CLIENT_VERIFY")).equals("SUCCESS")) {
        extSourceName = (String) req.getAttribute("SSL_CLIENT_I_DN");
        extSourceType = ExtSourcesManager.EXTSOURCE_X509;
        extSourceLoaString = (String) req.getAttribute("EXTSOURCELOA");
        extLogin = (String) req.getAttribute("SSL_CLIENT_S_DN");

        // Store X509
        additionalInformations.put("SSL_CLIENT_S_DN", (String) req.getAttribute("SSL_CLIENT_S_DN"));
        additionalInformations.put("dn", (String) req.getAttribute("SSL_CLIENT_S_DN"));

        // Get the X.509 certificate object
        X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");

        // Get the emails
        if (certs != null && certs.length > 0 && certs[0] != null) {
            String emails = "";

            Collection<List<?>> altNames;
            try {
                altNames = certs[0].getSubjectAlternativeNames();
                if (altNames != null) {
                    for (List<?> entry : altNames) {
                        if (((Integer) entry.get(0)) == 1) {
                            emails = (String) entry.get(1);
                        }
                    }
                }
            } catch (CertificateParsingException e) {
                log.error("Error during parsing certificate {}", certs);
            }

            additionalInformations.put("mail", emails);

            // Get organization from the certificate
            String oRegExpPattern = "(o|O)(\\s)*=([^+,])*";
            Pattern oPattern = Pattern.compile(oRegExpPattern);
            Matcher oMatcher = oPattern.matcher(certs[0].getSubjectX500Principal().getName());
            if (oMatcher.find()) {
                String[] org = oMatcher.group().split("=");
                if (org[1] != null && !org[1].isEmpty()) {
                    additionalInformations.put("o", org[1]);
                }
            }
        }
    }

    // Read all headers and store them in additionalInformation
    String headerName = "";
    for (Enumeration<String> headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = (String) headerNames.nextElement();
        // Tomcat expects all headers are in ISO-8859-1
        try {
            additionalInformations.put(headerName,
                    new String(req.getHeader(headerName).getBytes("ISO-8859-1")));
        } catch (UnsupportedEncodingException e) {
            log.error("Cannot encode header {} with value from ISO-8859-1.", headerName,
                    req.getHeader(headerName));
        }
    }

    // extSourceLoa must be number, if any specified then set to 0
    if (extSourceLoaString == null || extSourceLoaString.isEmpty()) {
        extSourceLoa = 0;
    } else {
        try {
            extSourceLoa = Integer.parseInt(extSourceLoaString);
        } catch (NumberFormatException ex) {
            extSourceLoa = 0;
        }
    }

    if (StringUtils.isBlank(extLogin) || StringUtils.isBlank(extSourceName)) {
        throw new IllegalStateException("extLogin or extSourceName is empty.");
    }

    AuthenticatedPrincipal principal = new AuthenticatedPrincipal(extLogin);

    additionalInformations.put("extSourceName", extSourceName);
    additionalInformations.put("extSourceType", extSourceType);
    additionalInformations.put("extSourceLoa", String.valueOf(extSourceLoa));
    principal.setAttributes(additionalInformations);

    principal.setAdminPrincipal(true);

    return principal;
}

From source file:fi.hoski.web.forms.EventServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    Event event;/*  www  .  jav  a 2  s  .  co  m*/
    String[] eventKeys = request.getParameterValues("event");
    if (eventKeys == null) {
        log("Event parameter missing");
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id=\"eNoEvent\">Event parameter missing</div>");
        return;
    } else if (Arrays.asList(eventKeys).contains(Event.EVENT_KEY_CHOOSE)) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id='eChooseEvent'>Choose the event</div>");
        return;
    }

    int count = 1;
    try {
        for (String eventKey : eventKeys) {
            if (!eventKey.isEmpty()) {
                try {
                    event = eventManager.getEvent(eventKey);
                } catch (Exception e) {
                    log(eventKey);
                    log(e.getMessage(), e);
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event not found</div>");
                    return;
                }

                Reservation reservation = new Reservation(event);

                @SuppressWarnings("unchecked")
                Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();

                reservation.set(Reservation.CREATOR, request.getRemoteUser());
                reservation.populate(params);
                String[] bk = params.get(Repository.VENEET_KEY);
                if (bk != null) {
                    Key boatKey = KeyFactory.stringToKey(bk[0]);
                    reservation.set(Repository.VENEID, boatKey);
                }

                eventManager.createReservation(reservation, false);
            } else {
                if (count == 1) {
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event key not found</div>");
                    return;
                }
            }
            count++;
        }
    } catch (EntityNotFoundException ex) {
        throw new ServletException(ex);
    } catch (DoubleBookingException ex) {
        if (count == 1) {
            log(ex.getMessage(), ex);
            sendError(response, HttpServletResponse.SC_CONFLICT,
                    "<div id=\"eDoubleBooking\">Double booking.</div>");
        }
    } catch (EventFullException e) {
        if (count == 1) {
            log(e.getMessage(), e);
            sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eEventFull\">Event full.</div>");
        }
    } catch (BoatNotFoundException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eBoatNotFound\">Boat not found.</div>");

    } catch (MandatoryPropertyMissingException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eMandatoryPropertyMissing\">"
                + e.getMessage() + " mandatory property missing.</div>");

    } catch (ConcurrentModificationException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT,
                "<div id=\"eConcurrentModification\">Concurrent modification.</div>");
    }
    response.setContentType("UTF-8");
    response.getWriter().write("Ilmoittautumisesi on vastaanotettu.");
}

From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java

/**
 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
 *///w ww  .  j a v a 2s.c om
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        ShareStore store = this.getStore();
        OslcResource resource = store.getOslcResource(request.getRequestURL().toString());
        if (resource == null) {
            throw new ShareServiceException(IConstants.SC_NOT_FOUND);
        }

        checkConditionalHeaders(request, resource);

        // cache the created and creator
        Date created = resource.getCreated();
        String creator = resource.getCreator();

        // ok, then we update this resource
        String contentType = request.getContentType();
        if (!contentType.startsWith(IConstants.CT_RDF_XML)) {
            throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
        }

        ServletInputStream content = request.getInputStream();
        OslcResource updatedResource = new OslcResource(resource.getUri());
        List<ShareStatement> statements = store.parse(resource.getUri(), content, contentType);
        updatedResource.addStatements(statements);
        updatedResource.setCreated(created);
        updatedResource.setCreator(creator);
        String userId = request.getRemoteUser();
        String userUri = this.getUserUri(userId);
        store.update(updatedResource, userUri);

        updatedResource = store.getOslcResource(resource.getUri());
        response.setStatus(IConstants.SC_OK);
        response.addHeader(IConstants.HDR_ETAG, updatedResource.getETag());
        response.addHeader(IConstants.HDR_LOCATION, updatedResource.getUri());
        String lastModified = StringUtils.rfc2822(updatedResource.getModified());
        response.addHeader(IConstants.HDR_LAST_MODIFIED, lastModified);

    } catch (ShareServerException e) {
        throw new ShareServiceException(IConstants.SC_BAD, e);
    }
}

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

/**
 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
 *///from   w  ww. j ava 2  s.  com
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        RioStore store = this.getStore();
        OslcResource resource = store.getOslcResource(request.getRequestURL().toString());
        if (resource == null) {
            throw new RioServiceException(IConstants.SC_NOT_FOUND);
        }

        checkConditionalHeaders(request, resource);

        // cache the created and creator
        Date created = resource.getCreated();
        String creator = resource.getCreator();

        // ok, then we update this resource
        String contentType = request.getContentType();
        if (!contentType.startsWith(IConstants.CT_RDF_XML)) {
            throw new RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
        }

        ServletInputStream content = request.getInputStream();
        OslcResource updatedResource = new OslcResource(resource.getUri());
        List<RioStatement> statements = store.parse(resource.getUri(), content, contentType);
        updatedResource.addStatements(statements);
        updatedResource.setCreated(created);
        updatedResource.setCreator(creator);
        String userId = request.getRemoteUser();
        String userUri = this.getUserUri(userId);
        store.update(updatedResource, userUri);

        updatedResource = store.getOslcResource(resource.getUri());
        response.setStatus(IConstants.SC_OK);
        response.addHeader(IConstants.HDR_ETAG, updatedResource.getETag());
        response.addHeader(IConstants.HDR_LOCATION, updatedResource.getUri());
        String lastModified = StringUtils.rfc2822(updatedResource.getModified());
        response.addHeader(IConstants.HDR_LAST_MODIFIED, lastModified);

    } catch (RioServerException e) {
        throw new RioServiceException(IConstants.SC_BAD, e);
    }
}

From source file:csiro.pidsvc.mappingstore.Manager.java

public Manager(HttpServletRequest request) throws NamingException, SQLException, IOException {
    this();//from   w  w  w  .j  a v a2s. c  om

    // Try to retrieve authentication details using Java API.
    _authorizationName = request.getRemoteUser();

    // If it fails try to read 'authorization' HTTP header directly.
    if (_authorizationName == null) {
        String authHeader = request.getHeader("authorization");
        if (authHeader != null && !authHeader.isEmpty() && authHeader.startsWith("Basic")) {
            // Extract user name from basic authentication HTTP header.
            authHeader = authHeader.substring(authHeader.indexOf(' '));
            authHeader = StringUtils.newStringUtf8(Base64.decodeBase64(authHeader));
            _authorizationName = authHeader.substring(0, authHeader.indexOf(':'));
        }
    }
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

private void challengeOrPassThrough(FilterChain chain, HttpServletRequest req, HttpServletResponse res,
        HttpSession session) throws IOException, ServletException {
    try {/*  www  .  j  a  va2s. co m*/
        // In this mode we can only use vaulted credentials. Do not proxy any request headers.
        String userId = AuthenticationUtil.getUserId(req);

        if (userId == null) {
            // If we are as yet unauthenticated but have external authentication, do a ping check as the external user.
            // This will either establish the session or throw us out to log in as someone else!
            userId = req.getRemoteUser();
            // Set the external auth flag so the UI knows we are using SSO etc.
            session.setAttribute(UserFactory.SESSION_ATTRIBUTE_EXTERNAL_AUTH, Boolean.TRUE);
            if (userId != null && logger.isDebugEnabled())
                logger.debug("Initial login from externally authenticated user " + userId);
            setExternalAuthSession(session);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Validating repository session for " + userId);
        }

        if (userId != null && !userId.equalsIgnoreCase(req.getRemoteUser())
                && session.getAttribute(NTLM_AUTH_DETAILS) == null
                && session.getAttribute(AUTH_BY_KERBEROS) == null) // Firefox & Chrome hack for MNT-15561
        {
            session.removeAttribute(UserFactory.SESSION_ATTRIBUTE_EXTERNAL_AUTH);
        }

        Connector conn = connectorService.getConnector(this.endpoint, userId, session);

        // ALF-10785: We must pass through the language header to set up the session in the correct locale
        ConnectorContext ctx;
        if (req.getHeader(HEADER_ACCEPT_LANGUAGE) != null) {
            if (logger.isDebugEnabled())
                logger.debug("Accept-Language header present: " + req.getHeader(HEADER_ACCEPT_LANGUAGE));
            ctx = new ConnectorContext(null,
                    Collections.singletonMap(HEADER_ACCEPT_LANGUAGE, req.getHeader(HEADER_ACCEPT_LANGUAGE)));
        } else {
            ctx = new ConnectorContext();
        }

        Response remoteRes = conn.call("/touch", ctx);
        if (Status.STATUS_UNAUTHORIZED == remoteRes.getStatus().getCode()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Repository session timed out - restarting auth process...");
            }

            String authHdr = remoteRes.getStatus().getHeaders().get(HEADER_WWWAUTHENTICATE);
            if (authHdr != null) {
                // restart SSO login as the repo has timed us out
                restartAuthProcess(session, req, res, authHdr);
            } else {
                // Don't invalidate the session if we've already got external authentication - it may result in us
                // having to reauthenticate externally too!
                if (req.getRemoteUser() == null) {
                    session.invalidate();
                }
                // restart manual login
                redirectToLoginPage(req, res);
            }
            return;
        } else {
            onSuccess(req, res, session, userId);

            // we have local auth in the session and the repo session is also valid
            // this means we do not need to perform any further auth handshake
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication not required, chaining ...");
            }

            chain.doFilter(req, res);
            return;
        }
    } catch (ConnectorServiceException cse) {
        throw new PlatformRuntimeException("Incorrectly configured endpoint ID: " + this.endpoint);
    }
}