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.sg.rest.SpringSecurityTest.java

@Test
public void testSecureResourceWithAuthTokenButNonSufficientRights() throws IOException, Exception {
    String authToken = webSecurityService.generateToken(ACCOUNT_ID, Instant.now(),
            TokenExpirationStandardDurations.WEB_SESSION_TOKEN_EXPIRATION_DURATION);
    Set<Role> roles = EnumSet.noneOf(Role.class);
    when(handler.handle(new GetAccountRolesOperation(ACCOUNT_ID)))
            .thenReturn(new GetAccountRolesResponse(roles));

    mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST).header(HttpCustomHeaders.AUTH_TOKEN_HEADER.getHeader(),
            authToken)).andExpect(status().is(HttpServletResponse.SC_FORBIDDEN))
            .andExpect(content().contentType(CustomMediaTypes.APPLICATION_JSON_UTF8.getMediatype()))
            .andExpect(jsonPath("$.eventRef.id", not(isEmptyOrNullString())));
}

From source file:com.erudika.para.security.RestAuthFilter.java

private boolean appAuthRequestHandler(String appid, BufferedRequestWrapper request,
        HttpServletResponse response) {/*from   ww w  .ja  v  a2  s. c  om*/
    String date = RestUtils.extractDate(request);
    Date d = Signer.parseAWSDate(date);
    String reqUri = request.getRequestURI();
    String method = request.getMethod();
    boolean requestExpired = (d != null)
            && (System.currentTimeMillis() > (d.getTime() + (Config.REQUEST_EXPIRES_AFTER_SEC * 1000)));

    if (!StringUtils.isBlank(appid)) {
        if (!StringUtils.isBlank(date)) {
            if (!requestExpired) {
                App app = Para.getDAO().read(App.id(appid));

                if (app != null) {
                    if (app.getActive()) {
                        if (!(app.getReadOnly() && isWriteRequest(request))) {
                            if (signer.isValidSignature(request, app.getSecret())) {
                                SecurityContextHolder.getContext()
                                        .setAuthentication(new AppAuthentication(app));
                            } else {
                                RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                        "Request signature is invalid.");
                                return false;
                            }
                        } else {
                            RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                    Utils.formatMessage("App is in read-only mode. [{0}]", appid));
                            return false;
                        }
                    } else {
                        RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                Utils.formatMessage("App not active. [{0}]", appid));
                        return false;
                    }
                } else {
                    RestUtils.returnStatusResponse(response, HttpServletResponse.SC_NOT_FOUND,
                            Utils.formatMessage("App not found. [{0}]", appid));
                    return false;
                }
            } else {
                RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
                        "Request has expired.");
                return false;
            }
        } else {
            RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
                    "'X-Amz-Date' header or parameter is not set!");
            return false;
        }
    } else {
        RestUtils.returnStatusResponse(response, HttpServletResponse.SC_UNAUTHORIZED, Utils
                .formatMessage("You don't have permission to access this resource. [{0} {1}]", method, reqUri));
        return false;
    }
    return true;
}

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

/**
 * //from w ww .  j  ava  2  s .  c om
 * @param email the e-mail of a principal.
 * @return a {@link Principal} representing the principal with the "email", 
 * if such a principal is found; otherwise "SC_NOT_FOUND" error is sent.
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("info")
@Transactional(readOnly = true)
public JAXBElement<Principal> getPrincipalByInfo(@QueryParam("email") String email) throws IOException {
    Map params = new HashMap<String, String>();
    params.put("email", email);
    try {
        Principal result = (Principal) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetPrincipalByInfo());
        return (result != null) ? (new ObjectFactory().createPrincipal(result))
                : (new ObjectFactory().createPrincipal(new Principal()));
    } catch (NotInDataBaseException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    }
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

/**
 * ??/*w w w. jav a  2  s . co  m*/
 */
@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 "/common/unauthorized";
}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

