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.osiam.addons.self_administration.controller.ChangeEmailController.java

/**
 * Validating the confirm token and saving the new email value as primary email if the validation was successful.
 *
 * @param authorization//from w  ww  .j a v a 2 s  .  c o  m
 *            Authorization header with HTTP Bearer authorization and a valid access token
 * @param userId
 *            The user id for the user whom email address should be changed
 * @param confirmationToken
 *            The previously generated confirmation token from the confirmation email
 * @return The HTTP status code and the updated user if successful
 * @throws IOException
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/confirm", produces = "application/json")
public ResponseEntity<String> confirm(@RequestHeader("Authorization") final String authorization,
        @RequestParam("userId") final String userId,
        @RequestParam("confirmToken") final String confirmationToken) throws IOException {

    if (Strings.isNullOrEmpty(confirmationToken)) {
        String message = "The submitted confirmation token is invalid!";
        LOGGER.warn(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }

    User updatedUser;
    Optional<Email> oldEmail;

    try {
        AccessToken accessToken = new AccessToken.Builder(
                SelfAdministrationHelper.extractAccessToken(authorization)).build();
        User user = osiamConnector.getUser(userId, accessToken);

        Extension extension = user.getExtension(Config.EXTENSION_URN);
        final OneTimeToken storedConfirmationToken = OneTimeToken
                .fromString(extension.getFieldAsString(Config.CONFIRMATION_TOKEN_FIELD));

        if (storedConfirmationToken.isExpired(config.getConfirmationTokenTimeout())) {
            UpdateUser updateUser = new UpdateUser.Builder()
                    .deleteExtensionField(extension.getUrn(), Config.CONFIRMATION_TOKEN_FIELD)
                    .deleteExtensionField(extension.getUrn(), Config.TEMP_EMAIL_FIELD).build();
            osiamConnector.updateUser(userId, updateUser, accessToken);

            String message = "The submitted confirmation token is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        if (!storedConfirmationToken.getToken().equals(confirmationToken)) {
            String message = "The submitted confirmation token is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        String newEmail = extension.getField(Config.TEMP_EMAIL_FIELD, ExtensionFieldType.STRING);
        oldEmail = SCIMHelper.getPrimaryOrFirstEmail(user);

        UpdateUser updateUser = getPreparedUserForEmailChange(extension, newEmail, oldEmail.get());

        updatedUser = osiamConnector.updateUser(userId, updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.warn(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        LOGGER.error(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (NoSuchElementException e) {
        String message = "The submitted confirmation token is invalid!";
        LOGGER.warn(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }

    Locale locale = SelfAdministrationHelper.getLocale(updatedUser.getLocale());

    // build the Map with the link for replacement
    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("user", updatedUser);

    try {
        renderAndSendEmailService.renderAndSendEmail("changeemailinfo", config.getFromAddress(),
                oldEmail.get().getValue(), locale, mailVariables);
    } catch (OsiamException e) {
        String message = "Problems creating email for confirming new user email: " + e.getMessage();
        LOGGER.error(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.osiam.addons.self_administration.controller.LostPasswordController.java

private ResponseEntity<String> changePassword(String userId, String authorization, String oneTimePassword,
        String newPassword) throws IOException {

    if (Strings.isNullOrEmpty(oneTimePassword)) {
        String message = "The submitted one time password is invalid!";
        LOGGER.warn(message);/*w  ww. ja v  a 2s. com*/
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }

    AccessToken accessToken = new AccessToken.Builder(
            SelfAdministrationHelper.extractAccessToken(authorization)).build();

    try {

        User user;
        if (Strings.isNullOrEmpty(userId)) {
            user = osiamConnector.getCurrentUser(accessToken);
        } else {
            user = osiamConnector.getUser(userId, accessToken);
        }

        Extension extension = user.getExtension(Config.EXTENSION_URN);
        final OneTimeToken storedOneTimePassword = OneTimeToken
                .fromString(extension.getFieldAsString(Config.ONETIME_PASSWORD_FIELD));

        if (storedOneTimePassword.isExpired(config.getOneTimePasswordTimeout())) {
            UpdateUser updateUser = new UpdateUser.Builder()
                    .deleteExtensionField(extension.getUrn(), Config.ONETIME_PASSWORD_FIELD).build();
            osiamConnector.updateUser(userId, updateUser, accessToken);

            String message = "The submitted one time password is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        if (!storedOneTimePassword.getToken().equals(oneTimePassword)) {
            String message = "The submitted one time password is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        UpdateUser updateUser = new UpdateUser.Builder().updatePassword(newPassword)
                .deleteExtensionField(extension.getUrn(), Config.ONETIME_PASSWORD_FIELD).build();

        User updatedUser = osiamConnector.updateUser(user.getId(), updateUser, accessToken);

        return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
    } catch (OsiamRequestException e) {
        LOGGER.warn(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        LOGGER.error(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (NoSuchElementException e) {
        String message = "The submitted one time password is invalid!";
        LOGGER.warn(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }
}

From source file:org.springframework.boot.actuate.endpoint.mvc.MvcEndpointSecurityInterceptor.java

private void sendFailureResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (request.getUserPrincipal() != null) {
        String roles = StringUtils.collectionToDelimitedString(this.roles, " ");
        response.sendError(HttpStatus.FORBIDDEN.value(),
                "Access is denied. User must have one of the these roles: " + roles);
    } else {//from  ww  w  . jav a 2s  . com
        logUnauthorizedAttempt();
        response.sendError(HttpStatus.UNAUTHORIZED.value(),
                "Full authentication is required to access this resource.");
    }
}

From source file:org.springframework.security.web.access.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(HttpStatus.FORBIDDEN.value());

            // forward to error page.
            RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
            dispatcher.forward(request, response);
        } else {/*from   w  w  w  .  j a  va 2  s. c o m*/
            response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase());
        }
    }
}

