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:com.hyeb.back.authenticate.AuthenticationFilter.java

@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse)
        throws Exception {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "accessDenied");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }//w  w w.jav  a  2  s  .  co  m
    return super.onAccessDenied(request, response);
}

From source file:jp.co.opentone.bsol.framework.web.filter.FeedAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    AuthUser u = authenticate(req, res);
    if (u == null) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from w ww. j  a v a2  s .  co  m*/
    }
    storeAuthenticateUser(req, res, u);
    chain.doFilter(request, response);
}

From source file:com.thinkberg.webdav.CopyMoveBase.java

/**
 * Handle a COPY or MOVE request.//w w  w.  j  a  v  a  2s  .  c o m
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error executing this request
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean overwrite = getOverwrite(request);
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());
    FileObject targetObject = getDestination(request);

    try {
        final LockManager lockManager = LockManager.getInstance();
        LockManager.EvaluationResult evaluation = lockManager.evaluateCondition(targetObject, getIf(request));
        if (!evaluation.result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        if ("MOVE".equals(request.getMethod())) {
            evaluation = lockManager.evaluateCondition(object, getIf(request));
            if (!evaluation.result) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return;
            }
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (null == targetObject) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    // delegate the actual execution to a sub class
    copyOrMove(object, targetObject, getDepth(request));
}

From source file:com.mirth.connect.server.servlets.UserServlet.java

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

    UserController userController = ControllerFactory.getFactory().createUserController();
    EventController eventController = ControllerFactory.getFactory().createEventController();
    PrintWriter out = response.getWriter();
    Operation operation = Operations.getOperation(request.getParameter("op"));
    ObjectXMLSerializer serializer = new ObjectXMLSerializer();

    if (operation.equals(Operations.USER_LOGIN)) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String version = request.getParameter("version");
        response.setContentType(TEXT_PLAIN);
        serializer.toXML(login(request, response, userController, eventController, username, password, version),
                out);/*from w ww. j  a va 2  s .com*/
    } else if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {
        try {
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (operation.equals(Operations.USER_LOGOUT)) {
                // Audit the logout request but don't block it
                isUserAuthorized(request, null);

                logout(request, userController, eventController);
            } else if (operation.equals(Operations.USER_GET)) {
                /*
                 * If the requesting user does not have permission, only
                 * return themselves.
                 */
                response.setContentType(APPLICATION_XML);
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                if (!isUserAuthorized(request, parameterMap)) {
                    user = new User();
                    user.setId(getCurrentUserId(request));
                }

                serializer.toXML(userController.getUser(user), out);
            } else if (operation.equals(Operations.USER_UPDATE)) {
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                if (isUserAuthorized(request, parameterMap) || isCurrentUser(request, user)) {
                    userController.updateUser(user);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.USER_CHECK_OR_UPDATE_PASSWORD)) {
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                if (isUserAuthorized(request, parameterMap) || isCurrentUser(request, user)) {
                    String plainPassword = request.getParameter("plainPassword");
                    serializer.toXML(userController.checkOrUpdateUserPassword(user.getId(), plainPassword),
                            out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.USER_REMOVE)) {
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                if (isUserAuthorized(request, parameterMap)) {
                    // Try to remove the user and then invalidate the
                    // session if it succeeded
                    userController.removeUser(user, (Integer) request.getSession().getAttribute(SESSION_USER));
                    UserSessionCache.getInstance().invalidateAllSessionsForUser(user);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.USER_IS_USER_LOGGED_IN)) {
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                if (isUserAuthorized(request, parameterMap)) {
                    response.setContentType(TEXT_PLAIN);
                    out.print(userController.isUserLoggedIn(user));
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.USER_PREFERENCES_GET)) {
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                // Allow if the user is requesting his own preferences.
                // Check this first so a current user call is not audited.
                if (isCurrentUser(request, user) || isUserAuthorized(request, parameterMap)) {
                    response.setContentType(TEXT_PLAIN);
                    serializer.toXML(userController.getUserPreferences(user), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.USER_PREFERENCES_SET)) {
                User user = (User) serializer.fromXML(request.getParameter("user"));
                parameterMap.put("user", user);

                // Allow if the user is setting his own preferences. Check
                // this first so a current user call is not audited.
                if (isCurrentUser(request, user) || isUserAuthorized(request, parameterMap)) {
                    String name = request.getParameter("name");
                    String value = request.getParameter("value");
                    userController.setUserPreference(user, name, value);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:de.mpg.escidoc.services.aa.web.client.BasicAaClient.java

private boolean testLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String auth = request.getHeader("authorization");
    if (auth == null) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"Validation Service\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } else {/*w  ww. j  a v  a  2  s  . com*/
        auth = auth.substring(6);
        String cred = new String(Base64.decodeBase64(auth.getBytes()));
        if (cred.contains(":")) {

            String[] userPass = cred.split(":");
            String userName = "admin";
            String password = "nimda";

            if (!userPass[0].equals(userName) || !userPass[1].equals(password)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            } else {
                return true;
            }
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }
}

From source file:com.haulmont.ext.core.app.restapi.CreateCallfromOktell.java

@RequestMapping(method = RequestMethod.GET, value = "/task/call")
public void getTaskStates(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "p") String phone) throws IOException, JSONException {
    Authentication authentication = Authentication.me(sessionId);
    if (authentication == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/* w  ww .jav  a2  s. c  o m*/
    }
    try {

        Call call = new Call();

        call.setName("? :" + phone);

        LoadContext catctx = new LoadContext(Category.class);
        catctx.setQueryString("select t from sys$Category t where t.id = :uuid").addParameter("uuid",
                UUID.fromString("053ae7ee-d327-4a90-909a-f540e4357324"));
        DataService catService = Locator.lookup(DataService.NAME);
        Category cat = catService.load(catctx);
        call.setCategory(cat);

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String stringDate = formatter.format(TimeProvider.currentTimestamp());
        call.setCallDescription("?  ? : " + stringDate);

        Priority priority = findPriorityByOrder(3);
        call.setPriority(priority);
        call.setNumber(callGNS.getNextNumber(call));

        LoadContext procctx = new LoadContext(Proc.class);
        procctx.setQueryString("select p from wf$Proc p where p.name =:name").addParameter("name",
                " ");
        procctx.setView("edit");
        DataService procService = Locator.lookup(DataService.NAME);
        Proc proc = procService.load(procctx);
        call.setProc(proc);

        String roleInitiator = "oktell";
        String roleExecutor = "office_manager";

        String initiator = findUserByRole(roleInitiator).getLogin();
        String executor = findUserByRole(roleExecutor).getLogin();

        if (call.getRoles() == null) {
            call.setRoles(new ArrayList<CardRole>());
        }

        for (ProcRole procRole : proc.getRoles()) {
            if ((roleInitiator).equals(procRole.getCode()) && initiator != null) {
                updateCardRole(procRole, call, initiator);
            } else if ((roleExecutor).equals(procRole.getCode()) && executor != null)
                updateCardRole(procRole, call, executor);
        }

        Set<Entity> toCommit = new HashSet<Entity>();

        MetaClass metaClass = call.getMetaClass();
        for (MetaProperty metaProperty : metaClass.getProperties()) {
            Object value = call.getValue(metaProperty.getName());
            if (value instanceof List) {
                for (Object entity : ((List) value))
                    toCommit.add((Entity) entity);
            }
        }

        LoadContext extClt = new LoadContext(ExtClient.class);
        extClt.setQueryString("select c from ext$Client c where c.numberTel = :phone").addParameter("phone",
                phone);
        extClt.setView("_local");
        DataService dataServiceClt = Locator.lookup(DataService.NAME);
        ExtClient extClient = dataServiceClt.load(extClt);

        if (extClient != null) {
            call.setExtClient(extClient);
            call.setTelephoneNumber(extClient.getNumberTel());
            call.setCallDescription("?  ? : " + stringDate
                    + "  " + extClient.getName());
        }
        call.setTelephoneNumber(phone);

        //List<CardRole> roleList = call.getRoles().get(0).getProcRole().;

        toCommit.add(call);
        dataService.commit(new CommitContext(toCommit));

        wfService.startProcess(call);

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = new PrintWriter(response.getOutputStream());
        JSONObject responseJson = new JSONObject();
        responseJson.put("id", call.getId());
        writer.write(responseJson.toString());
        writer.close();

    } finally {
        authentication.forget();
    }
}

From source file:com.phil.web.security.authorization.AccessDeniedHandlerImpl.java

public void handle(ServletRequest request, ServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    if (errorPage != null) {
        // Put exception into request scope (perhaps of use to a view)
        ((HttpServletRequest) request).setAttribute(SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY,
                accessDeniedException);/* w w w .j  a v a2s. c om*/

        ((HttpServletResponse) response).sendRedirect(errorPage);
    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                accessDeniedException.getMessage());
    }
}

From source file:com.esri.gpt.framework.http.crawl.HttpCrawlRequest.java

private void adviseRobotsTxt() throws IOException {
    if (bots != null) {
        String url = getRelativePath();
        LOG.fine(String.format("Evaluating access to %s using robots.txt", getUrl()));
        Access access = requestAccess(bots, url);
        if (!access.hasAccess()) {
            LOG.info(String.format("Access to %s disallowed by robots.txt", getUrl()));
            throw new HttpClientException(HttpServletResponse.SC_FORBIDDEN,
                    String.format("Access to %s disallowed by robots.txt", getUrl()));
        }//from  w w w . ja v  a  2s .c o  m
        LOG.fine(String.format("Access to %s allowed by robots.txt", getUrl()));
        CrawlLocker.getInstance().enterServer(getProtocolHostPort(), resolveThrottleDelay(bots));
    }
}

From source file:se.skltp.cooperation.web.rest.v1.filter.AccessControlFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

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

    log.debug("AccessControl is " + accesscontrol + request.getParameter(API_KEY) + " header: "
            + request.getHeader(API_KEY));

    if (accesscontrol) {
        if (request.getRequestURI().contains("/v1/")) {
            if (!api_key.equals(request.getHeader(API_KEY))) {
                if (!api_key.equals(request.getParameter(API_KEY))) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Nonexisting or invalid API key");
                    return;
                }/*from  www  . j  ava 2 s  .c  om*/
            }
        }
    }

    chain.doFilter(request, res);
}

From source file:org.mitre.openid.connect.filter.PromptFilter.java

/**
 * //from   ww w  .ja  v a2  s .  c o m
 */
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

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

    if (!Strings.isNullOrEmpty(request.getParameter("prompt"))) {
        // we have a "prompt" parameter

        if (request.getParameter("prompt").equals("none")) {
            logger.info("Client requested no prompt");
            // see if the user's logged in
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();

            if (auth != null) {
                // user's been logged in already (by session management)
                // we're OK, continue without prompting
                chain.doFilter(req, res);
            } else {
                // user hasn't been logged in, we need to "return an error"
                logger.info("User not logged in, no prompt requested, returning 403 from filter");
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                return;
            }
        } else if (request.getParameter("prompt").equals("login")) {

            // first see if the user's already been prompted in this session
            HttpSession session = request.getSession();
            if (session.getAttribute(PROMPTED) == null) {
                // user hasn't been PROMPTED yet, we need to check             

                session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE);

                // see if the user's logged in
                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                if (auth != null) {
                    // user's been logged in already (by session management)
                    // log them out and continue
                    SecurityContextHolder.getContext().setAuthentication(null);
                    chain.doFilter(req, res);
                } else {
                    // user hasn't been logged in yet, we can keep going since we'll get there
                    chain.doFilter(req, res);
                }
            } else {
                // user has been PROMPTED, we're fine

                // but first, undo the prompt tag
                session.removeAttribute(PROMPTED);
                chain.doFilter(req, res);
            }
        } else {
            // prompt parameter is a value we don't care about, not our business
            chain.doFilter(req, res);
        }

    } else if (!Strings.isNullOrEmpty(request.getParameter("max_age"))) {
        // TODO: issue #450
        String maxAge = request.getParameter("max_age");
        HttpSession session = request.getSession();
        Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);

        Date now = new Date();
        if (authTime != null) {
            Integer max = Integer.parseInt(maxAge);
            long seconds = (now.getTime() - authTime.getTime()) / 1000;
            if (seconds > max) {
                // session is too old, log the user out and continue
                SecurityContextHolder.getContext().setAuthentication(null);
            }
        }

        chain.doFilter(req, res);
    } else {
        // no prompt parameter, not our business
        chain.doFilter(req, res);
    }

}