Example usage for org.springframework.http HttpStatus FORBIDDEN

List of usage examples for org.springframework.http HttpStatus FORBIDDEN

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FORBIDDEN.

Prototype

HttpStatus FORBIDDEN

To view the source code for org.springframework.http HttpStatus FORBIDDEN.

Click Source Link

Document

403 Forbidden .

Usage

From source file:org.springframework.social.twitter.api.impl.TwitterErrorHandler.java

private void handleClientErrors(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);

    String errorText = "";
    if (errorMap.containsKey("error")) {
        errorText = (String) errorMap.get("error");
    } else if (errorMap.containsKey("errors")) {
        Object errors = errorMap.get("errors");
        if (errors instanceof List) {
            @SuppressWarnings("unchecked")
            List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
            errorText = errorsList.get(0).get("message");
        } else if (errors instanceof String) {
            errorText = (String) errors;
        }/* w  ww  . j a  va 2 s  .  co m*/
    }

    if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorText.contains("Rate limit exceeded.")) {
            throw new RateLimitExceededException("twitter");
        }
    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (errorText == null) {
            throw new NotAuthorizedException("twitter", response.getStatusText());
        } else if (errorText.equals("Could not authenticate you.")) {
            throw new MissingAuthorizationException("twitter");
        } else if (errorText.equals("Could not authenticate with OAuth.")) { // revoked token
            throw new RevokedAuthorizationException("twitter");
        } else if (errorText.equals("Invalid / expired Token")) { // Note that Twitter doesn't actually expire tokens
            throw new InvalidAuthorizationException("twitter", errorText);
        } else {
            throw new NotAuthorizedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.FORBIDDEN) {
        if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
            throw new DuplicateStatusException("twitter", errorText);
        } else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
            throw new MessageTooLongException(errorText);
        } else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
            throw new InvalidMessageRecipientException(errorText);
        } else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
            throw new RateLimitExceededException("twitter");
        } else {
            throw new OperationNotPermittedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("twitter", errorText);
    } else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM)
            || statusCode == HttpStatus.valueOf(TOO_MANY_REQUESTS)) {
        throw new RateLimitExceededException("twitter");
    }

}

From source file:org.springframework.web.cors.DefaultCorsProcessor.java

/**
 * Invoked when one of the CORS checks failed.
 * The default implementation sets the response status to 403 and writes
 * "Invalid CORS request" to the response.
 *//*  ww  w .  j  a  v a 2s  .c o  m*/
protected void rejectRequest(ServerHttpResponse response) throws IOException {
    response.setStatusCode(HttpStatus.FORBIDDEN);
    response.getBody().write("Invalid CORS request".getBytes(StandardCharsets.UTF_8));
}

From source file:org.springframework.web.cors.reactive.DefaultCorsProcessor.java

/**
 * Invoked when one of the CORS checks failed.
 *///from   w w w.j a va  2  s. co  m
protected void rejectRequest(ServerHttpResponse response) {
    response.setStatusCode(HttpStatus.FORBIDDEN);
    logger.debug("Invalid CORS request");
}

From source file:org.springframework.web.socket.server.DefaultHandshakeHandler.java

@Override
public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler webSocketHandler) throws IOException, HandshakeFailureException {

    logger.debug("Starting handshake for " + request.getURI());

    if (!HttpMethod.GET.equals(request.getMethod())) {
        response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
        response.getHeaders().setAllow(Collections.singleton(HttpMethod.GET));
        logger.debug("Only HTTP GET is allowed, current method is " + request.getMethod());
        return false;
    }//from  w  ww .j  a v a 2  s  .c  om
    if (!"WebSocket".equalsIgnoreCase(request.getHeaders().getUpgrade())) {
        handleInvalidUpgradeHeader(request, response);
        return false;
    }
    if (!request.getHeaders().getConnection().contains("Upgrade")
            && !request.getHeaders().getConnection().contains("upgrade")) {
        handleInvalidConnectHeader(request, response);
        return false;
    }
    if (!isWebSocketVersionSupported(request)) {
        handleWebSocketVersionNotSupported(request, response);
        return false;
    }
    if (!isValidOrigin(request)) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return false;
    }
    String wsKey = request.getHeaders().getSecWebSocketKey();
    if (wsKey == null) {
        logger.debug("Missing \"Sec-WebSocket-Key\" header");
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        return false;
    }

    String selectedProtocol = selectProtocol(request.getHeaders().getSecWebSocketProtocol());
    // TODO: select extensions

    logger.debug("Upgrading HTTP request");

    response.setStatusCode(HttpStatus.SWITCHING_PROTOCOLS);
    response.getHeaders().setUpgrade("WebSocket");
    response.getHeaders().setConnection("Upgrade");
    response.getHeaders().setSecWebSocketProtocol(selectedProtocol);
    response.getHeaders().setSecWebSocketAccept(getWebSocketKeyHash(wsKey));
    // TODO: response.getHeaders().setSecWebSocketExtensions(extensions);

    response.flush();

    if (logger.isTraceEnabled()) {
        logger.trace("Upgrading with " + webSocketHandler);
    }

    this.requestUpgradeStrategy.upgrade(request, response, selectedProtocol, webSocketHandler);

    return true;
}

