Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

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

Introduction

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

Prototype

int SC_FORBIDDEN

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

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:org.ovirt.engine.api.common.security.CSRFProtectionFilter.java

private void doFilterExistingSession(HttpSession session, HttpServletRequest request,
        HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    // Check if the protection is enabled for this session, if it isn't then jump to the next filter:
    boolean enabled = (Boolean) session.getAttribute(ENABLED_ATTRIBUTE);
    if (!enabled) {
        chain.doFilter(request, response);
        return;//from   ww  w  .j a  va  2  s  .  co m
    }

    // Check if the request contains a session id header, if it doesn't then it must be rejected immediately:
    String sessionIdHeader = request.getHeader(SESSION_ID_HEADER);
    if (sessionIdHeader == null) {
        log.warn(
                "Request for path \"{}\" from IP address {} has been rejected because CSRF protection is enabled "
                        + "for the session but the the session id header \"{}\" hasn't been provided.",
                request.getContextPath() + request.getPathInfo(), request.getRemoteAddr(), SESSION_ID_HEADER);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Check if the actual session id matches the session id header:
    String actualSessionId = session.getId();
    if (!sessionIdHeader.equals(actualSessionId)) {
        log.warn(
                "Request for path \"{}\" from IP address {} has been rejected because CSRF protection is enabled "
                        + "for the session but the value of the session id header \"{}\" doesn't match the actual session "
                        + "id.",
                request.getContextPath() + request.getPathInfo(), request.getRemoteAddr(), SESSION_ID_HEADER);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Everything is OK, let the request go to the next filter:
    chain.doFilter(request, response);
}

From source file:org.jboss.as.test.manualmode.web.ssl.AbstractCertificateLoginModuleTestCase.java

/**
 * Testing access to HTTPS connector which have configured truststore with
 * trusted certificates. Client with trusted certificate is allowed to
 * access both secured/unsecured resource. Client with untrusted certificate
 * can only access unprotected resources.
 *
 * @throws Exception//from ww w . jav  a  2  s  .c o m
 */
public void testLoginWithCertificate(String appName) throws Exception {

    Assume.assumeFalse(
            SystemUtils.IS_JAVA_1_6 && SystemUtils.JAVA_VENDOR.toUpperCase(Locale.ENGLISH).contains("IBM"));

    final URL printPrincipalUrl = getServletUrl(HTTPS_PORT, appName, PrincipalPrintingServlet.SERVLET_PATH);
    final URL securedUrl = getServletUrl(HTTPS_PORT, appName, SECURED_SERVLET_WITH_SESSION);
    final URL unsecuredUrl = getServletUrl(HTTPS_PORT, appName, SimpleServlet.SERVLET_PATH);

    final HttpClient httpClient = getHttpsClient(CLIENT_KEYSTORE_FILE);
    final HttpClient httpClientUntrusted = getHttpsClient(UNTRUSTED_KEYSTORE_FILE);

    try {
        makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_FORBIDDEN);

        String responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK);
        assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody);

        String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK);
        assertEquals("Unexpected principal", "cn=client", principal.toLowerCase());

        responseBody = makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_OK);
        assertEquals("Secured page was not reached", SimpleServlet.RESPONSE_BODY, responseBody);

        try {
            makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN);
        } catch (SSLHandshakeException e) {
            // OK
        } catch (java.net.SocketException se) {
            // OK - on windows usually fails with this one
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
        httpClientUntrusted.getConnectionManager().shutdown();
    }
}

From source file:com.google.gerrit.httpd.auth.oauth.OAuthSession.java

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp, OAuthToken token)
        throws IOException {
    AuthRequest areq = new AuthRequest(ExternalId.Key.parse(user.getExternalId()));
    AuthResult arsp;/*from  ww  w.ja  v a 2s.c o  m*/
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            if (!authenticateWithIdentityClaimedDuringHandshake(areq, rsp, claimedIdentifier)) {
                return;
            }
        } else if (linkMode) {
            if (!authenticateWithLinkedIdentity(areq, rsp)) {
                return;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);

        accountId = arsp.getAccountId();
        tokenCache.put(accountId, token);
    } catch (AccountException e) {
        log.error("Unable to authenticate user \"" + user + "\"", e);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    webSession.get().login(arsp, true);
    String suffix = redirectToken.substring(OAuthWebFilter.GERRIT_LOGIN.length() + 1);
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(Url.decode(suffix));
    rsp.sendRedirect(rdr.toString());
}

