Example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Click Source Link

Document

Status code (401) indicating that the request requires HTTP authentication.

Usage

From source file:com.cloudera.alfredo.server.KerberosAuthenticationHandler.java

/**
 * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only
 * after the Kerberos SPNEGO sequence completed successfully.
 * <p/>/*from  w  w  w  .  ja va 2 s.  c om*/
 *
 * @param request the HTTP client request.
 * @param response the HTTP client response.
 * @return an authentication token if the Kerberos SPNEGO sequence is complete and valid,
 * <code>null</code> if is in progress (in this case the handler handles the response to the client).
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
 */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);

    if (authorization == null) {
        response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        LOG.trace("SPNEGO starts");
    } else if (!authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '"
                + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        Subject serverSubject = loginContext.getSubject();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    try {
                        gssContext = gssManager.createContext((GSSCredential) null);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = base64.encodeToString(serverToken);
                            response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE,
                                    KerberosAuthenticator.NEGOTIATE + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            LOG.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            int index = clientPrincipal.indexOf("/");
                            if (index == -1) {
                                index = clientPrincipal.indexOf("@");
                            }
                            String userName = (index == -1) ? clientPrincipal
                                    : clientPrincipal.substring(0, index);
                            token = new AuthenticationToken(userName, clientPrincipal, TYPE);
                            response.setStatus(HttpServletResponse.SC_OK);
                            LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}

From source file:com.mindquarry.user.webapp.AuthenticationFilter.java

/**
 * Filter method that implements the actual logic and decides whether to
 * process by calling the next filter in the chain (another filter or the
 * servlet) or stopping here and sending a special response (authentication
 * request or redirect).//w  w w .ja  v a 2 s.c o  m
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    // cast to http request and response due to read and set http headers
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    // always send an authentication request in order to avoid one round
    // trip
    response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm_ + "\"");

    // only do authentication for protected URIs, eg. excluded login page
    if (isProtected(request)) {
        // the request that checks if the credentials are ok by providing
        // them as request parameters instead of sending the HTTP basic
        // authorization header
        if (isCheckLoginRequest(request)) {
            // look for credentials in request parameter
            if (authenticateUserFromRequestParams(request)) {
                writeBUContinueResponse(response);
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }

        } else {
            // look for credentials in HTTP auth header
            Credentials authenticated = authenticateUser(request);

            // the special login request is done to actually perform the
            // authentication, this is typically the second step initiated by
            // the login page
            if (isLoginRequest(request)) {

                if (authenticated == null) {
                    // not authenticated. trigger auth. with username / password
                    // either by the HTTP auth dialog in the browser or
                    // automatically by Javascript XMLHttpRequest
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    // authenticated. redirect to original target
                    String originalUrl = request.getParameter(TARGET_URI_PARAM);
                    String redirectUrl = response.encodeRedirectURL((originalUrl != null ? originalUrl : "."));

                    if (isAJAXRequest(request)) {
                        // no redirect necessary, the AJAX client must do
                        // this himself (because redirects as answers to
                        // XHR requests, if supported by the browser, will
                        // redirect the XHR, but not notify the calling
                        // javascript about the new url)

                        // in ajax requests we have to send some valid XML
                        // as content, otherwise some browsers make problems
                        writeBUContinueResponse(response);
                        response.setStatus(HttpServletResponse.SC_OK);

                    } else {
                        response.sendRedirect(redirectUrl);
                    }
                }

                // no further servlet processing.
                return;

            } else {
                // 99 percent of all pages, not the special login request.

                // here we either have the first request to the server, ie.
                // not yet authenticated, or some client that does not send the
                // authorization data preemptively (although he already did
                // authenticate) -> see isGuiBrowserRequest()
                if (authenticated == null) {
                    // not authenticated.

                    // standard browser with preemptive sending auth data, thus
                    // it must be the first request -> go to login page
                    if (isGuiBrowserRequest(request)) {
                        String loginUrl = buildLoginUrlForRequest(request);
                        String redirectUrl = response.encodeRedirectURL(loginUrl);
                        response.sendRedirect(redirectUrl);
                    } else {
                        // trigger simple client auth. or re-authentication
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    }

                    // no further servlet processing.
                    return;

                } else {
                    // authenticated. make username available as request
                    // attribute
                    request.setAttribute(USERNAME_ATTR, authenticated.username);
                    request.setAttribute(PASSWORD_ATTR, authenticated.password);
                    CurrentUser currentUser = lookupCurrentUserRequestBean();
                    currentUser.setId(authenticated.username);
                }
            }
        }
    }
    // access granted, proceed with the servlet
    chain.doFilter(servletRequest, servletResponse);
}

From source file:com.erudika.para.security.JWTRestfulAuthFilter.java

private boolean revokeAllTokensHandler(HttpServletRequest request, HttpServletResponse response) {
    JWTAuthentication jwtAuth = getJWTfromRequest(request);
    if (jwtAuth != null) {
        try {//from   www .j  av a  2s .  co m
            User user = SecurityUtils.getAuthenticatedUser(jwtAuth);
            if (user != null) {
                jwtAuth = (JWTAuthentication) authenticationManager.authenticate(jwtAuth);
                if (jwtAuth != null && jwtAuth.getApp() != null) {
                    user.resetTokenSecret();
                    CoreUtils.overwrite(jwtAuth.getApp().getAppIdentifier(), user);
                    RestUtils.returnStatusResponse(response, HttpServletResponse.SC_OK,
                            Utils.formatMessage("All tokens revoked for user {0}!", user.getId()));
                    return true;
                }
            }
        } catch (Exception ex) {
            logger.debug(ex);
        }
    }
    response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
    RestUtils.returnStatusResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Invalid or expired token.");
    return false;
}

From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.POST, value = "user/notification/sync")
public @ResponseBody ResponseEntity<SyncData> syncDataByUser(HttpServletRequest request,
        HttpServletResponse response, @RequestParam long since, @RequestBody Map<String, Object> obj)
        throws IOException, ClassNotFoundException, DataException {
    String userId = getUserId();/*w  w w. jav  a 2s . co m*/
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    SyncDataRequest syncReq = Util.convertRequest(obj, since);
    SyncData out = notificationManager.synchronizeByUser(userId, syncReq.getSyncData());
    return new ResponseEntity<SyncData>(out, HttpStatus.OK);
}

