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:alpha.portal.webapp.controller.SignupController.java

/**
 * On submit./* w ww.  j av  a2 s .  c o m*/
 * 
 * @param user
 *            the user
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.log.isDebugEnabled()) {
        this.log.debug("entering 'onSubmit' method...");
    }
    final Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(this.roleManager.getRole(Constants.USER_ROLE));

    try {
        this.getUserManager().saveUser(user);
    } catch (final AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor
        // userManagerSecurity
        this.log.warn(ade.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (final UserExistsException e) {
        errors.rejectValue("username", "errors.existing.user",
                new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

        // redisplay the unencrypted passwords
        user.setPassword(user.getConfirmPassword());
        return "signup";
    }

    this.saveMessage(request, this.getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    final UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (this.log.isDebugEnabled()) {
        this.log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    this.message.setSubject(this.getText("signup.email.subject", locale));

    try {
        this.sendUserMessage(user, this.getText("signup.email.message", locale),
                RequestUtil.getAppURL(request));
    } catch (final MailException me) {
        this.saveError(request, me.getMostSpecificCause().getMessage());
    }

    return this.getSuccessView();
}

From source file:com.imaginary.home.cloud.api.RestApi.java

public @Nullable String authenticate(@Nonnull String method, @Nonnull HttpServletRequest request,
        Map<String, Object> headers) throws RestException {
    Number timestamp = (Number) headers.get(TIMESTAMP);
    String apiKey = (String) headers.get(API_KEY);
    String signature = (String) headers.get(SIGNATURE);
    String version = (String) headers.get(VERSION);

    if (timestamp == null || apiKey == null || signature == null || version == null) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INCOMPLETE_HEADERS,
                "Incomplete authentication headers, requires: " + API_KEY + " - " + TIMESTAMP + " - "
                        + SIGNATURE + " - " + VERSION);
    }/*  w  w  w  .  jav a  2 s .  c  om*/
    if (signature.length() < 1) {
        throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SIGNATURE,
                "No signature was provided for authentication");
    }
    try {
        ControllerRelay relay = ControllerRelay.getRelay(apiKey);
        String userId = null;
        String customSalt;
        String secret;

        if (relay == null) {
            ApiKey key = ApiKey.getApiKey(apiKey);

            if (key == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_KEY,
                        "Invalid API key");
            }
            secret = key.getApiKeySecret();
            userId = key.getUserId();
            customSalt = userId;
        } else {
            secret = relay.getApiKeySecret();
            customSalt = relay.getLocationId();
        }
        String stringToSign;

        if (relay != null) {
            String token = Configuration.decrypt(relay.getLocationId(), relay.getToken());

            stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":"
                    + token + ":" + timestamp.longValue() + ":" + version;
        } else {
            stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":"
                    + timestamp.longValue() + ":" + version;
        }
        String expected;

        try {
            expected = CloudService.sign(Configuration.decrypt(customSalt, secret).getBytes("utf-8"),
                    stringToSign);
        } catch (Exception e) {
            throw new RestException(e);
        }
        if (!signature.equals(expected)) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_SIGNATURE,
                    "String to sign was: " + stringToSign);
        }
        return userId;
    } catch (PersistenceException e) {
        throw new RestException(e);
    }
}

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

@VisibleForTesting
protected boolean validateAppId(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    boolean valid = false;
    String ourAppId = null;/*  w  w  w  .  j  av a 2s . c  om*/
    try {
        ourAppId = getReceiver().getAppId().get();
    } catch (StageException e) {
        throw new IOException("Cant resolve credential value", e);
    }
    String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
    String reqAppId = req.getHeader(HttpConstants.X_SDC_APPLICATION_ID_HEADER);

    if (reqAppId == null && receiver.isAppIdViaQueryParamAllowed()) {
        reqAppId = getQueryParameters(req).get(HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM)[0];
    }

    if (reqAppId == null) {
        LOG.warn("Request from '{}' missing appId, rejected", requestor);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing 'appId'");
    } else if (!ourAppId.equals(reqAppId)) {
        LOG.warn("Request from '{}' invalid appId '{}', rejected", requestor, reqAppId);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
    } else {
        valid = true;
    }
    return valid;
}

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

/**
 * /*from w  w w. j a v a  2  s .  c o  m*/
 * @param externalIdentifier the external UUID of a principal.
 * @return the {@link Principal} element representing the principal object with the "externalIdentifier".
 * @throws IOException is sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{principalid}")