From source file:org.springframework.web.socket.server.support.AbstractHandshakeHandler.java

@Override
public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {

    WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHeaders());
    if (logger.isTraceEnabled()) {
        logger.trace("Processing request " + request.getURI() + " with headers=" + headers);
    }/* ww  w  .ja v a  2s. c o  m*/
    try {
        if (HttpMethod.GET != request.getMethod()) {
            response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
            response.getHeaders().setAllow(Collections.singleton(HttpMethod.GET));
            if (logger.isErrorEnabled()) {
                logger.error("Handshake failed due to unexpected HTTP method: " + request.getMethod());
            }
            return false;
        }
        if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
            handleInvalidUpgradeHeader(request, response);
            return false;
        }
        if (!headers.getConnection().contains("Upgrade") && !headers.getConnection().contains("upgrade")) {
            handleInvalidConnectHeader(request, response);
            return false;
        }
        if (!isWebSocketVersionSupported(headers)) {
            handleWebSocketVersionNotSupported(request, response);
            return false;
        }
        if (!isValidOrigin(request)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return false;
        }
        String wsKey = headers.getSecWebSocketKey();
        if (wsKey == null) {
            if (logger.isErrorEnabled()) {
                logger.error("Missing \"Sec-WebSocket-Key\" header");
            }
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return false;
        }
    } catch (IOException ex) {
        throw new HandshakeFailureException(
                "Response update failed during upgrade to WebSocket: " + request.getURI(), ex);
    }

    String subProtocol = selectProtocol(headers.getSecWebSocketProtocol(), wsHandler);
    List<WebSocketExtension> requested = headers.getSecWebSocketExtensions();
    List<WebSocketExtension> supported = this.requestUpgradeStrategy.getSupportedExtensions(request);
    List<WebSocketExtension> extensions = filterRequestedExtensions(request, requested, supported);
    Principal user = determineUser(request, wsHandler, attributes);

    if (logger.isTraceEnabled()) {
        logger.trace("Upgrading to WebSocket, subProtocol=" + subProtocol + ", extensions=" + extensions);
    }
    this.requestUpgradeStrategy.upgrade(request, response, subProtocol, extensions, user, wsHandler,
            attributes);
    return true;
}

From source file:org.springframework.web.socket.server.support.DefaultHandshakeHandler.java

@Override
public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {

    WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHeaders());
    if (logger.isTraceEnabled()) {
        logger.trace("Processing request " + request.getURI() + " with headers=" + headers);
    }/*from w  ww  .j  a v a  2s  .  co m*/
    try {
        if (!HttpMethod.GET.equals(request.getMethod())) {
            response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
            response.getHeaders().setAllow(Collections.singleton(HttpMethod.GET));
            if (logger.isErrorEnabled()) {
                logger.error("Handshake failed due to unexpected HTTP method: " + request.getMethod());
            }
            return false;
        }
        if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
            handleInvalidUpgradeHeader(request, response);
            return false;
        }
        if (!headers.getConnection().contains("Upgrade") && !headers.getConnection().contains("upgrade")) {
            handleInvalidConnectHeader(request, response);
            return false;
        }
        if (!isWebSocketVersionSupported(headers)) {
            handleWebSocketVersionNotSupported(request, response);
            return false;
        }
        if (!isValidOrigin(request)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return false;
        }
        String wsKey = headers.getSecWebSocketKey();
        if (wsKey == null) {
            if (logger.isErrorEnabled()) {
                logger.error("Missing \"Sec-WebSocket-Key\" header");
            }
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return false;
        }
    } catch (IOException ex) {
        throw new HandshakeFailureException(
                "Response update failed during upgrade to WebSocket, uri=" + request.getURI(), ex);
    }

    String subProtocol = selectProtocol(headers.getSecWebSocketProtocol(), wsHandler);
    List<WebSocketExtension> requested = headers.getSecWebSocketExtensions();
    List<WebSocketExtension> supported = this.requestUpgradeStrategy.getSupportedExtensions(request);
    List<WebSocketExtension> extensions = filterRequestedExtensions(request, requested, supported);
    Principal user = determineUser(request, wsHandler, attributes);

    if (logger.isTraceEnabled()) {
        logger.trace("Upgrading to WebSocket, subProtocol=" + subProtocol + ", extensions=" + extensions);
    }
    this.requestUpgradeStrategy.upgrade(request, response, subProtocol, extensions, user, wsHandler,
            attributes);
    return true;
}

