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.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    HttpSession session = request.getSession();

    try {//from   w  ww  . j a v  a 2  s. co m

        SliApi.setBaseUrl(apiUrl);

        // Setup OAuth service
        OAuthService service = new ServiceBuilder().provider(SliApi.class)
                .apiKey(propDecryptor.getDecryptedClientId())
                .apiSecret(propDecryptor.getDecryptedClientSecret()).callback(callbackUrl).build();

        // Check cookies for token, if found insert into session
        boolean cookieFound = checkCookiesForToken(request, session);

        Object token = session.getAttribute(OAUTH_TOKEN);

        if (token == null && request.getParameter(OAUTH_CODE) == null) {
            // Initiate authentication
            initiatingAuthentication(request, response, session, service);
        } else if (token == null && request.getParameter(OAUTH_CODE) != null) {
            // Verify authentication
            verifyingAuthentication(request, response, session, service);
        } else {
            // Complete authentication
            completeAuthentication(request, response, session, token, cookieFound);
        }
    } catch (OAuthException ex) {
        session.invalidate();
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() });
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
        return;
    } catch (Exception ex) {
        session.invalidate();
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() });
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        return;
    }
}

From source file:net.groupbuy.controller.admin.CommonController.java

/**
 * ??/*from w  w  w  . j a v a 2 s  .  c om*/
 */
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "unauthorized");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    return "/admin/common/unauthorized";
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // If not an administrator, make sure user is not trying to add or edit another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) {
        if (isAdd(request) || request.getParameter("id") != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }//from w w  w. j  a va  2s .co  m
    }

    if (!isFormSubmission(request)) {
        String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they can't change passwords
        log.debug("checking for remember me login...");

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                saveMessage(request, getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        User user;
        if (userId == null && !isAdd(request)) {
            user = getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        return user;
    } else {
        // populate user object from database, so all fields don't need to be hidden fields in form
        return getUserManager().getUser(request.getParameter("id"));
    }
}

From source file:com.imaginary.home.cloud.api.call.CommandCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    if (userId != null) {
        throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                "A user cannot update a command state");
    }//from w w w.ja va2 s . co m
    String commandId = (path.length > 1 ? path[1] : null);

    if (commandId == null) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_OPERATION,
                "You cannot PUT against the command root");
    }
    try {
        PendingCommand cmd = PendingCommand.getCommand(commandId);

        if (cmd == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "No such command: " + commandId);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equals("complete")) {
            object = object.getJSONObject("result");
            boolean result = (object.has("result") && object.getBoolean("result"));
            String errorMessage = (object.has("errorMessage") ? object.getString("errorMessage") : null);
            ControllerRelay relay = ControllerRelay.getRelay(cmd.getRelayId());

            cmd.update(PendingCommandState.EXECUTED, result, errorMessage);

            if (relay != null) {
                resp.setHeader("x-imaginary-has-commands", String.valueOf(PendingCommand.hasCommands(relay)));
            }
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in request");
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }

}

From source file:net.bhira.sample.api.controller.CompanyController.java

/**
 * Save the given instance of {@link net.bhira.sample.model.Company}. It will create a new
 * instance of the company does not exist, otherwise it will update the existing instance.
 * //from   w  ww .  java  2  s  .c om
 * @param request
 *            the http request containing JSON payload in its body.
 * @param response
 *            the http response to which the results will be written.
 * @return the error message, if save was not successful.
 */