From source file:com.bosch.iot.things.example.historian.Controller.java

/**
 * Check access on specific property by doing a callback to the Things service.
 *///w w  w .j  a v a2  s  . c o  m
private boolean checkAccess(String thingId, String feature, String path)
        throws UnsupportedEncodingException, IOException {
    HttpServletRequest httpReq = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();
    HttpServletResponse httpRes = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getResponse();

    // enforce BASIC auth
    String auth = httpReq.getHeader("Authorization");
    if (auth == null) {
        httpRes.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }

    String httpid = URLEncoder.encode(thingId, "UTF-8") + "/features/" + URLEncoder.encode(feature, "UTF-8")
            + "/properties/" + path;
    HttpGet thingsRequest = new HttpGet(
            getConfig().getProperty("thingsServiceEndpointUrl") + "/cr/1/things/" + httpid);

    // fill in apiToken if not provided
    String apiToken = getConfig().getProperty("apiToken");
    if (apiToken != null && httpReq.getHeader("x-cr-api-token") == null) {
        thingsRequest.addHeader("x-cr-api-token", apiToken);
    }

    // forward all other Headers to Things service
    Enumeration<String> headerNames = httpReq.getHeaderNames();
    if (headerNames != null) {
        final Set<String> headersToIgnore = new HashSet(Arrays.asList(new String[] { "host" }));
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (!headersToIgnore.contains(name)) {
                thingsRequest.addHeader(name, httpReq.getHeader(name));
            }
        }
    }

    LOGGER.debug("Callback to Things service: {}", thingsRequest);

    try (CloseableHttpResponse response = getHttpClient().execute(thingsRequest)) {
        LOGGER.debug("... retured {}", response.getStatusLine());

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode < 200 || statusCode > 299) {
            httpRes.setStatus(statusCode);
            return false;
        }
    }

    return true;
}

From source file:com.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationFilter.java

