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:org.dasein.cloud.vcloud.vCloudMethod.java

private void loadOrg(@Nonnull String endpoint, @Nonnull Org org, @Nonnull String orgId)
        throws CloudException, InternalException {
    String xml;/*from  w w w .  jav a  2s .  c o  m*/

    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [GET (" + (new Date()) + ")] -> " + endpoint
                + " >--------------------------------------------------------------------------------------");
    }
    try {
        HttpClient client = getClient(false);
        HttpGet get = new HttpGet(endpoint);

        get.addHeader("Accept", "application/*+xml;version=" + org.version.version
                + ",application/*+xml;version=" + org.version.version);
        addAuth(get, org.token);

        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            APITrace.trace(provider, "GET org");
            response = client.execute(get);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            logger.error("I/O error from server communications: " + e.getMessage());
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        logger.debug("HTTP STATUS: " + code);

        if (code == HttpServletResponse.SC_NOT_FOUND || code == HttpServletResponse.SC_FORBIDDEN) {
            throw new CloudException("Org URL is invalid");
        } else if (code == HttpServletResponse.SC_UNAUTHORIZED) {
            authenticate(true);
            loadOrg(endpoint, org, orgId);
            return;
        } else if (code == HttpServletResponse.SC_NO_CONTENT) {
            throw new CloudException("No content from org URL");
        } else if (code == HttpServletResponse.SC_OK) {
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    xml = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(xml);
                        wire.debug("");
                    }
                } else {
                    xml = null;
                }
            } catch (IOException e) {
                logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                throw new CloudException(e);
            }
        } else {
            logger.error("Expected OK for GET request, got " + code);
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    xml = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(xml);
                        wire.debug("");
                    }
                } else {
                    xml = null;
                }
            } catch (IOException e) {
                logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                throw new CloudException(e);
            }

            vCloudException.Data data = null;

            if (xml != null && !xml.equals("")) {
                Document doc = parseXML(xml);
                String docElementTagName = doc.getDocumentElement().getTagName();
                String nsString = "";
                if (docElementTagName.contains(":"))
                    nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
                NodeList errors = doc.getElementsByTagName(nsString + "Error");

                if (errors.getLength() > 0) {
                    data = vCloudException.parseException(code, errors.item(0));
                }
            }
            if (data == null) {
                throw new vCloudException(CloudErrorType.GENERAL, code,
                        response.getStatusLine().getReasonPhrase(), "No further information");
            }
            logger.error("[" + code + " : " + data.title + "] " + data.description);
            throw new vCloudException(data);
        }
    } finally {
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [GET (" + (new Date()) + ")] -> " + endpoint
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
    if (xml == null) {
        throw new CloudException("No content from org URL");
    }
    Document doc = parseXML(xml);
    String docElementTagName = doc.getDocumentElement().getTagName();
    String nsString = "";
    if (docElementTagName.contains(":"))
        nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
    NodeList orgList = doc.getElementsByTagName(nsString + "Org");

    for (int i = 0; i < orgList.getLength(); i++) {
        Node orgNode = orgList.item(i);

        if (orgNode.hasAttributes()) {
            Node type = orgNode.getAttributes().getNamedItem("type");

            if (type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg())) {
                Node name = orgNode.getAttributes().getNamedItem("name");

                if (name != null && name.getNodeValue().trim().equals(orgId)) {
                    Node href = orgNode.getAttributes().getNamedItem("href");

                    if (href != null) {
                        Region region = new Region();
                        String url = href.getNodeValue().trim();

                        region.setActive(true);
                        region.setAvailable(true);
                        if (provider.isCompat()) {
                            region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1));
                        } else {
                            region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1));
                        }
                        region.setJurisdiction("US");
                        region.setName(name.getNodeValue().trim());

                        org.endpoint = url.substring(0, url.lastIndexOf("/api/org"));
                        org.region = region;
                        org.url = url;
                        return;
                    }
                }
            }
        }
    }
    throw new CloudException("Could not find " + orgId + " among listed orgs");
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Send a JSON-RPC message to an agent Usage: POST /servlet/{agentId} With a
 * JSON-RPC request as body. Response will be a JSON-RPC response.
 * //from ww  w. ja  v  a 2  s . c om
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, ServletException {

    // retrieve the agent url and the request body
    final String body = StringUtil.streamToString(req.getInputStream());

    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    if (agentId == null || agentId.equals("")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        resp.flushBuffer();
        return;
    }

    if (host.hasPrivate(agentId) && !handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        resp.flushBuffer();
        return;
    }

    // Attach the claimed senderId, or null if not given.
    String senderUrl = req.getHeader("X-Eve-SenderUrl");
    if (senderUrl == null || senderUrl.equals("")) {
        senderUrl = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr();
    }
    final String tag = new UUID().toString();

    final SyncCallback<String> callback = new SyncCallback<String>();

    final AsyncCallbackQueue<String> callbacks = host.getCallbackQueue("HttpTransport", String.class);
    callbacks.push(tag, "", callback);
    //TODO: check if it's base64 encoded data, decode to byte[] and call receive byte[].
    host.receive(agentId, body, URI.create(senderUrl), tag);

    try {
        final Object message = callback.get();
        // return response
        resp.addHeader("Content-Type", "application/json");
        resp.getWriter().println(message.toString());
        resp.getWriter().close();
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "Http Sync receive raised exception.", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Receiver raised exception:" + e.getMessage());
    }
    resp.flushBuffer();
}

