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.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController.java

/**
 * @should return unauthorized if not logged in
 * @should return forbidden if logged in
 *///from w w  w .  j a  v  a2 s.c om
@ExceptionHandler(APIAuthenticationException.class)
@ResponseBody
public SimpleObject apiAuthenticationExceptionHandler(Exception ex, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    int errorCode;
    String errorDetail;
    if (Context.isAuthenticated()) {
        // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN
        errorCode = HttpServletResponse.SC_FORBIDDEN;
        errorDetail = "User is logged in but doesn't have the relevant privilege";
    } else {
        // user is not logged in -> 401 UNAUTHORIZED
        errorCode = HttpServletResponse.SC_UNAUTHORIZED;
        errorDetail = "User is not logged in";
        if (shouldAddWWWAuthHeader(request)) {
            response.addHeader("WWW-Authenticate",
                    "Basic realm=\"OpenMRS at " + RestConstants.URI_PREFIX + "\"");
        }
    }
    response.setStatus(errorCode);
    return RestUtil.wrapErrorResponse(ex, errorDetail);
}

From source file:net.duckling.ddl.web.interceptor.access.VWBDenyListener.java

public void onDeny(HttpServletRequest request, HttpServletResponse response,
        RequirePermission requirePermission) throws IOException {
    VWBSession m_session = VWBSession.findSession(request);
    VWBContainer container = VWBContainerImpl.findContainer();
    Principal currentUser = m_session.getCurrentUser();

    try {/*  w  w  w.j  ava  2  s. co  m*/
        if (m_session.isAuthenticated()) {
            LOGGER.info("User " + currentUser.getName() + " has no access - forbidden (permission="
                    + getRequiredPermission(requirePermission) + ") URL:" + request.getRequestURI());
            response.setHeader("ddl-auth", "Permission dend");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else {
            LOGGER.info("User " + currentUser.getName() + " has no access - redirecting (permission="
                    + getRequiredPermission(requirePermission) + ") URL:" + request.getRequestURI());

            String requesturl = (String) request.getAttribute(Attributes.REQUEST_URL);
            if (requesturl == null) {
                requesturl = getRequestURL(request);
            }
            m_session.setAttribute(Attributes.REQUEST_URL, requesturl);
            m_session.setAttribute(Attributes.TEAM_ID_FOR_JOIN_PUBLIC_TEAM, request.getParameter("teamId"));
            if (isAjaxRequest(request)) {
                response.setStatus(450);
            } else {
                if (isHashURL(requesturl)) {
                    m_session.removeAttribute(Attributes.REQUEST_URL);
                    request.setAttribute("url", UrlUtil.changeSchemeToHttps(
                            container.getURL(UrlPatterns.LOGIN, null, null, false), request));
                    request.getRequestDispatcher("/jsp/aone/hash/dealHashRequest.jsp").forward(request,
                            response);
                } else {
                    String redirect = UrlUtil.changeSchemeToHttps(
                            container.getURL(UrlPatterns.LOGIN, null, null, false), request);
                    response.sendRedirect(redirect);
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("Redirect failed for:" + e.getMessage(), e);
        throw new InternalVWBException(e.getMessage());
    } catch (ServletException e) {
        LOGGER.error("Redirect failed for:" + e.getMessage(), e);
        throw new InternalVWBException(e.getMessage());
    }
}

From source file:edu.chalmers.dat076.moviefinder.filter.UserFilter.java

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
        throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    String path = req.getRequestURI().substring(req.getContextPath().length());

    Object o = session.getAttribute("user");

    if (o == null) {
        if (path.toLowerCase().startsWith("/api/login/login")) {
            chain.doFilter(req, res);/*from  w  ww.jav  a 2s  . com*/
            return;
        } else if (path.toLowerCase().startsWith("/api/")) {
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        } else {
            chain.doFilter(req, res);
            return;
        }
    }

    User u = (User) o;
    if (path.toLowerCase().startsWith("/api/admin") && u.getRole() != UserRole.ADMIN) {
        res.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    chain.doFilter(req, res);
}

From source file:fr.aliasource.webmail.proxy.impl.ResponderImpl.java

public void denyAccess(String cause) {
    logger.warn("Denying access");
    resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
    try {//  w  ww .  jav  a2s .c o  m
        resp.getWriter().println("Access denied: " + cause);
    } catch (IOException e) {
        logger.error("Cannot write response");
    }
}

From source file:grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Spring Security won't save the original request
        requestCache.saveRequest(request, response);
    }//from   w  ww . j  av a  2  s  .co  m

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (useForward && (errorPage != null || ajaxError)) {
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.getRequestDispatcher(ajaxError ? ajaxErrorPage : errorPage).forward(request, response);
        return;
    }

    String redirectUrl;
    String serverURL = ReflectionUtils.getGrailsServerURL();
    if (serverURL == null) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }
        redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    } else {
        redirectUrl = serverURL;
    }

    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!checkRequest(request, response, OPERATION_GET_REPORT)) {
        return;//from  w ww . j  a v a  2  s.c o  m
    }

    String fileName = getFileName(request);

    if (containsProhibitedQueryString(fileName)) {
        LOGGER.debug("Query parameter contains a prohibited character sequence. The parameter: {} ", fileName);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    StringBuilder buildfilePath = new StringBuilder(EXPORT_DIR).append(fileName);
    String filePath = buildfilePath.toString();

    File loadedFile = new File(filePath);

    if (!isFileAndExists(loadedFile, fileName, response, OPERATION_GET_REPORT)) {
        return;
    }

    FileInputStream fileInputStream = new FileInputStream(filePath);

    ServletContext context = getServletContext();
    String mimeType = context.getMimeType(filePath);

    if (mimeType == null) {
        // MIME mapping not found
        mimeType = DEFAULTMIMETYPE;
    }

    response.setContentType(mimeType);
    response.setContentLength((int) loadedFile.length());

    StringBuilder headerValue = new StringBuilder("attachment; filename=\"%s\"").append(fileName);
    response.setHeader("Content-Disposition", headerValue.toString());

    OutputStream outputStream = response.getOutputStream();

    byte[] buffer = new byte[1024];
    int len;
    while ((len = fileInputStream.read(buffer)) > -1) {
        outputStream.write(buffer, 0, len);
    }
    IOUtils.closeQuietly(fileInputStream);
    IOUtils.closeQuietly(outputStream);
    LOGGER.trace("The file {} has been dispatched to the client.", fileName);

}