From source file:org.springframework.web.socket.server.support.OriginHandshakeInterceptor.java

@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
        WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

    if (!WebUtils.isSameOrigin(request) && !WebUtils.isValidOrigin(request, this.allowedOrigins)) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        if (logger.isDebugEnabled()) {
            logger.debug("Handshake request rejected, Origin header value " + request.getHeaders().getOrigin()
                    + " not allowed");
        }//from  w  w  w  .  j av a  2  s  . c o m
        return false;
    }
    return true;
}

From source file:org.springframework.web.socket.sockjs.support.AbstractSockJsService.java

protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)
        throws IOException {

    if (WebUtils.isSameOrigin(request)) {
        return true;
    }/*www  .j  a  va 2 s.  c om*/

    if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed.");
        }
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return false;
    }

    return true;
}

From source file:org.tightblog.ui.restapi.UserController.java

@PostMapping(value = "/tb-ui/register/rest/registeruser")
public ResponseEntity registerUser(@Valid @RequestBody UserData newData, Locale locale,
        HttpServletResponse response) throws ServletException {
    ValidationError maybeError = advancedValidate(null, newData, true, locale);
    if (maybeError != null) {
        return ResponseEntity.badRequest().body(maybeError);
    }/*from   w  ww.  jav  a  2 s. c  om*/

    long userCount = userRepository.count();
    WebloggerProperties.RegistrationPolicy option = webloggerPropertiesRepository.findOrNull()
            .getRegistrationPolicy();
    if (userCount == 0 || !WebloggerProperties.RegistrationPolicy.DISABLED.equals(option)) {
        boolean mustActivate = userCount > 0;
        if (mustActivate) {
            newData.user.setActivationCode(UUID.randomUUID().toString());
            newData.user.setStatus(UserStatus.REGISTERED);
        } else {
            // initial user is the Admin, is automatically enabled.
            newData.user.setStatus(UserStatus.ENABLED);
        }

        User user = new User();
        user.setUserName(newData.user.getUserName());
        user.setDateCreated(Instant.now());

        ResponseEntity re = saveUser(user, newData, null, response, true);

        if (re.getStatusCode() == HttpStatus.OK && mustActivate) {
            UserData data = (UserData) re.getBody();
            if (data != null) {
                emailService.sendUserActivationEmail(data.getUser());
            }
        }
        return re;
    } else {
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }
}

From source file:org.tightblog.ui.restapi.UserController.java

@PostMapping(value = "/tb-ui/authoring/rest/weblog/{weblogId}/memberupdate", produces = "text/plain")
public ResponseEntity updateWeblogMembership(@PathVariable String weblogId, Principal p, Locale locale,
        @RequestBody List<UserWeblogRole> uwrs) throws ServletException {

    Weblog weblog = weblogRepository.findById(weblogId).orElse(null);
    User user = userRepository.findEnabledByUserName(p.getName());
    if (user != null && weblog != null && user.hasEffectiveGlobalRole(GlobalRole.ADMIN)) {

        // must remain at least one admin
        List<UserWeblogRole> owners = uwrs.stream().filter(r -> r.getWeblogRole().equals(WeblogRole.OWNER))
                .collect(Collectors.toList());
        if (owners.size() < 1) {
            return ResponseEntity.badRequest()
                    .body(messages.getMessage("members.oneAdminRequired", null, locale));
        }/*www. j  av  a 2 s .  co  m*/

        // one iteration for each line (user) in the members table
        for (UserWeblogRole uwr : uwrs) {
            if (WeblogRole.NOBLOGNEEDED.equals(uwr.getWeblogRole())) {
                userManager.deleteUserWeblogRole(uwr);
            } else {
                userManager.grantWeblogRole(uwr.getUser(), uwr.getWeblog(), uwr.getWeblogRole());
            }
        }
        String msg = messages.getMessage("members.membersChanged", null, locale);
        return ResponseEntity.ok(msg);
    } else {
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }
}