@Test
@InSequence(2)//from  ww  w.  ja  va 2 s.co m
public void testSecuredReadWriteOperations() throws Exception {
    try {
        controller.start(CONTAINER1, new Config().add(SERVER_CONFIG_PROPERTY, CONFIG_READ_WRITE_SECURED).map());
        //correct alias for the certificate
        put(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        //test wrong authorization, 1. wrong alias for the certificate
        put(securedClient(test2Alias), keyAddress(KEY_B), HttpServletResponse.SC_FORBIDDEN);
        //2. access over 8080
        put(securedClient(testAlias), keyAddressUnsecured(KEY_B), HttpServletResponse.SC_UNAUTHORIZED);
        post(securedClient(testAlias), keyAddress(KEY_C), HttpServletResponse.SC_OK);
        post(securedClient(test2Alias), keyAddress(KEY_D), HttpServletResponse.SC_FORBIDDEN);
        //get is secured too
        HttpResponse resp = get(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        String content = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())).readLine();
        assertEquals("data", content);
        //test wrong authorization, 1. wrong alias for the certificate
        get(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN);
        //2. access over 8080
        get(securedClient(testAlias), keyAddressUnsecured(KEY_A), HttpServletResponse.SC_UNAUTHORIZED);
        head(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN);
        //access over 8080
        head(securedClient(testAlias), keyAddressUnsecured(KEY_A), HttpServletResponse.SC_UNAUTHORIZED);
        head(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        delete(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN);
        delete(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        delete(securedClient(testAlias), keyAddress(KEY_C), HttpServletResponse.SC_OK);
    } finally {
        controller.stop(CONTAINER1);
    }
}

From source file:org.ngrinder.script.controller.DavSvnController.java

/**
 * Request Handler./*from   w  w w  . java 2  s . c o  m*/
 * 
 * @param request
 *            request
 * @param response
 *            response
 * @throws ServletException
 *             occurs when servlet has a problem.
 * @throws IOException
 *             occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        final String head = DAVPathUtil.head(request.getPathInfo());
        final User currentUser = userContext.getCurrentUser();
        // check the security. If the other user tries to the other user's
        // repo, deny it.
        if (!StringUtils.equals(currentUser.getUserId(), head)) {
            SecurityContextHolder.getContext().setAuthentication(null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    head + " is not accessible by " + currentUser.getUserId());
            return;
        }
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerExFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

From source file:com.streamsets.pipeline.stage.origin.sdcipctokafka.IpcToKafkaServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    if (shuttingDown) {
        LOG.debug("Shutting down, discarding incoming request from '{}'", requestor);
        resp.setStatus(HttpServletResponse.SC_GONE);
    } else {/*ww w . ja v a2 s  . co m*/
        String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER);
        String compression = req.getHeader(Constants.X_SDC_COMPRESSION_HEADER);
        String contentType = req.getContentType();
        String json1Fragmentable = req.getHeader(Constants.X_SDC_JSON1_FRAGMENTABLE_HEADER);
        if (!Constants.APPLICATION_BINARY.equals(contentType)) {
            invalidRequestMeter.mark();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format(
                    "Wrong content-type '{}', expected '{}'", contentType, Constants.APPLICATION_BINARY));
        } else if (!"true".equals(json1Fragmentable)) {
            invalidRequestMeter.mark();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format(
                    "RPC client is not using a fragmentable JSON1 encoding, client;s SDC must be upgraded"));
        } else if (!configs.appId.equals(appId)) {
            invalidRequestMeter.mark();
            LOG.warn("IPC from '{}' invalid appId '{}', rejected", requestor, appId);
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
        } else {
            long start = System.currentTimeMillis();
            LOG.debug("Request accepted from '{}'", requestor);
            try (InputStream in = req.getInputStream()) {
                InputStream is = in;
                boolean processRequest = true;
                if (compression != null) {
                    switch (compression) {
                    case Constants.SNAPPY_COMPRESSION:
                        is = new SnappyFramedInputStream(is, true);
                        break;
                    default:
                        invalidRequestMeter.mark();
                        LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression,
                                requestor);
                        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                                "Unsupported compression: " + compression);
                        processRequest = false;
                    }
                }
                if (processRequest) {
                    LOG.debug("Processing request from '{}'", requestor);
                    List<byte[]> messages = SdcStreamFragmenter.fragment(is, maxMessageSize, maxRpcRequestSize);
                    LOG.debug("Request from '{}' broken into '{}' messages", requestor, messages.size());
                    long kStart = System.currentTimeMillis();
                    SdcKafkaProducer producer = getKafkaProducer();
                    long kafkaTime = System.currentTimeMillis() - kStart;
                    try {
                        for (byte[] message : messages) {
                            // we are using round robing partition strategy, partition key is ignored
                            kStart = System.currentTimeMillis();
                            producer.enqueueMessage(configs.topic, message, "");
                            kafkaTime += System.currentTimeMillis() - kStart;
                        }
                        kStart = System.currentTimeMillis();
                        producer.write();
                        kafkaTime += System.currentTimeMillis() - kStart;
                        resp.setStatus(HttpServletResponse.SC_OK);
                        requestMeter.mark();
                    } catch (StageException ex) {
                        LOG.warn("Kakfa producer error: {}", ex.toString(), ex);
                        errorQueue.offer(ex);
                        errorRequestMeter.mark();
                        LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex);
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
                    } finally {
                        kStart = System.currentTimeMillis();
                        releaseKafkaProducer(producer);
                        kafkaTime += System.currentTimeMillis() - kStart;
                    }
                    kafkaTimer.update(kafkaTime, TimeUnit.MILLISECONDS);
                    kafkaMessagesMeter.mark(messages.size());
                }
            } catch (Exception ex) {
                errorRequestMeter.mark();
                LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString());
            } finally {
                requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
            }
        }
    }
}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

private boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String auth = request.getHeader("authorization");
    if (auth == null) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"PID Cache\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } else {//w ww  .  j  av a2 s  . co m
        auth = auth.substring(6);
        String cred = new String(Base64.decodeBase64(auth.getBytes()));
        if (cred.contains(":")) {

            String[] userPass = cred.split(":");
            String userName = PropertyReader.getProperty("escidoc.pidcache.user.name");
            String password = PropertyReader.getProperty("escidoc.pidcache.user.password");

            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.google.gerrit.httpd.auth.openid.OAuthSessionOverOpenID.java

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    com.google.gerrit.server.account.AuthRequest areq = new com.google.gerrit.server.account.AuthRequest(
            ExternalId.Key.parse(user.getExternalId()));
    AuthResult arsp = null;/*from   ww w  . ja v a 2s . c o  m*/
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId());
        Optional<Account.Id> claimedId = Optional.empty();

        // We try to retrieve claimed identity.
        // For some reason, for example staging instance
        // it may deviate from the really old OpenID identity.
        // What we want to avoid in any event is to create new
        // account instead of linking to the existing one.
        // That why we query it here, not to lose linking mode.
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            claimedId = accountManager.lookup(claimedIdentifier);
            if (!claimedId.isPresent()) {
                log.debug("Claimed identity is unknown");
            }
        }

        // Use case 1: claimed identity was provided during handshake phase
        // and user account exists for this identity
        if (claimedId.isPresent()) {
            log.debug("Claimed identity is set and is known");
            if (actualId.isPresent()) {
                if (claimedId.get().equals(actualId.get())) {
                    // Both link to the same account, that's what we expected.
                    log.debug("Both link to the same account. All is fine.");
                } else {
                    // This is (for now) a fatal error. There are two records
                    // for what might be the same user. The admin would have to
                    // link the accounts manually.
                    log.error("OAuth accounts disagree over user identity:\n" + "  Claimed ID: "
                            + claimedId.get() + " is " + claimedIdentifier + "\n" + "  Delgate ID: "
                            + actualId.get() + " is " + user.getExternalId());
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                // Claimed account already exists: link to it.
                log.debug("Claimed account already exists: link to it.");
                try {
                    accountManager.link(claimedId.get(), areq);
                } catch (OrmException | ConfigInvalidException e) {
                    log.error("Cannot link: " + user.getExternalId() + " to user identity:\n" + "  Claimed ID: "
                            + claimedId.get() + " is " + claimedIdentifier);
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
        } else if (linkMode) {
            // Use case 2: link mode activated from the UI
            Account.Id accountId = identifiedUser.get().getAccountId();
            try {
                log.debug("Linking \"{}\" to \"{}\"", user.getExternalId(), accountId);
                accountManager.link(accountId, areq);
            } catch (OrmException | ConfigInvalidException e) {
                log.error("Cannot link: " + user.getExternalId() + " to user identity: " + accountId);
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            } finally {
                linkMode = false;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        log.error("Unable to authenticate user \"" + user + "\"", e);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    webSession.get().login(arsp, true);
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(Url.decode(redirectToken));
    rsp.sendRedirect(rdr.toString());
}

From source file:co.kuali.coeus.sys.impl.persistence.SchemaSpyFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final UserSession session = getGlobalVariableService().getUserSession() != null
            ? getGlobalVariableService().getUserSession()
            : (UserSession) ((HttpServletRequest) request).getSession()
                    .getAttribute(KRADConstants.USER_SESSION_KEY);
    if (session == null || !getPermissionService().isAuthorizedByTemplate(session.getPrincipalId(),
            KRADConstants.KRAD_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_VIEW,
            Collections.singletonMap(KimConstants.AttributeConstants.VIEW_ID, KIM_SCHEMA_SPY_VIEW_ID),
            Collections.<String, String>emptyMap())) {
        HttpUtils.disableCache((HttpServletResponse) response);
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from  w w  w .j  av  a 2  s.  co  m*/
    }

    if (!getConfigurationService().getPropertyValueAsBoolean(SCHEMA_SPY_CONFIG_PARAM)) {
        HttpUtils.disableCache((HttpServletResponse) response);
        response.getWriter().write("SchemaSpy has been disabled.");
        return;
    }

    synchronized (initialized) {
        if (REFRESH_TRUE.equals(request.getParameter(REFRESH_PARAM)) && initialized.get()) {
            Executors.newSingleThreadExecutor().execute(refreshSchemaSpy);
        }

        if (!initialized.get()) {
            HttpUtils.disableCache((HttpServletResponse) response);
            response.getWriter().write("Please wait. SchemaSpy is still processing.");
            return;
        }
    }

    chain.doFilter(request, response);
}