From source file:org.springframework.social.cloudplaylists.api.impl.CloudPlaylistsErrorHandler.java

void handleCloudPlaylistsError(HttpStatus statusCode, Map errorDetails) {

    String message = (String) errorDetails.get("error_description");
    HttpStatus httpStatus = statusCode;//w  w w .j  a  v  a2  s . com

    if (httpStatus == HttpStatus.OK) {
        // Should never happen
    } else if (httpStatus == HttpStatus.BAD_REQUEST) {

        String error = (String) errorDetails.get("error");
        String error_description = (String) errorDetails.get("error_description");

        if (error != null && PlaylistUpdateException.class.getName().equals(error)) {
            throw new PlaylistUpdateException(error_description);
        }
        if (error != null && PlaylistCreationException.class.getName().equals(error)) {
            throw new PlaylistCreationException(error_description);
        }

        throw new ResourceNotFoundException("cloudplaylists", message);

    } else if (httpStatus == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("cloudplaylists", message);

    } else if (httpStatus == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("cloudplaylists", message);
    } else if (httpStatus == HttpStatus.FORBIDDEN) {
        String provider = (String) errorDetails.get("provider");
        String error = (String) errorDetails.get("error");
        if (error != null && provider != null && NotConnectedException.class.getName().equals(error)) {
            throw new NotConnectedException(provider);
        }
        if (error != null && provider != null && ExpiredAuthorizationException.class.getName().equals(error)) {
            throw new ExpiredAuthorizationException(provider);
        }
        throw new OperationNotPermittedException("cloudplaylists", message);
    } else if (httpStatus == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("cloudplaylists", message);
    } else if (httpStatus == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("cloudplaylists", message);
    }
}

From source file:org.springframework.social.exfm.api.impl.ExFmErrorHandler.java

void handleExFmError(HttpStatus statusCode, Status status) {

    String message = status.getStatus_text();

    HttpStatus httpStatus = statusCode != HttpStatus.OK ? statusCode
            : HttpStatus.valueOf(Integer.parseInt(status.getStatus_code()));

    if (httpStatus == HttpStatus.OK) {
        // Should never happen
    } else if (httpStatus == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("exfm", message);

    } else if (httpStatus == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("exfm", message);

    } else if (httpStatus == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("exfm", message);
    } else if (httpStatus == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("exfm", message);
    } else if (httpStatus == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("exfm", message);
    } else if (httpStatus == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("exfm", message);
    }//from   w  ww  . j a  va2s .  co  m
}

From source file:org.springframework.social.lastfm.api.impl.LastFmErrorHandler.java