@Transactional(readOnly = true)
public JAXBElement<Principal> getPrincipal(@PathParam("principalid") String externalIdentifier)
        throws IOException {
    Map params = new HashMap<String, String>();
    params.put("externalId", externalIdentifier);
    try {
        Principal result = (Principal) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetPrincipal());
        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:com.haulmont.cuba.core.controllers.LogDownloadController.java

protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException {
    UUID sessionUUID;/*from   w ww. j a  v a2s  .  c om*/
    try {
        sessionUUID = UUID.fromString(sessionId);
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    UserSession session = userSessions.getAndRefresh(sessionUUID);
    if (session == null)
        response.sendError(HttpServletResponse.SC_FORBIDDEN);

    return session;
}

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

@Override
public void get(@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 (logger.isDebugEnabled()) {
        logger.debug("GET " + req.getRequestURI());
    }//from ww  w . ja  v  a 2  s  .c o  m
    try {
        String deviceId = (path.length > 1 ? path[1] : null);

        if (logger.isDebugEnabled()) {
            logger.debug("deviceId=" + deviceId);
        }
        if (deviceId != null) {
            Device device = Device.getDevice(deviceId);

            if (device == null) {
                throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                        "The device " + deviceId + " does not exist.");
            }
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().println((new JSONObject(toJSON(device))).toString());
            resp.getWriter().flush();
        } else {
            String locationId = req.getParameter("locationId");
            String deviceType = req.getParameter("deviceType");
            String tmp = req.getParameter("includeChildren");
            boolean includeChildren = (tmp != null && tmp.equalsIgnoreCase("true"));

            if (logger.isDebugEnabled()) {
                logger.debug("Params=" + locationId + " / " + deviceType + " / " + includeChildren);
            }
            User user = (userId != null ? User.getUserByUserId(userId) : null);
            ControllerRelay relay = (user == null
                    ? ControllerRelay.getRelay((String) headers.get(RestApi.API_KEY))
                    : null);
            Location location = (locationId == null ? null : Location.getLocation(locationId));

            if (locationId != null && location == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION,
                        "You do not have access to those resources");
            }
            if (user == null && relay == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION,
                        "Cannot request devices without a proper authentication context");
            }
            if (relay != null && location != null) {
                if (!relay.getLocationId().equals(location.getLocationId())) {
                    throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION,
                            "You do not have access to those resources");
                }
            }
            Collection<ControllerRelay> relays;

            if (relay != null) {
                relays = Collections.singletonList(relay);
            } else {
                if (location != null) {
                    boolean allowed = location.getOwnerId().equals(user.getUserId());

                    if (!allowed) {
                        for (String id : user.getLocationIds()) {
                            if (id.equals(location.getLocationId())) {
                                allowed = true;
                                break;
                            }
                        }
                        if (!allowed) {
                            throw new RestException(HttpServletResponse.SC_FORBIDDEN,
                                    RestException.INVALID_ACTION, "You do not have access to those resources");
                        }
                    }
                    relays = ControllerRelay.findRelaysInLocation(location);
                } else {
                    relays = new ArrayList<ControllerRelay>();
                    for (Location l : user.getLocations()) {
                        relays.addAll(ControllerRelay.findRelaysInLocation(l));
                    }
                }

            }
            if (logger.isDebugEnabled()) {
                logger.debug("relays=" + relays);
            }
            ArrayList<Device> devices = new ArrayList<Device>();

            for (ControllerRelay r : relays) {
                if (deviceType == null) {
                    devices.addAll(Device.findDevicesForRelay(r));
                } else if (deviceType.equals("powered")) {
                    if (includeChildren) {
                        PoweredDevice.findPoweredDevicesForRelayWithChildren(r, devices);
                    } else {
                        devices.addAll(PoweredDevice.findPoweredDevicesForRelay(r));
                    }
                } else if (deviceType.equals("light")) {
                    devices.addAll(Light.findPoweredDevicesForRelay(r));
                } else {
                    throw new RestException(HttpServletResponse.SC_BAD_REQUEST,
                            RestException.INVALID_DEVICE_TYPE, "Invalid device type: " + deviceType);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("devices=" + devices);
            }
            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            for (Device d : devices) {
                list.add(toJSON(d));
            }
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().println((new JSONArray(list)).toString());
            resp.getWriter().flush();
        }
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:org.jboss.as.test.integration.web.security.servlet.methods.DenyUncoveredHttpMethodsTestCase.java

@Test
public void testOptionsMethod() throws Exception {
    HttpOptions httpOptions = new HttpOptions(getURL());
    HttpResponse response = getHttpResponse(httpOptions);

    assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN));
}

From source file:org.jboss.as.test.clustering.cluster.web.authentication.BasicAuthenticationWebFailoverTestCase.java

@Test
public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, URISyntaxException {

    CredentialsProvider provider = new BasicCredentialsProvider();
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build();

    URI uri1 = SecureServlet.createURI(baseURL1);
    URI uri2 = SecureServlet.createURI(baseURL2);

    try {// ww w .j  a  va 2 s  .  c om
        // Valid login, invalid role
        setCredentials(provider, "forbidden", "password", baseURL1, baseURL2);
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Invalid login, valid role
        setCredentials(provider, "allowed", "bad", baseURL1, baseURL2);
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Valid login, valid role
        setCredentials(provider, "allowed", "password", baseURL1, baseURL2);
        String sessionId = null;
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
            sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        undeploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        deploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    log.debug(path);//from  w ww. j av a2 s.c om

    if (path == null) {
        return;
    }
    String[] parts = path.split("/");

    if (path.length() < 1) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request");
        return;
    }

    // for this validation, the key and secret are passed as POST parameters
    if (StringUtils.equals(parts[1], "validateOAuthConsumer")) {
        validateOAuthConsumer(request, response);
        return;
    }

    HttpSession session = request.getSession();
    String consumerKey = (String) session.getAttribute("consumerKey");
    String consumerSecret = (String) session.getAttribute("consumerSecret");

    if (!checkOAuthConsumer(consumerKey, consumerSecret)) {
        // no valid key in session, no access
        log.error("Request without valid key from " + request.getRemoteAddr());
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to access the servlet!");
        return;
    }

    if (StringUtils.equals(parts[1], "deleteTweet")) {
        deleteTweets(request, response);

    } else if (StringUtils.equals(parts[1], "updateUserStatus")) {
        updateUserStatus(request, response);

    } else if (StringUtils.equals(parts[1], "retweet")) {
        retweet(request, response);

    } else if (StringUtils.equals(parts[1], "verifyCredentials")) {
        verifyCredentials(request, response);

    } else if (StringUtils.equals(parts[1], "getTweets")) {
        getTweets(request, response);

    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request");
        return;
    }
}