From source file:com.boylesoftware.web.Router.java

/**
 * Send request for user authentication, which can be a redirect to the
 * login page, or the 401 HTTP code./* ww w.jav a 2 s . c  o  m*/
 *
 * @param webapp The web-application.
 * @param request The HTTP request.
 * @param response The HTTP response.
 *
 * @throws ServletException If an error happens.
 */
private void sendRequestForAuthentication(final AbstractWebApplication webapp, final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException {

    LooseCannon.heel();

    final String loginPageURI = webapp.getRouterConfiguration().getLoginPageURI();
    if (loginPageURI != null) {

        try (final PooledStringBuffer buf = StringBufferPool.get()) {
            final StringBuilder sb = buf.getStringBuilder();

            sb.append(request.getRequestURI());
            final String queryString = request.getQueryString();
            if (queryString != null)
                sb.append('?').append(queryString);
            final String targetURI = sb.toString();
            sb.setLength(0);

            sb.append("https://").append(request.getServerName());

            final int httpsPort = webapp.getHTTPSPort();
            if (httpsPort != 443)
                sb.append(':').append(httpsPort);

            sb.append(StringUtils.emptyIfNull(request.getContextPath())).append(loginPageURI).append('?')
                    .append(Authenticator.TARGET_URI).append('=');

            try {
                sb.append(URLEncoder.encode(targetURI, "UTF-8"));
            } catch (final UnsupportedEncodingException e) {
                throw new ServletException("UTF-8 is unsupported.", e);
            }

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            response.setHeader("Location", sb.toString());
        }

    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // TODO: configure realm in the application configuration
        response.setHeader("WWW-Authenticate", "Basic realm=\"Application\"");
    }
}

From source file:com.janrain.backplane2.server.Backplane2ControllerTest.java

@Test
public void testTokenEndPointAuthenticationFailure() throws Exception {
    refreshRequestAndResponse();//from www  .  ja va2  s  .  c o m
    request.setRequestURI("/v2/token");
    request.setMethod("POST");
    request.setParameter("grant_type", OAuth2.OAUTH2_TOKEN_GRANT_TYPE_CLIENT_CREDENTIALS);
    setOAuthBasicAuthentication(request, testClient.get(User.Field.USER), "wrong_secret");
    handlerAdapter.handle(request, response, controller);
    logger.info("testTokenEndPointAuthenticationFailure() => " + response.getContentAsString());
    assertTrue(response.getContentAsString().contains(ERR_RESPONSE));
    assertTrue(HttpServletResponse.SC_UNAUTHORIZED == response.getStatus());
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom POST by calling handler to identify URI, reading/parsing
 * data, calling handler and writing results to response.
 *//*ww w.  j a  v  a 2  s . c o  m*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isCollectionURI(areq)) {

                if (req.getContentType().startsWith("application/atom+xml")) {

                    // parse incoming entry
                    Entry entry = Atom10Parser.parseEntry(
                            new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);

                    // call handler to post it
                    Entry newEntry = handler.postEntry(areq, entry);

                    // set Location and Content-Location headers                        
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    // write entry back out to response
                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else if (req.getContentType() != null) {

                    // get incoming title and slug from HTTP header
                    String title = areq.getHeader("Title");

                    // create new entry for resource, set title and type
                    Entry resource = new Entry();
                    resource.setTitle(title);
                    Content content = new Content();
                    content.setType(areq.getContentType());
                    resource.setContents(Collections.singletonList(content));

                    // hand input stream off to hander to post file
                    Entry newEntry = handler.postMedia(areq, resource);

                    // set Location and Content-Location headers
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else {
                    res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                            "No content-type specified in request");
                }

            } else {
                res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request");
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing POST", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing POST", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles updating a project matching the given id Note: Dates should be in
 * the format dd mm yyyy/*from w  ww  .ja v a2 s .  c om*/
 * 
 * @param idpart
 * @throws ProjectServiceException
 * @throws InvalidXmlException
 * @throws BizPolicyException
 * @throws IOException
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.PUT })
public void handleUpdateProjectRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType, @RequestBody byte[] content,
        HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, InvalidXmlException, BizPolicyException, IOException {

    // TODO Why doesn't spring do this?
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        Project newProject = objectBuilder.buildProject(new ByteArrayInputStream(content));
        String id = util.buildRequestUrl(req);

        Project originalProject = projectService.get(id);

        if (originalProject != null) {

            if (newProject.getId().equalsIgnoreCase(id)) {
                if (authorizationService.canUpdateProject(user, newProject)) {
                    projectBizService.updateProject(newProject, user);

                    resp.setCharacterEncoding("UTF-8");
                    resp.setContentType("text/xml");

                    newProject = projectService.get(id);
                    Bop bop = new Bop();
                    bop.addProject(newProject);
                    objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
                } else {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                try {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "ID doesn't match ID of supplied project");
                } catch (Exception ee) {
                    log.debug("Handling exception", ee);
                }
            }

        } else {
            try {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Could not find project with id: " + idpart);
            } catch (Exception ee) {
                log.debug("Handling exception", ee);
            }
        }
    }
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * It does the Kerberos authentication when it has to be done through 
 * username and password. It looks in the default Kerberos domain defined 
 * in the Kerberos config file (krb5.ini or krb5.conf) if there is a valid 
 * user with those credentials. If so, it gets his/her Kerberos ticket.
 * /*from   w  ww.  ja  v  a2 s.  c om*/
 * @param userCred username and password credentials
 *
 * @return the method result in HTTP error format
 */
public int authUsernamePassword(Credential userCred) {

    int result = HttpServletResponse.SC_UNAUTHORIZED;

    Krb5LoginModule login = null;
    userSubject = new Subject();

    logger.debug("authUsernamePassword: using username and password");

    try {

        //Create config objects and pass the credentials      
        Map state = new HashMap();
        UsernamePasswordCredentials usrpwdCred = new UsernamePasswordCredentials(userCred.getUsername(),
                userCred.getPassword());
        state.put("javax.security.auth.login.name", usrpwdCred.getUserName());
        state.put("javax.security.auth.login.password", usrpwdCred.getPassword().toCharArray());
        state.put("java.security.krb5.conf", krbini);

        if (logger.isDebugEnabled()) {
            logger.debug("Username: " + usrpwdCred.getUserName());
        }

        Map option = new HashMap();
        String isDebug = "false";
        if (logger.isDebugEnabled()) {
            isDebug = "true";
        }
        option.put("debug", isDebug);
        option.put("tryFirstPass", "true");
        option.put("useTicketCache", "false");
        option.put("doNotPrompt", "false");
        option.put("storePass", "false");
        option.put("forwardable", "true");

        login = new Krb5LoginModule();
        login.initialize(userSubject, new NegotiateCallbackHandler(), state, option);

        if (login.login()) {
            login.commit();
            logger.debug("Login commit");
            if (id == null) {
                username = usrpwdCred.getUserName();
                id = username;
            }
            logger.debug("username is ... " + id);
            result = HttpServletResponse.SC_OK;
        }
    } catch (LoginException e) {
        logger.error("LoginException while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_UNAUTHORIZED;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Exception while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return result;

}

From source file:com.adito.vfs.webdav.DAVServlet.java

/**
 * Add the headers required for the browser to popup an authentication
 * dialog for a specified realm, and send the
 * {@link HttpServletResponse.SC_UNAUTHORIZED} HTTP response code.
 * //  ww  w. ja  v  a2 s.  c  o m
 * @param request request
 * @param response response
 * @param realm realm.
 * @throws IOException
 */
public static void sendAuthorizationError(HttpServletRequest request, HttpServletResponse response,
        String realm) throws IOException {
    /*
     * If this is for the default realm (i.e Adito Authentication, we
     * need to set up an authentication scheme
     */
    if (realm.equals(WebDAVAuthenticationModule.DEFAULT_REALM)) {
        configureAuthenticationScheme(request, response);
    }

    // Configure the response

    if (log.isDebugEnabled())
        log.debug("Sending auth request for realm " + realm);
    response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    request.getSession().setAttribute(DAVTransaction.ATTR_EXPECTING_REALM_AUTHENTICATION, realm);

}

From source file:com.sslexplorer.vfs.webdav.DAVServlet.java

/**
 * Add the headers required for the browser to popup an authentication
 * dialog for a specified realm, and send the
 * {@link HttpServletResponse.SC_UNAUTHORIZED} HTTP response code.
 * //from w  w w  .j a v  a  2 s .  c o  m
 * @param request request
 * @param response response
 * @param realm realm.
 * @throws IOException
 */
public static void sendAuthorizationError(HttpServletRequest request, HttpServletResponse response,
        String realm) throws IOException {
    /*
     * If this is for the default realm (i.e SSL-Explorer Authentication, we
     * need to set up an authentication scheme
     */
    if (realm.equals(WebDAVAuthenticationModule.DEFAULT_REALM)) {
        configureAuthenticationScheme(request, response);
    }

    // Configure the response

    if (log.isDebugEnabled())
        log.debug("Sending auth request for realm " + realm);
    response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    request.getSession().setAttribute(DAVTransaction.ATTR_EXPECTING_REALM_AUTHENTICATION, realm);

}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override//from w  w  w.j a v a2s  . c  o m
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(new Random().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity)
                            throws Exception {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request)
                throws IOException, AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), isHttps);
                        }
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug("Authentication exception: " + ex.getMessage(), ex);
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}