/**
 * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain)./*from www.  j av  a  2s  .c o  m*/
 */
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(header);
    logger.debug(pathInfo);

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) {
        /**
         * It is not needed to authenticate these operations
         */
        logger.debug("Operation does not need to Authenticate");
    } else {

        if (header == null) {
            header = "";
        }

        try {
            String token = header;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            String txId = request.getHeader("txId");
            if (txId != null) {
                MDC.put("txId", txId);

            }

            logger.debug(tenantId);
            logger.debug(token);
            // String tenantId = request.getPathInfo().split("/")[3];

            if (debug) {
                logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token
                        + "' and tenant " + tenantId);
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token,
                    tenantId);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            // check AUTH-TOKEN and VDC are the same
            String uri = request.getRequestURI();
            logger.debug("URI: " + uri);
            if (uri.contains("vdc") && !uri.contains(tenantId)) {
                String str = "Bad credentials for requested VDC";
                logger.info(str);
                throw new AccessDeniedException(str);
            }

            UserDetails user = (UserDetails) authResult.getPrincipal();
            logger.debug("User: " + user.getUsername());
            logger.debug("Token: " + user.getPassword());
            if (authResult.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);

            }

            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

        } catch (AuthenticationException failed) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication request for failed: " + failed);
            }

            rememberMeServices.loginFail(request, response);
            onUnsuccessfulAuthentication(request, response, failed);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                authenticationEntryPoint.commence(request, response, failed);
            }

            return;
        } catch (AccessDeniedException ex) {
            throw ex;
        } catch (Exception ex) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication exception: " + ex);
            }

            rememberMeServices.loginFail(request, response);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
            return;
        }

        String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

        response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);

}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilter.java

/**
 * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain)./*from   ww  w.  j  a v a2s.co m*/
 */
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(headerToken);
    logger.debug(pathInfo);

    // first of all, check HTTP if exists accept header
    if (!validateAcceptHeader(request, response)) {
        return;
    }

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) {
        /**
         * It is not needed to authenticate these operations
         */
        logger.debug("Operation does not need to Authenticate");
    } else {

        if (headerToken == null) {
            headerToken = "";
        }

        try {
            String token = headerToken;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            logger.debug(tenantId);
            logger.debug(token);
            // String tenantId = request.getPathInfo().split("/")[3];

            if (debug) {
                logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token
                        + "' and tenant " + tenantId);
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token,
                    tenantId);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            // check AUTH-TOKEN and VDC are the same
            String uri = request.getRequestURI();
            logger.debug("URI: " + uri);
            if (uri.contains("vdc") && !uri.contains(tenantId)) {
                String str = "Bad credentials for requested VDC";
                logger.info(str);
                throw new AccessDeniedException(str);
            }

            UserDetails user = (UserDetails) authResult.getPrincipal();

            logger.debug("User: " + user.getUsername());
            logger.debug("Token: " + user.getPassword());
            if (authResult.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);

            }

            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

        } catch (AuthenticationException failed) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication request for failed: " + failed);
            }

            rememberMeServices.loginFail(request, response);
            onUnsuccessfulAuthentication(request, response, failed);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                authenticationEntryPoint.commence(request, response, failed);
            }

            return;
        } catch (AccessDeniedException ex) {
            throw ex;
        } catch (Exception ex) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication exception: " + ex);
            }

            rememberMeServices.loginFail(request, response);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
            return;
        }

        String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

        response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);

}

From source file:edu.indiana.d2i.htrc.oauth2.filter.OAuth2Filter.java

private void respondWithError(HttpServletResponse resp, OAuthProblemException error)
        throws IOException, ServletException {

    OAuthResponse oauthResponse = null;/*from  w  ww . j  a va2 s. c om*/

    try {
        if (OAuthUtils.isEmpty(error.getError())) {
            oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm(realm)
                    .buildHeaderMessage();

        } else {

            int responseCode = 401;
            if (error.getError().equals(OAuthError.CodeResponse.INVALID_REQUEST)) {
                responseCode = 400;
            } else if (error.getError().equals(OAuthError.ResourceResponse.INSUFFICIENT_SCOPE)) {
                responseCode = 403;
            }

            oauthResponse = OAuthRSResponse.errorResponse(responseCode).setRealm(realm)
                    .setError(error.getError()).setErrorDescription(error.getDescription())
                    .setErrorUri(error.getUri()).buildBodyMessage();
        }
        resp.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        resp.setContentType("text/html");
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.getWriter().println(oauthResponse.getBody());

    } catch (OAuthSystemException e) {
        throw new ServletException(e);
    }
}

From source file:org.slc.sli.dashboard.web.controller.ConfigController.java

