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:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * Extract information from AxisFault and map it to a HTTP Status code.
 *
 * @param af Axis Fault/* w  ww.  ja  v a  2  s .c o  m*/
 * @return HTTP Status code.
 */
private int getHttpServletResponseStatus(AxisFault af) {
    // subclasses... --Glen
    return af.getFaultCode().getLocalPart().startsWith("Server.Unauth") ? HttpServletResponse.SC_UNAUTHORIZED
            : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    // This will raise a 401 for both
    // "Unauthenticated" & "Unauthorized"...
}

From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java

@POST
@Path("deleteEvents")
@Produces(MediaType.APPLICATION_JSON)/*from ww w.ja v  a2 s .  co  m*/
@RestQuery(name = "deleteevents", description = "Deletes a json list of events by their given ids e.g. [\"1dbe7255-e17d-4279-811d-a5c7ced689bf\", \"04fae22b-0717-4f59-8b72-5f824f76d529\"]", returnDescription = "Returns a JSON object containing a list of event ids that were deleted, not found or if there was a server error.", reponses = {
        @RestResponse(description = "Events have been deleted", responseCode = HttpServletResponse.SC_OK),
        @RestResponse(description = "The list of ids could not be parsed into a json list.", responseCode = HttpServletResponse.SC_BAD_REQUEST),
        @RestResponse(description = "If the current user is not authorized to perform this action", responseCode = HttpServletResponse.SC_UNAUTHORIZED) })