From source file:com.evolveum.midpoint.gui.impl.util.ReportPeerQueryInterceptor.java

private boolean isFileAndExists(File reportFile, String fileName, HttpServletResponse response,
        String operation) throws IOException {

    if (!reportFile.exists()) {
        LOGGER.warn(operation + " not successful. The file: {} was not found on the filesystem.", fileName);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return false;
    }/*from w  w  w  .  j a  v a  2 s  . c  om*/

    if (reportFile.isDirectory()) {
        LOGGER.warn(operation
                + " not successful. The file is actually a directory with the name: {}. This operation is prohibited.",
                fileName);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }

    return true;

}

From source file:net.big_oh.common.web.filters.ipaddress.IPAddressFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (response instanceof HttpServletResponse) {

        HttpServletResponse resp = (HttpServletResponse) response;

        // check white list rules
        for (IPAddressWhiteListFilterRule whiteListRule : whiteListRules) {
            if (whiteListRule.doesRequestingAddressMatchRule(InetAddress.getByName(request.getRemoteAddr()))) {
                logger.info("Request from " + request.getRemoteAddr()
                        + " permitted because of matching white list rule (" + whiteListRule.toString() + ").");
                chain.doFilter(request, response);
                return;
            }/*from  w  w  w.ja  va 2  s.co  m*/
        }

        // check blacklist rules
        for (IPAddressBlackListFilterRule blackListRule : blackListRules) {
            if (blackListRule.doesRequestingAddressMatchRule(InetAddress.getByName(request.getRemoteAddr()))) {
                logger.info("Request from " + request.getRemoteAddr()
                        + " rejected because of matching black list rule (" + blackListRule.toString() + ").");
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        logger.info(
                "Request from " + request.getRemoteAddr() + " permitted because no matching rules were found.");
        chain.doFilter(request, response);
        return;

    } else {
        logger.info("Encountered a non-HTTP request.  Processing normally.");
        chain.doFilter(request, response);
        return;
    }

}

From source file:com.adito.core.actions.AuthenticatedDispatchAction.java

/**
 * This abstract class will populate all the common variables required by an
 * action within the webstudio framework, such as current user, permission
 * database, user database etc//  w w w  .j  av  a 2  s  .  c  om
 * 
 * @param mapping
 * @param form
 * @param request
 * @param response
 * 
 * @exception Exception if business logic throws an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // Setup mode
    boolean setupMode = ContextHolder.getContext().isSetupMode();
    if (setupMode) {
        if ((getNavigationContext(mapping, form, request, response) & SessionInfo.SETUP_CONSOLE_CONTEXT) == 0) {
            return mapping.findForward("setup");
        } else {
            /*
             * Make the mapping and form available, this helps with reusing
             * some JSP pages
             */
            request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
            request.setAttribute(Constants.REQ_ATTR_FORM, form);

            //
            CoreUtil.checkNavigationContext(this, mapping, form, request, response);
            return super.execute(mapping, form, request, response);
        }
    }
    try {
        try {
            if (!SystemDatabaseFactory.getInstance().verifyIPAddress(request.getRemoteAddr())) {
                String link = null;
                log.error(request.getRemoteHost() + " is not authorized");
                if (log.isInfoEnabled())
                    log.info("Logging off, IP address verification failed.");

                if (LogonControllerFactory.getInstance().hasClientLoggedOn(request,
                        response) == LogonController.LOGGED_ON) {
                    LogonControllerFactory.getInstance().logoffSession(request, response);
                }

                if (link != null) {
                    ActionForward fwd = new ActionForward(link, true);
                    return fwd;
                } else {
                    // Do not direct to logon page for Ajax requests
                    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
                    return (mapping.findForward("logon"));
                }
            } else {
                /*
                 * Make the mapping and form available, this helps with
                 * reusing some JSP pages
                 */
                request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
                request.setAttribute(Constants.REQ_ATTR_FORM, form);

                int logonStatus = LogonControllerFactory.getInstance().hasClientLoggedOn(request, response);
                if (logonStatus == LogonController.INVALID_TICKET) {
                    ActionMessages msgs = new ActionMessages();
                    msgs.add(Globals.ERROR_KEY, new ActionMessage("login.invalidTicket"));
                    saveErrors(request, msgs);
                } else if (logonStatus == LogonController.LOGGED_ON) {
                    SessionInfo session = LogonControllerFactory.getInstance().getSessionInfo(request);
                    // Set the logon ticket / domain logon ticket again
                    LogonControllerFactory.getInstance().addCookies(new ServletRequestAdapter(request),
                            new ServletResponseAdapter(response),
                            (String) request.getSession().getAttribute(Constants.LOGON_TICKET),
                            getSessionInfo(request));

                    ActionForward fwd = checkIntercept(mapping, request, response);
                    if (fwd != null) {
                        return fwd;
                    }

                    /*
                     * Make sure the current navigation context is correct.
                     * If not, then check the user can switch to the correct
                     * and switch it.
                     */
                    CoreUtil.checkNavigationContext(this, mapping, form, request, response);

                    PropertyProfile profile = null;
                    if (request.getSession().getAttribute(Constants.SESSION_LOCKED) == null) {
                        profile = (PropertyProfile) request.getSession()
                                .getAttribute(Constants.SELECTED_PROFILE);
                        if (profile == null) {
                            request.getSession().setAttribute(Constants.ORIGINAL_REQUEST,
                                    Util.getOriginalRequest(request));
                            return mapping.findForward("selectPropertyProfile");
                        }
                        doCheckPermissions(mapping, session, request);
                        return super.execute(mapping, form, request, response);
                    }
                }
            }
        } catch (NoPermissionException e) {
            if (log.isDebugEnabled())
                log.debug("User " + e.getPrincipalName()
                        + " attempted to access page they do have have permission for. Resource type = "
                        + e.getResourceType()
                        + ". Now attempting to find the first valid item in the current menu tree to display.",
                        e);
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (SecurityException ex) {
            // Not logged in or expired
        } catch (ServletException ex) {
            throw ex;
        }

        // Do not direct to logon page for Ajax requests
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        }

        return gotoLogon(mapping, form, request, response);
    } catch (Throwable t) {
        log.error("Failed to process authenticated request.", t);
        throw t instanceof Exception ? (Exception) t : new Exception(t);
    }
}