@RequestMapping(value = "/company", method = RequestMethod.POST)
@ResponseBody
public Callable<String> saveCompany(HttpServletRequest request, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing POST company");
                Gson gson = JsonUtil.createGson();
                Company company = gson.fromJson(request.getReader(), Company.class);
                LOG.debug("POST company received json = {}", gson.toJson(company));
                companyService.save(company);
                HashMap<String, Long> map = new HashMap<String, Long>();
                map.put("id", company.getId());
                body = gson.toJson(map);
                LOG.debug("POST company/ successful with return ID = {}", company.getId());
            } catch (Exception ex) {
                if (ex instanceof JsonSyntaxException) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
                body = ex.getLocalizedMessage();
                LOG.warn("Error saving company. {}", body);
                LOG.debug("Save error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:de.mare.mobile.ui.security.AuthFilter.java

public void doFilterInternal(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (AppFeatures.PORTAL.isActive()) {
        final String requestURI = request.getRequestURI();
        User user = userSession.getUser();
        // area accessible without login
        boolean anonymousArea = false;
        if (this.excludeURIs != null) {
            for (final String excludeURI : this.excludeURIs) {
                String excludeURIWithContext = request.getContextPath() + excludeURI.trim();
                final boolean withStart = excludeURIWithContext.endsWith("*");
                final boolean isRequestURIexcluded;
                if (withStart) {
                    // remove the star
                    excludeURIWithContext = excludeURIWithContext.substring(0,
                            excludeURIWithContext.length() - 1);
                    isRequestURIexcluded = requestURI.startsWith(excludeURIWithContext);
                } else {
                    isRequestURIexcluded = requestURI.equals(excludeURIWithContext);
                }/*from w ww  .jav  a  2s .  co  m*/
                if (isRequestURIexcluded) {
                    anonymousArea = true;
                    break;
                }
            }
        }
        if (anonymousArea || user != null) {
            // let the others work
            chain.doFilter(servletRequest, servletResponse);
        } else {
            if (this.redirectToLoginPage) {
                // save the requested URL
                final StringBuffer urlBuffer = request.getRequestURL();
                if (StringUtils.isNotEmpty(request.getQueryString())) {
                    urlBuffer.append("?").append(request.getQueryString());
                }
                final String url = urlBuffer.toString();
                if (!url.contains("login") && !url.contains("error.")) {
                    // does not redirect to a login page (like loginFailed)
                    request.getSession().setAttribute(AppConstants.REDIRECT_AFTER_SUCCESSFUL_LOGIN, url);
                }
                request.getRequestDispatcher(this.loginPage).forward(servletRequest, servletResponse);
            } else {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }
        }
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:de.mpg.mpdl.inge.pubman.web.sword.PubManDepositServlet.java

/**
 * Process a POST request.//from w  w w .  j a  va 2 s  .  co  m
 * 
 * @param HttpServletRequest
 * @param HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.pubMan = new PubManSwordServer();
    SwordUtil util = new SwordUtil();
    Deposit deposit = new Deposit();
    AccountUserVO user = null;
    this.errorDoc = new PubManSwordErrorDocument();
    DepositResponse dr = null;

    // Authentification ---------------------------------------------
    String usernamePassword = this.getUsernamePassword(request);
    if (usernamePassword == null) {
        this.errorDoc.setSummary("No user credentials provided.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } else {
        int p = usernamePassword.indexOf(":");
        if (p != -1) {
            deposit.setUsername(usernamePassword.substring(0, p));
            deposit.setPassword(usernamePassword.substring(p + 1));
            user = util.getAccountUser(deposit.getUsername(), deposit.getPassword());
            this.pubMan.setCurrentUser(user);
        }
    }

    try {
        // Deposit --------------------------------------------------
        // Check if login was successfull
        if (this.pubMan.getCurrentUser() == null && this.validDeposit) {
            this.errorDoc.setSummary("Login user: " + deposit.getUsername() + " failed.");
            this.errorDoc.setErrorDesc(swordError.AuthentificationFailure);
            this.validDeposit = false;
        }

        // Check if collection was provided
        this.collection = request.getParameter("collection");
        if ((this.collection == null || this.collection.equals("")) && this.validDeposit) {
            this.collection = request.getParameter("collection");
            this.errorDoc.setSummary("No collection provided in request.");
            this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
            this.validDeposit = false;
        }

        // Check if user has depositing rights for this collection
        else {
            if (!util.checkCollection(this.collection, user) && this.validDeposit) {
                this.errorDoc.setSummary("User: " + deposit.getUsername()
                        + " does not have depositing rights for collection " + this.collection + ".");
                this.errorDoc.setErrorDesc(swordError.AuthorisationFailure);
                this.validDeposit = false;
            }
        }

        deposit.setFile(request.getInputStream());
        deposit = this.readHttpHeader(deposit, request);

        // Check if metadata format is supported
        if (!util.checkMetadatFormat(deposit.getFormatNamespace())) {
            throw new SWORDContentTypeException();
        }

        if (this.validDeposit) {
            // Get the DepositResponse
            dr = this.pubMan.doDeposit(deposit, this.collection);
        }
    } catch (SWORDAuthenticationException sae) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, this.getError());
        this.logger.error(sae.toString());
        this.validDeposit = false;

    } catch (SWORDContentTypeException e) {
        this.errorDoc.setSummary("File format not supported.");
        this.errorDoc.setErrorDesc(swordError.ErrorContent);
        this.validDeposit = false;
    } catch (ContentStreamNotFoundException e) {
        this.errorDoc.setSummary("No metadata File was found.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } catch (ItemInvalidException e) {
        ValidationReportItemVO itemReport = null;
        ValidationReportVO report = e.getReport();
        String error = "";
        for (int i = 0; i < report.getItems().size(); i++) {
            itemReport = report.getItems().get(i);
            error += itemReport.getContent() + "\n";
        }
        this.errorDoc.setSummary(error);
        this.errorDoc.setErrorDesc(swordError.ValidationFailure);
        this.validDeposit = false;
    } catch (PubItemStatusInvalidException e) {
        logger.error("Error in sword processing", e);
        this.errorDoc.setSummary("Provided item has wrong status.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } catch (Exception ioe) {
        logger.error("Error in sword processing", ioe);
        this.errorDoc.setSummary("An internal server error occurred.");
        this.errorDoc.setErrorDesc(swordError.InternalError);
        this.validDeposit = false;
    }
    try {
        // Write response atom
        if (this.validDeposit) {
            response.setStatus(dr.getHttpResponse());
            response.setContentType("application/xml");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Location", dr.getEntry().getContent().getSource());
            PrintWriter out = response.getWriter();
            out.write(dr.marshall());
            out.flush();
        }
        // Write error document
        else {
            String errorXml = this.errorDoc.createErrorDoc();
            response.setStatus(this.errorDoc.getStatus());
            response.setContentType("application/xml");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.write(errorXml);
            out.flush();
        }
    } catch (Exception e) {
        this.logger.error("Error document could not be created.", e);
        throw new RuntimeException();
    }

    this.pubMan.setCurrentUser(null);
    this.validDeposit = true;
}

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

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

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession();

    // skip everything that's not an authorize URL
    if (!requestMatcher.matches(request)) {
        chain.doFilter(req, res);
        return;
    }

    try {
        // we have to create our own auth request in order to get at all the parmeters appropriately
        AuthorizationRequest authRequest = null;

        ClientDetailsEntity client = null;

        authRequest = authRequestFactory
                .createAuthorizationRequest(createRequestMap(request.getParameterMap()));
        if (!Strings.isNullOrEmpty(authRequest.getClientId())) {
            client = clientService.loadClientByClientId(authRequest.getClientId());
        }

        // save the login hint to the session
        // but first check to see if the login hint makes any sense
        String loginHint = loginHintExtracter.extractHint((String) authRequest.getExtensions().get(LOGIN_HINT));
        if (!Strings.isNullOrEmpty(loginHint)) {
            session.setAttribute(LOGIN_HINT, loginHint);
        } else {
            session.removeAttribute(LOGIN_HINT);
        }

        if (authRequest.getExtensions().get(PROMPT) != null) {
            // we have a "prompt" parameter
            String prompt = (String) authRequest.getExtensions().get(PROMPT);
            List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));

            if (prompts.contains(PROMPT_NONE)) {
                // 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 {
                    logger.info("Client requested no prompt");
                    // user hasn't been logged in, we need to "return an error"
                    if (client != null && authRequest.getRedirectUri() != null) {

                        // if we've got a redirect URI then we'll send it

                        String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);

                        try {
                            URIBuilder uriBuilder = new URIBuilder(url);

                            uriBuilder.addParameter(ERROR, LOGIN_REQUIRED);
                            if (!Strings.isNullOrEmpty(authRequest.getState())) {
                                uriBuilder.addParameter(STATE, authRequest.getState()); // copy the state parameter if one was given
                            }

                            response.sendRedirect(uriBuilder.toString());
                            return;

                        } catch (URISyntaxException e) {
                            logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
                            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                            return;
                        }
                    }

                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                    return;
                }
            } else if (prompts.contains(PROMPT_LOGIN)) {

                // first see if the user's already been prompted in this session
                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 (authRequest.getExtensions().get(MAX_AGE) != null
                || (client != null && client.getDefaultMaxAge() != null)) {

            // default to the client's stored value, check the string parameter
            Integer max = (client != null ? client.getDefaultMaxAge() : null);
            String maxAge = (String) authRequest.getExtensions().get(MAX_AGE);
            if (maxAge != null) {
                max = Integer.parseInt(maxAge);
            }

            if (max != null) {

                Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);

                Date now = new Date();
                if (authTime != null) {
                    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);
        }

    } catch (InvalidClientException e) {
        // we couldn't find the client, move on and let the rest of the system catch the error
        chain.doFilter(req, res);
    }
}

From source file:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getstudentexams/{userId}")
public @ResponseBody StudentInfoExams getStudentExams(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable String userId) throws InvocationException {
    try {//from   www.  j av  a 2 s .c o m
        User user = getUserObject(userId);
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(userId, token);
        StudentInfoExams result = getStudentExams(idAda);
        if (result != null) {
            return result;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

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