From source file:cz.incad.Kramerius.security.rightscommands.post.Delete.java

@Override
public void doCommand() {
    try {/*w  ww . j a v  a2  s.  co  m*/

        HttpServletRequest req = this.requestProvider.get();
        //Right right = RightsServlet.createRightFromPost(req, rightsManager, userManager, criteriumWrapperFactory);
        Map values = new HashMap();
        Enumeration parameterNames = req.getParameterNames();

        while (parameterNames.hasMoreElements()) {
            String key = (String) parameterNames.nextElement();
            String value = req.getParameter(key);
            SimpleJSONObjects simpleJSONObjects = new SimpleJSONObjects();
            simpleJSONObjects.createMap(key, values, value);
        }

        List rightsToDelete = (List) values.get("deletedrights");

        for (int i = 0; i < rightsToDelete.size(); i++) {
            String id = rightsToDelete.get(i).toString();
            deleteRight(Integer.parseInt(id));

        }

    } catch (SQLException e) {
        try {
            this.responseProvider.get().sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.daimler.spm.storefront.util.CSRFHandlerInterceptor.java

@Override
public boolean preHandle(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse, final Object handler) throws Exception {
    if (shouldCheckCSRFTokenForRequest(httpServletRequest)) {
        // httpServletRequest is POST and CSRF token validation is need for the given servelet path
        final String sessionCsrfToken = CSRFTokenManager.getTokenForSession(httpServletRequest.getSession());
        final String requestCsrfToken = CSRFTokenManager.getTokenFromRequest(httpServletRequest);
        if (sessionCsrfToken.equals(requestCsrfToken)) {
            return true;
        } else {/*w w w.j  a v a 2s .c  o  m*/
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "CSRF token validation failure");
            return false;
        }
    } else {
        // httpServletRequest doesn't need CSRF token validation
        return true;
    }
}

From source file:cn.imethan.common.security.handle.AccessDeniedHandlerImpl.java

public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    if (!response.isCommitted()) {
        if (errorPage != null) {
            // Put exception into request scope (perhaps of use to a view)
            request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);

            // Set the 403 status code.
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);

            // forward to error page.
            RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
            dispatcher.forward(request, response);
        } else {//from ww w  .  j a va 2s. co  m
            response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        }
    }
}

From source file:fi.hoski.web.auth.LoginServlet.java

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

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {//from w w w  . j a  v a  2  s.  c  o m
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

            HttpSession session = request.getSession(false);
            if (session != null) {
                session.setAttribute(USER, null);
                session.invalidate();
            }

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}