From source file:gov.nih.nci.nbia.servlet.DownloadServletV2.java

private void sendAccessDenial(HttpServletResponse response) throws IOException {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTUser.java

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {/*from   www. jav a 2s.co m*/
        WSUserSearchCriteria c = restUtils.getWSUserSearchCriteria(getUserSearchInformation(req.getPathInfo()));

        WSUser userToDelete = new WSUser();
        userToDelete.setUsername(c.getName());
        userToDelete.setTenantId(c.getTenantId());

        if (isLoggedInUser(restUtils.getCurrentlyLoggedUser(), userToDelete)) {
            throw new ServiceException(HttpServletResponse.SC_FORBIDDEN,
                    "user: " + userToDelete.getUsername() + " can not to delete himself");
        } else if (validateUserForGetOrDelete(userToDelete)) {
            if (isAlreadyAUser(userToDelete)) {
                userAndRoleManagementService.deleteUser(userToDelete);
            } else {
                throw new ServiceException(HttpServletResponse.SC_NOT_FOUND,
                        "user: " + userToDelete.getUsername() + " was not found");
            }
        } else {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters");
        }
        if (log.isDebugEnabled()) {
            log.debug(userToDelete.getUsername() + " was deleted");
        }

        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }
}

From source file:com.adito.core.actions.AuthenticatedAction.java