public Response deleteEvents(String eventIdsContent) throws UnauthorizedException {
    if (StringUtils.isBlank(eventIdsContent)) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    JSONArray eventIdsJsonArray;
    try {
        eventIdsJsonArray = (JSONArray) parser.parse(eventIdsContent);
    } catch (org.json.simple.parser.ParseException e) {
        logger.error("Unable to parse '{}' because: {}", eventIdsContent, ExceptionUtils.getStackTrace(e));
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (ClassCastException e) {
        logger.error("Unable to cast '{}' because: {}", eventIdsContent, ExceptionUtils.getStackTrace(e));
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    BulkOperationResult result = new BulkOperationResult();

    for (Object eventIdObject : eventIdsJsonArray) {
        String eventId = eventIdObject.toString();
        try {
            if (!removeEvent(eventId)) {
                result.addServerError(eventId);
            } else {
                result.addOk(eventId);
            }
        } catch (NotFoundException e) {
            result.addNotFound(eventId);
        }
    }
    return Response.ok(result.toJson()).build();
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.PUT, value = "/recurrent/{itineraryId}")
public @ResponseBody Boolean updateRecurrentJourney(HttpServletResponse response,
        @RequestBody(required = false) BasicRecurrentJourney recurrent, @PathVariable String itineraryId)
        throws Exception {
    try {//from w w w  .  j a  v  a2 s  . com
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

        String objectClientId = recurrent.getClientId();
        if (!itineraryId.equals(objectClientId)) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            return null;
        }

        Map<String, Object> pars = new TreeMap<String, Object>();
        pars.put("clientId", itineraryId);
        // RecurrentJourneyObject res =
        // domainStorage.searchDomainObjectFixForSpring(pars,
        // RecurrentJourneyObject.class);
        RecurrentJourneyObject res = domainStorage.searchDomainObject(pars, RecurrentJourneyObject.class);

        if (res != null) {
            if (!userId.equals(res.getUserId())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return null;
            }

            res.setData(recurrent.getData());
            res.setName(recurrent.getName());
            res.setMonitor(recurrent.isMonitor());

            domainStorage.saveRecurrent(res);

            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.SPNEGOLoginModuleTestCase.java

/**
 * Kerberos simple scenario. Client provides a valid Kerberos token (without SPNEGO envelope) in the first round. See
 * <a href="https://tools.ietf.org/html/rfc4121">RFC-4121</a>.
 *//*from  w w  w .j  a va  2s  . c o  m*/
@Test
@OperateOnDeployment("WEB")
public void testPlainKerberosWorkflow(@ArquillianResource URL webAppURL) throws Exception {
    final URI uri = getServletURI(webAppURL, SimpleSecuredServlet.SERVLET_PATH);
    final byte[] kerberosToken = createNewKerberosTicketForHttp(uri);
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        final HttpGet httpGet = new HttpGet(uri);
        HttpResponse response = httpClient.execute(httpGet);
        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        assertHttpHeader(response, HEADER_WWW_AUTHENTICATE, "Negotiate");
        EntityUtils.consume(response.getEntity());
        httpGet.setHeader(HEADER_AUTHORIZATION,
                "Negotiate " + Base64.getEncoder().encodeToString(kerberosToken));
        response = httpClient.execute(httpGet);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(
                    "Negotiate response in HTTP header:\n" + KerberosTestUtils.dumpNegotiateHeader(response));
        }
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        assertEquals("Unexpected response body", SimpleSecuredServlet.RESPONSE_BODY,
                EntityUtils.toString(response.getEntity()));
    }
}

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.Cas2Authenticator.java

@Override
public boolean onError(HttpServletRequest request, HttpServletResponse response) {
    try {/*from   ww w.  j  av  a 2 s  .  c  o m*/
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (errorPage != null) {
            response.sendRedirect(errorPage);
        }
    } catch (Exception e) {
        log.error(e);
        return false;
    }
    return true;
}

From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java

/**
 *
 * @param httpServletRequest//w  w w . jav a2 s .  c o m
 * @param httpServletResponse
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    String format;
    String language;
    String redirect_url;

    this.logger.debug(
            "[" + config.getProperty("service.name") + "] " + "PathInfo = " + httpServletRequest.getPathInfo());
    this.logger.debug("[" + config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    if (path != null) {
        String[] params = path.substring(1, path.length()).split("/");

        if (params.length == 1) {
            patronid = params[0];
            service = "patron";
        } else if (params.length == 2) {
            patronid = params[0];
            service = params[1];
        } else if (params[1].equals("items") && params.length > 2) {
            patronid = params[0];
            for (int i = 1; i < params.length; i++) {

                service += params[i];
                if (i < params.length - 1) {
                    service += "/";
                }
            }
        }
    }

    if (patronid.equals("patronid")) {

        patronid = "";
    }

    this.logger.debug("[" + config.getProperty("service.name") + "] " + "Service: " + service);
    this.logger.debug("[" + config.getProperty("service.name") + "] " + "Patron: " + patronid);

    format = "html";

    if (httpServletRequest.getParameter("format") != null
            && !httpServletRequest.getParameter("format").equals("")) {

        format = httpServletRequest.getParameter("format");
    } else {

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerNameKey = headerNames.nextElement();

            if (headerNameKey.equals("Accept")) {

                this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

                if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                    format = "html";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                    format = "xml";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                    format = "json";
                }
            }
        }
    }

    this.logger.info("format = " + format);

    if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format, "", "");
    } else {

        // read requestBody
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = httpServletRequest.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
            /*report an error*/ }

        String requestBody = jb.toString();

        // read document list
        DocumentList documentList = null;

        try {

            // read DocumentList
            documentList = mapper.readValue(requestBody, DocumentList.class);
        } catch (Exception e) {

            if (!requestBody.equals("")) {

                String[] params = requestBody.split("&");

                if (params.length > 1) {

                    documentList = new DocumentList();
                    documentList.setDoc(new ArrayList<Document>());

                    for (String param : params) {

                        if (param.startsWith("document_id")) {
                            Document document = new Document();
                            document.setEdition(param.split("=")[1]);
                            documentList.getDoc().add(document);
                        }
                    }
                }
            } else if (httpServletRequest.getParameter("document_id") != null
                    && !httpServletRequest.getParameter("document_id").equals("")) {

                Document document = new Document();
                document.setEdition(httpServletRequest.getParameter("document_id"));

                if (httpServletRequest.getParameter("storage_id") != null
                        && !httpServletRequest.getParameter("storage_id").equals("")) {

                    document.setStorage_id(httpServletRequest.getParameter("storage_id"));
                }

                documentList = new DocumentList();
                documentList.setDoc(new ArrayList<Document>());
                documentList.getDoc().add(document);
            } else {

                // if exists cookie with name "PaiaServiceDocumentList": read it
                Cookie[] cookies = httpServletRequest.getCookies();

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("PaiaServiceDocumentList")) {

                            if (cookie.getValue() != null && !cookie.getValue().equals("")
                                    && !cookie.getValue().equals("null")) {

                                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                                this.logger.info(value);
                                documentList = mapper.readValue(value, DocumentList.class);
                            }

                            break;
                        }
                    }
                }
            }
        }

        if (patronid.equals("")) {

            // Authorization
            this.authorize(httpServletRequest, httpServletResponse, format, documentList);
        } else {

            redirect_url = "";

            if (httpServletRequest.getParameter("redirect_url") != null
                    && !httpServletRequest.getParameter("redirect_url").equals("")) {

                redirect_url = httpServletRequest.getParameter("redirect_url");
            }

            this.logger.info("redirect_url = " + redirect_url);

            language = "";

            // PAIA core - function
            if ((httpServletRequest.getMethod().equals("GET")
                    && (service.equals("patron") || service.equals("fullpatron") || service.equals("items")
                            || service.startsWith("items/ordered") || service.startsWith("items/reserved")
                            || service.startsWith("items/borrowed") || service.startsWith("items/borrowed/ill")
                            || service.startsWith("items/borrowed/renewed")
                            || service.startsWith("items/borrowed/recalled") || service.equals("fees")
                            || service.equals("request")))
                    || (httpServletRequest.getMethod().equals("POST") && (service.equals("request")
                            || service.equals("renew") || service.equals("cancel")))) {

                // get 'Accept' and 'Authorization' from Header
                Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
                while (headerNames.hasMoreElements()) {

                    String headerNameKey = (String) headerNames.nextElement();
                    this.logger.debug(
                            "[" + config.getProperty("service.name") + "] " + "headerNameKey = " + headerNameKey
                                    + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey));

                    if (headerNameKey.equals("Accept-Language")) {
                        language = httpServletRequest.getHeader(headerNameKey);
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "Accept-Language: "
                                + language);
                    }
                    if (headerNameKey.equals("Accept")) {
                        accept = httpServletRequest.getHeader(headerNameKey);
                        this.logger
                                .debug("[" + config.getProperty("service.name") + "] " + "Accept: " + accept);
                    }
                    if (headerNameKey.equals("Authorization")) {
                        authorization = httpServletRequest.getHeader(headerNameKey);
                    }
                }

                // language
                if (language.startsWith("de")) {
                    language = "de";
                } else if (language.startsWith("en")) {
                    language = "en";
                } else if (httpServletRequest.getParameter("l") != null) {
                    language = httpServletRequest.getParameter("l");
                } else {
                    language = "de";
                }

                // if not exists token: read request parameter
                if ((authorization == null || authorization.equals(""))
                        && httpServletRequest.getParameter("access_token") != null
                        && !httpServletRequest.getParameter("access_token").equals("")) {
                    authorization = httpServletRequest.getParameter("access_token");
                }

                // if not exists token
                if (authorization == null || authorization.equals("")) {

                    // if exists PaiaService-Cookie: read content
                    Cookie[] cookies = httpServletRequest.getCookies();

                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if (cookie.getName().equals("PaiaService")) {

                                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                                this.logger.info(value);
                                LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                                // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount)
                                if (loginResponse.getPatron().equals(patronid)) {
                                    authorization = loginResponse.getAccess_token();
                                }

                                break;
                            }
                        }

                        // if not exists token - search for Shibboleth-Token
                        if (authorization == null || authorization.equals("")) {

                            if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                                AuthorizationInterface authorizationInterface = Lookup
                                        .lookup(AuthorizationInterface.class);
                                // init Authorization Service
                                authorizationInterface.init(this.config);

                                try {

                                    authorization = authorizationInterface.getAuthCookies(cookies);
                                } catch (AuthorizationException e) {

                                    // TODO correct error handling
                                    this.logger.error("[" + config.getProperty("service.name") + "] "
                                            + HttpServletResponse.SC_UNAUTHORIZED + "!");
                                }

                                this.logger.debug("[" + config.getProperty("service.name") + "] "
                                        + "Authorization: " + authorization);
                            }
                        }
                    }
                }

                httpServletResponse.setHeader("Access-Control-Allow-Origin",
                        config.getProperty("Access-Control-Allow-Origin"));
                httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

                // check token ...
                boolean isAuthorized = false;

                if (authorization != null && !authorization.equals("")) {

                    if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                        AuthorizationInterface authorizationInterface = Lookup
                                .lookup(AuthorizationInterface.class);
                        // init Authorization Service
                        authorizationInterface.init(this.config);

                        try {

                            isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service,
                                    patronid, authorization);
                        } catch (AuthorizationException e) {

                            // TODO correct error handling
                            this.logger.error("[" + config.getProperty("service.name") + "] "
                                    + HttpServletResponse.SC_UNAUTHORIZED + "!");
                        }
                    } else {

                        // TODO correct error handling
                        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                                + "Authorization Interface not implemented!");
                    }
                }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                        + authorization + " - " + isAuthorized);

                if (isAuthorized) {

                    // execute query
                    this.provideService(httpServletRequest, httpServletResponse, patronid, service, format,
                            language, redirect_url, documentList);
                } else {

                    // Authorization
                    this.authorize(httpServletRequest, httpServletResponse, format, documentList);
                }
            } else {

                this.logger.error("[" + config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + httpServletRequest.getMethod()
                        + " for '" + service + "' not allowed!");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                }

                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
                requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        }
    }
}