void handleLastFmError(HttpStatus statusCode, Map<Integer, String> errorDetails) {

    String message = errorDetails.values().iterator().next();
    if (statusCode == HttpStatus.OK) {
        // TODO I've just put a single error code in here for now - need to
        // complete with other error codes
        if (errorDetails.containsKey(3)) {
            throw new ResourceNotFoundException("lastfm", message);
        }// ww  w  .jav a  2 s .  c om
        if (errorDetails.containsKey(6)) {
            throw new ResourceNotFoundException("lastfm", message);
        }
        if (errorDetails.containsKey(10)) {
            throw new NotAuthorizedException("lastfm", message);
        }
        if (errorDetails.containsKey(8)) {
            throw new ResourceNotFoundException("lastfm", message);
        }
        if (errorDetails.containsKey(13)) {
            throw new NotAuthorizedException("lastfm", message);
        }

    } else if (statusCode == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("lastfm", message);

    } else if (statusCode == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("lastfm", message);
    } else if (statusCode == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("lastfm", message);
    } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("lastfm", message);
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("lastfm", message);
    }
}

From source file:org.springframework.social.linkedin.api.impl.LinkedInErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    Map<String, Object> errorDetails = extractErrorDetailsFromResponse(response);
    String message = (String) errorDetails.get("message");
    HttpStatus statusCode = response.getStatusCode();
    if (statusCode.equals(HttpStatus.UNAUTHORIZED)) {
        throw new NotAuthorizedException("linkedIn", message);
    } else if (statusCode.equals(HttpStatus.FORBIDDEN)) {
        if (message.contains("Throttle")) {
            throw new RateLimitExceededException("linkedin");
        } else {/*  w w  w  .j a v  a  2s . c  o m*/
            throw new InsufficientPermissionException("linkedin");
        }
    } else if (statusCode.equals(HttpStatus.NOT_FOUND)) {
        throw new ResourceNotFoundException("linkedin", message);
    }

    handleUncategorizedError(response);
}

From source file:org.springframework.social.mixcloud.api.impl.MixcloudErrorHandler.java

/**
 * Examines the error data returned from Mixcloud and throws the most
 * applicable exception./*from w  w  w. ja  v  a  2  s  . c  om*/
 * 
 * @param errorDetails
 *            a Map containing an "error"
 */
void handleMixcloudError(HttpStatus statusCode, SocialException errorDetails) {
    if (statusCode == HttpStatus.OK) {

    } else if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorDetails instanceof UncategorizedApiException) {
            String message = errorDetails.getMessage();
            if (AUTHORIZATION_FAILURE_MESSAGES.contains(message)) {
                throw new NotAuthorizedException("mixcloud", message);
            } else {
                throw errorDetails;

            }
        } else {
            throw errorDetails;
        }

    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        throw new NotAuthorizedException("mixcloud", errorDetails.getMessage());
    } else if (statusCode == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("mixcloud", errorDetails.getMessage());
    } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("mixcloud", errorDetails.getMessage());
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("mixcloud", errorDetails.getMessage());
    }
}

From source file:org.springframework.social.soundcloud.api.impl.SoundCloudErrorHandler.java

/**
 * Examines the error data returned from SoundCloud and throws the most applicable exception.
 * @param errorDetails a Map containing an "error_message"
 *//*from  w  w w.j a  v  a2s .c o  m*/
void handleSoundCloudError(HttpStatus statusCode, List<Map<String, String>> errorDetailsList) {
    // Can't trust the type to be useful. It's often OAuthException, even for things not OAuth-related. 
    // Can rely only on the message (which itself isn't very consistent).
    List<String> messages = new ArrayList<String>();
    for (Map<String, String> errorDetails : errorDetailsList) {
        String message = errorDetails.get("error_message");
        messages.add(message);
    }
    String message = constructMessage(messages);

    if (statusCode == HttpStatus.OK) {

    } else if (statusCode == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("soundcloud", message);

    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("soundcloud", message);

    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (isMessageStartsWithText(messages, "invalid_token")) {
            handleInvalidAccessToken(message);
        }
        throw new NotAuthorizedException("soundcloud", message);
    } else if (statusCode == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("soundcloud", message);
    } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("soundcloud", message);
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("soundcloud", message);
    }
}