public final ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // Setup mode
    boolean installMode = isInstallMode();
    if (installMode) {
        if ((getNavigationContext(mapping, form, request, response) & SessionInfo.SETUP_CONSOLE_CONTEXT) == 0) {
            return mapping.findForward("setup");
        } else {//from  w  w w . j a v a 2s  . c o  m
            /*
             * Make the mapping and form available, this helps with reusing
             * some JSP pages
             */
            request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
            request.setAttribute(Constants.REQ_ATTR_FORM, form);

            CoreUtil.checkNavigationContext(this, mapping, form, request, response);
            return onExecute(mapping, form, request, response);
        }
    }

    try {
        try {
            if (!SystemDatabaseFactory.getInstance().verifyIPAddress(request.getRemoteAddr())) {
                String link = null;
                log.error(request.getRemoteHost() + " is not authorized");
                if (log.isInfoEnabled())
                    log.info("Logging off, IP address verification failed.");
                if (LogonControllerFactory.getInstance().hasClientLoggedOn(request,
                        response) == LogonController.LOGGED_ON) {
                    LogonControllerFactory.getInstance().logoffSession(request, response);
                }

                if (link != null) {
                    return new ActionForward(link, true);
                } else {
                    // Do not direct to logon page for Ajax requests
                    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
                    return mapping.findForward("logon");
                }

            } else {

                int logonStatus = LogonControllerFactory.getInstance().hasClientLoggedOn(request, response);
                if (logonStatus == LogonController.INVALID_TICKET) {
                    ActionMessages msgs = new ActionMessages();
                    msgs.add(Globals.ERROR_KEY, new ActionMessage("login.invalidTicket"));
                    saveErrors(request, msgs);
                } else if (logonStatus == LogonController.LOGGED_ON) {

                    User currentUser = LogonControllerFactory.getInstance().getUser(request);

                    // Set the logon ticket / domain logon ticket again
                    LogonControllerFactory.getInstance().addCookies(new ServletRequestAdapter(request),
                            new ServletResponseAdapter(response),
                            (String) request.getSession().getAttribute(Constants.LOGON_TICKET),
                            getSessionInfo(request));

                    if (!LogonControllerFactory.getInstance().isAdministrator(getSessionInfo(request).getUser())
                            && requiresAdministrator) {
                        response.sendError(403, "You do not have permission to access this area");
                        return null;
                    } else {
                        /*
                         * Make the mapping and form available, this helps
                         * with reusing some JSP pages
                         */
                        request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
                        request.setAttribute(Constants.REQ_ATTR_FORM, form);

                        // Check for intercepts, but don't forward if the
                        // result of an Ajax action

                        ActionForward fwd = checkIntercept(mapping, request, response);
                        if (fwd != null) {
                            return fwd;
                        }

                        /*
                         * Make sure the current navigation context is
                         * correct. If not, then check the user can switch
                         * to the correct and switch it.
                         */
                        CoreUtil.checkNavigationContext(this, mapping, form, request, response);

                        // Check the user has the permissions to access this
                        // page
                        if (resourceType != null) {
                            if (!PolicyDatabaseFactory.getInstance().isPermitted(resourceType, permissions,
                                    currentUser, false)) {
                                throw new NoPermissionException("Action denied for current user");
                            }
                        }

                        if (request.getSession().getAttribute(Constants.SESSION_LOCKED) == null
                                || isIgnoreSessionLock()) {
                            if (requiresProfile()) {
                                PropertyProfile profile = (PropertyProfile) request.getSession()
                                        .getAttribute(Constants.SELECTED_PROFILE);
                                if (profile == null) {
                                    request.getSession().setAttribute(Constants.ORIGINAL_REQUEST,
                                            Util.getOriginalRequest(request));
                                    return mapping.findForward("selectPropertyProfile");
                                }
                            }
                            return onExecute(mapping, form, request, response);
                        }
                    }
                }
            }
        } catch (NoPermissionException e) {
            if (log.isDebugEnabled())
                log.debug("User attempted to access page they do have have permission for. Resource type = "
                        + resourceType
                        + ". Now attempting to find the first valid item in the current menu tree to display.",
                        e);
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (SecurityException ex) {
            // Not logged in or expired
        } catch (ServletException ex) {
            throw ex;
        }

        // Do not direct to logon page for Ajax requests
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        return gotoLogon(mapping, form, request, response);
    } catch (Throwable t) {
        log.error("Failed to process authenticated request.", t);
        throw t instanceof Exception ? (Exception) t : new Exception(t);
    }
}

From source file:eu.dasish.annotation.backend.rest.CachedRepresentationResource.java

/**
 * /*ww  w  .java2  s  . co  m*/
 * @param externalId the external UUID of a cached representation.
 * @return the image-blob if the cached-representation's blob is an image file.
 * @throws IOException if logging an error fails (should be changed to sending httpResponse error message).
 */
@GET
@Produces({ "image/jpeg", "image/png" })
@Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/content")
@Transactional(readOnly = true)
public BufferedImage getCachedRepresentationContent(@PathParam("cachedid") String externalId)
        throws IOException {
    Map params = new HashMap();
    try {
        InputStream result = (InputStream) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetCachedRepresentationInputStream(), Resource.CACHED_REPRESENTATION, Access.READ,
                externalId);
        if (result != null) {
            ImageIO.setUseCache(false);
            try {
                BufferedImage retVal = ImageIO.read(result);
                return retVal;
            } catch (IOException e1) {
                loggerServer.info(e1.toString());

                return null;
            }
        } else {
            loggerServer.info(" The cached representation with the id " + externalId + " has null blob.");
            return null;
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return null;
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return null;
    }

}