From source file:de.innovationgate.wgpublisher.WGPRequestPath.java

private void handleLoginFailure(HttpServletRequest request, HttpServletResponse response,
        WGPDispatcher dispatcher)/* w w  w .ja  va  2 s .  co  m*/
        throws HttpErrorException, IOException, UnsupportedEncodingException, WGException {

    // Look if there is a login for that domain. If so, user has no
    // access to this db
    if (!this.core.allowLoginRetry(database, request.getSession())) {
        throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                "You have no access to application '" + getDatabaseKey() + "'", getDatabaseKey());
    }

    // Try to login, if no login for this domain
    String dbAttribHttpLogin = (String) database.getAttribute(WGACore.DBATTRIB_HTTPLOGIN);
    if (dbAttribHttpLogin == null) {
        dbAttribHttpLogin = "false";
    }

    // Try to determine media key from URL, to see if we should do HTTP Login. This will only work with standard URLs.
    if (this.pathElements.size() >= 2) {
        readMediaKey(core, this.pathElements, 1);
        if (mediaKey != null && mediaKey.isHttpLogin() || dbAttribHttpLogin.equals("true")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate",
                    "Basic realm=\"" + database.getAttribute(WGACore.DBATTRIB_DOMAIN) + "\"");
            return;
        }
    } else if (dbAttribHttpLogin.equals("true")) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader("WWW-Authenticate",
                "Basic realm=\"" + database.getAttribute(WGACore.DBATTRIB_DOMAIN) + "\"");
        return;
    }

    // Redirect to login facility
    if (request.getParameter("$ajaxInfo") == null) {
        dispatcher.sendRedirect(request, response, dispatcher.getLoginURL(request, database, getCompleteURL()));
    } else {
        // this is an ajax call without login information - redirect to jsp and fire event LoginRequired
        String loginRequiredEvent = de.innovationgate.wgpublisher.webtml.portlet.PortletEvent.LOGIN_REQUIRED_EVENT
                .toJavaScriptObject();
        String encodedEvent = Base64.encodeWeb(loginRequiredEvent.getBytes());
        dispatcher.sendRedirect(request, response,
                this.publisherURL + "/fireSystemEvent.jsp?event=" + encodedEvent);
    }
}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * Handles the special WebDAV methods.// w  ww. j  a va2s .  com
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //showRequestInfo(req);
    //Set the encoding scheme to be used
    try {
        req.setCharacterEncoding("UTF-8");
    } catch (Exception e) {
        if (System.getProperty("DEBUG") != null) {
            System.out.println("WebdavServlet-> Unsupported encoding");
        }
    }

    ActionContext context = new ActionContext(this, req, resp);
    if (!systemInitialized(context)) {
        // initialize the SystemStatus, WebdavManager and ConnectionElement for this server
        initializeSystem(context);
    }
    // Authentication Check
    String argHeader = req.getHeader("Authorization");
    if (!allowUser(context, argHeader)) {
        System.out.println("Unauthorized access");
        if (context.getRequest().getHeader("user-agent").toLowerCase().startsWith("microsoft")
                || context.getRequest().getHeader("user-agent").toLowerCase().indexOf("windows") > -1) {
            //Microsoft Client. Hence use Basic Authentication
            //Basic Authentication
            //System.out.println("Authentication Scheme-> BASIC");
            resp.setHeader("WWW-Authenticate", "BASIC realm=\"" + CFS_USER_REALM + "\"");
        } else {
            //Any othe client use Digest Authentication
            // Digest Authentication
            // determine the 'number once' value that is unique for this auth
            //System.out.println("Authentication Scheme-> DIGEST");
            String nonce = generateNonce();
            // determine the 'opaque' value which should be returned as is by the client
            String opaque = generateOpaque();
            resp.setHeader("WWW-Authenticate", "Digest realm=\"" + CFS_USER_REALM + "\", " + "nonce=\"" + nonce
                    + "\", " + "opaque=\"" + opaque + "\"");
        }
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    //Fix for MACOSX finder. Do not allow requests for files starting with a period
    String path = getRelativePath(context.getRequest());
    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        return;
    }

    String method = req.getMethod();
    //System.out.println("METHOD: " + method + ", Path: " + path);
    if (method.equals(METHOD_PROPFIND)) {
        doPropfind(context);
    } else if (method.equals(METHOD_OPTIONS)) {
        doOptions(context);
    } else if (method.equals(METHOD_PROPPATCH)) {
        doProppatch(req, resp);
    } else if (method.equals(METHOD_MKCOL)) {
        doMkcol(context);
    } else if (method.equals(METHOD_COPY)) {
        doCopy(context);
    } else if (method.equals(METHOD_MOVE)) {
        doMove(context);
    } else if (method.equals(METHOD_LOCK)) {
        doLock(context);
    } else if (method.equals(METHOD_UNLOCK)) {
        doUnlock(context);
    } else if (method.equals(METHOD_DELETE)) {
        doDelete(context);
    } else {
        // DefaultServlet processing
        super.service(req, resp);
    }
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    ZimbraLog.clearContext();/*www. j  av  a2 s.  c  om*/
    addRemoteIpToLoggingContext(req);

    String fmt = req.getParameter(ContentServlet.PARAM_FORMAT);

    ZimbraLog.addUserAgentToContext(req.getHeader("User-Agent"));

    // file upload requires authentication
    boolean isAdminRequest = false;
    try {
        isAdminRequest = isAdminRequest(req);
    } catch (ServiceException e) {
        drainRequestStream(req);
        throw new ServletException(e);
    }

    AuthToken at = isAdminRequest ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (at == null) {
        mLog.info("Auth token not present.  Returning %d response.", HttpServletResponse.SC_UNAUTHORIZED);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, null);
        return;
    }

    boolean doCsrfCheck = false;
    boolean csrfCheckComplete = false;
    if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) {
        doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK);
    }

    if (doCsrfCheck) {
        String csrfToken = req.getHeader(Constants.CSRF_TOKEN);

        // Bug: 96344
        if (!StringUtil.isNullOrEmpty(csrfToken)) {
            if (!CsrfUtil.isValidCsrfToken(csrfToken, at)) {

                drainRequestStream(req);
                mLog.info("CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s"
                        + ". CSRF token is: %s", at, at.isCsrfTokenEnabled(), csrfToken);
                sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, null);
                return;
            }
            csrfCheckComplete = true;
        } else {
            if (at.isCsrfTokenEnabled()) {
                csrfCheckComplete = false;
                mLog.debug(
                        "CSRF token was not found in the header. Auth token is %s, it is CSRF enabled:  %s, will check if sent in"
                                + " form field.",
                        at, at.isCsrfTokenEnabled());
            }
        }
    } else {
        csrfCheckComplete = true;
    }

    try {
        Provisioning prov = Provisioning.getInstance();
        Account acct = AuthProvider.validateAuthToken(prov, at, true);
        if (!isAdminRequest) {
            // fetching the mailbox will except if it's in maintenance mode
            if (Provisioning.onLocalServer(acct)) {
                Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(acct, false);
                if (mbox != null) {
                    ZimbraLog.addMboxToContext(mbox.getId());
                }
            }
        }

        boolean limitByFileUploadMaxSize = req.getParameter(PARAM_LIMIT_BY_FILE_UPLOAD_MAX_SIZE) != null;

        // file upload requires multipart enctype
        if (ServletFileUpload.isMultipartContent(req)) {
            handleMultipartUpload(req, resp, fmt, acct, limitByFileUploadMaxSize, at, csrfCheckComplete);
        } else {
            if (!csrfCheckComplete) {
                drainRequestStream(req);
                mLog.info("CSRF token validation failed for account: %s.No csrf token recd.", acct);
                sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, null);
            } else {
                handlePlainUpload(req, resp, fmt, acct, limitByFileUploadMaxSize);
            }
        }
    } catch (ServiceException e) {
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        returnError(resp, e);
    }
}