/**
 * Controller to return configs (driver and all edOrg levels), without waterfall logic.
 * The 'params' parameter contains a map of url query parameters. The parameters are matched
 * to the attributes in the JSON config files.
 *
 * @param configType// w w  w  .ja  v a  2  s. com
 * @param request
 * @param response
 * @return DriverConfig and all EdOrg hierarchy JSON.
 */
@RequestMapping(value = CONFIG_ALL, method = RequestMethod.GET)
@ResponseBody
public List<ConfigWrapper> handleConfigPanels(@RequestParam Map<String, String> configType,
        final HttpServletRequest request, HttpServletResponse response) {

    String token = SecurityUtil.getToken();
    Boolean isAdmin = SecurityUtil.isAdmin();
    if (isAdmin != null && isAdmin.booleanValue()) {
        Map<String, Collection<Config>> mapConfigs = configManager.getAllConfigByType(token,
                userEdOrgManager.getUserEdOrg(token), configType);

        // re-organize config objects. group by Education Agency Name
        Map<String, List<ConfigWrapper>> mapConfigWrappers = new HashMap<String, List<ConfigWrapper>>();
        if (mapConfigs != null) {
            Set<String> edOrgNames = mapConfigs.keySet();
            for (String edOrgName : edOrgNames) {
                // get Collection of Config by edOrgName
                Collection<Config> configs = mapConfigs.get(edOrgName);
                for (Config config : configs) {
                    ConfigWrapper configWrapper = new ConfigWrapper(config);
                    configWrapper.setEducationAgencyName(edOrgName);
                    List<ConfigWrapper> configWrappers = mapConfigWrappers.get(configWrapper.getId());
                    if (configWrappers == null) {
                        configWrappers = new LinkedList<ConfigWrapper>();
                        mapConfigWrappers.put(configWrapper.getId(), configWrappers);
                    }
                    configWrappers.add(configWrapper);
                }
            }
        }

        // make a single array of ConfigWrapper
        List<ConfigWrapper> listConfigWrapper = new LinkedList<ConfigWrapper>();
        for (String idName : mapConfigWrappers.keySet()) {
            listConfigWrapper.addAll(mapConfigWrappers.get(idName));
        }

        // make alphabetical order (1st. Config.id 2nd. EdOrgName)
        Collections.sort(listConfigWrapper);
        return listConfigWrapper;
    }
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return null;
}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

@Override
public List<Endpoint> getEndpointsForToken(String userToken, String tracingHeader) throws AuthServiceException {
    final Map<String, String> headers = new HashMap<>();

    List<Endpoint> endpointList;

    try {//from ww w.j  a  v  a 2  s.co  m
        headers.put(ACCEPT_HEADER, MediaType.APPLICATION_XML);
        headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false));
        if (tracingHeader != null) {
            headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader);
        }

        ServiceClientResponse endpointListResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

        switch (endpointListResponse.getStatus()) {
        case HttpServletResponse.SC_OK:
            endpointList = getEndpointList(endpointListResponse);
            break;
        case HttpServletResponse.SC_UNAUTHORIZED:
            LOG.error("Unable to get endpoints for user: " + endpointListResponse.getStatus()
                    + " :admin token expired. "
                    + "Retrieving new admin token and retrying endpoints retrieval...");

            headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true));
            endpointListResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                    targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

            if (endpointListResponse.getStatus() == HttpServletResponse.SC_OK) {
                endpointList = getEndpointList(endpointListResponse);
            } else {
                delegationMessage.set("Unable to get endpoints for user: " + userToken
                        + " with configured admin credentials");
                LOG.error("Still unable to get endpoints: " + endpointListResponse.getStatus());
                throw new AuthServiceException(
                        "Unable to retrieve service catalog for user with configured Admin credentials");
            }
            break;
        case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
        case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + endpointListResponse.getStatus());
            throw buildAuthServiceOverLimitException(endpointListResponse);
        default:
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + endpointListResponse.getStatus());
            LOG.error("Unable to get endpoints for token. Status code: " + endpointListResponse.getStatus());
            throw new AuthServiceException("Unable to retrieve service catalog for user. Response from "
                    + targetHostUri + ": " + endpointListResponse.getStatus());
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to get endpoints.", e);
    }

    return endpointList;
}