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.mitre.uma.web.ResourceSetRegistrationEndpoint.java

@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String readResourceSet(@PathVariable("id") Long id, Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
        m.addAttribute("code", HttpStatus.NOT_FOUND);
        m.addAttribute("error", "not_found");
        return JsonErrorView.VIEWNAME;
    } else {//w  w w. j  a va2 s  .com

        rs = validateScopes(rs);

        if (!auth.getName().equals(rs.getOwner())) {

            logger.warn("Unauthorized resource set request from wrong user; expected " + rs.getOwner() + " got "
                    + auth.getName());

            // it wasn't issued to this user
            m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
            return JsonErrorView.VIEWNAME;
        } else {
            m.addAttribute(JsonEntityView.ENTITY, rs);
            return ResourceSetEntityView.VIEWNAME;
        }

    }

}

From source file:io.lavagna.web.helper.PermissionMethodInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    ExpectPermission expectPermission = ExpectPermission.Helper.getAnnotation(handler);
    if (expectPermission == null) {
        return true;
    }//from  w w  w  . j a va 2s  . c  o  m

    Class<? extends OwnershipChecker> ownershipChecker = expectPermission.ownershipChecker();

    UserWithPermission user = UserSession.fetchFromRequest(request, userService);

    // check the base permission
    if (user.getBasePermissions().containsKey(expectPermission.value())) {
        return true;
    }

    // check if the resource has a custom ownership checker (the user must
    // have a read permission)
    if (NoOpOwnershipChecker.class != ownershipChecker && user.getBasePermissions().containsKey(Permission.READ)
            && context.getBean(expectPermission.ownershipChecker()).hasOwnership(request, user)) {
        return true;
    }
    //

    // TODO: in some cases the user pass a list of ids as a _body_. This
    // kind of bulk operation will need to ensure the correctness with the
    // right filter.

    // project level check
    Set<String> projectIds = extractProjectIdsFromRequestUri(request.getRequestURI(), projectService);
    if (allProjectsIdsHavePermission(projectIds, user, expectPermission.value())) {
        return true;
    }

    // project level ownership check
    if (NoOpOwnershipChecker.class != ownershipChecker
            && allProjectsIdsHavePermission(projectIds, user, Permission.READ)
            && context.getBean(expectPermission.ownershipChecker()).hasOwnership(request, user)) {
        return true;
    }

    response.sendError(HttpStatus.FORBIDDEN.value());
    return false;
}

From source file:org.echocat.marquardt.authority.spring.SpringAuthorityController.java

@ExceptionHandler(ClientNotAuthorizedException.class)
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Client is not authorized.")
public void handleClientNotAuthorizedException(final ClientNotAuthorizedException ex) {
    LOGGER.info(ex.getMessage());/*from   ww  w . j a va  2 s.  c o m*/
}

From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java

public String getToken(String user, String password) {
    LOG.debug("Get SugarCRM token");

    if (null == user || null == password || user.isEmpty() || password.isEmpty()) {
        LOG.info("User and password must be provided when creating token");
        throw new BadRequestException(ERR_MISSING_USER_PASSWORD,
                "User and password must be provided when creating token");
    }//from www . ja  v a 2 s. c om

    String data = String.format(
            "{\"user_auth\":{\"user_name\":\"%s\",\"password\":\"%s\",\"version\":\"%s\"},\"application_name\":\"%s\"}",
            this.user, md5Hash(this.password), "1.0", "Meeter");
    //LOG.debug("Send login with data:{}", data);

    this.token = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
            LOG.debug("Sending login request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm());
        }
    }, new ResponseExtractor<String>() {
        @Override
        public String extractData(ClientHttpResponse clientHttpResponse) throws IOException {
            LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value());

            if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                SugarCRMLoginResponse response = MAPPER.readValue(clientHttpResponse.getBody(),
                        SugarCRMLoginResponse.class);
                LOG.debug("Response:{}", response);
                if (!response.hasError()) {
                    return response.getId();
                } else if (response.isInvalidCredentials()) {
                    LOG.info("SugarCRM login failed with invalid credentials",
                            new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                    throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN,
                            "SugarCRM login failed with invalid credentials");
                } else {
                    LOG.info("SugarCRM login failed with unknown reason:{}",
                            new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                    throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN,
                            "SugarCRM login failed with unknown reason");
                }
            } else {
                // If the SugarCRM does not respond with 200 throw http 503
                LOG.warn("SugarCRM is responding with http code:{}",
                        clientHttpResponse.getStatusCode().value());
                throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE,
                        "SugarCRM request failed");
            }
        }
    }, "login", "json", "json", data);

    LOG.debug("Got token:{}", this.token);

    return this.token;
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationFlowTest() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();//  w w  w. j  a  v a2 s  .co m

    // Calling protected remotelog service
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    // Try without token first - It should be 'Forbidden'
    // http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate      
    ResponseEntity<String> responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entityRemotelog, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode());

    // Try now with the CSRF token - It should work well
    // This implies passing JSESSIONID and CSRF Token
    headers.set(DEFAULT_CSRF_HEADER_NAME, loginInfo.getXsrfToken());
    entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityRemotelog, String.class);
    assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode());

    // Calling here logout
    builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + basicAuthenticationLogoutEndpointPath);
    HttpEntity<Void> entityLogout = new HttpEntity<Void>(headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityLogout, String.class);
    assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode());

    // Try to call remotelog again (after logout)
    // This implies passing JSESSIONID and CSRF Token - We expect this not to work as the CSRF token has been removed and the session invalidated
    entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityRemotelog, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.TokenAdminEndpointsIntegrationTests.java

@Test
@OAuth2ContextConfiguration// w  ww.  j av a  2 s. c  o m
public void testUserCannotListTokensOfClient() throws Exception {
    assertEquals(HttpStatus.FORBIDDEN, serverRunning.getForString("/oauth/clients/app/tokens").getStatusCode());
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

@RequestMapping(value = "/identifier", method = RequestMethod.PUT)
@ResponseBody/*from ww w.j av a 2s .  c o  m*/
public ResponseEntity<String> mergePatients(@RequestBody String mergeMessage, HttpServletRequest request,
        HttpServletResponse response) {
    Map<String, String> postUpdateIdentifiers = null;
    Map<String, String> preUpdateIdentifiers = null;

    HttpSession httpSession = request.getSession();
    if (Context.isAuthenticated()) {
        NodeList node = identifyMessageType(mergeMessage);
        String typeName = node.item(0).getTextContent();

        postUpdateIdentifiers = identifyPostUpdateIdentifiers(mergeMessage);
        preUpdateIdentifiers = identifyPreUpdateIdentifiers(mergeMessage);

        if (typeName.equals("JOIN")) {
            Object httpResponse = mergePatient(postUpdateIdentifiers, preUpdateIdentifiers);
            response.setStatus((Integer) httpResponse);

            if (response.equals(HttpServletResponse.SC_OK)) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Patient.merged");
                validatePostidentifiers(postUpdateIdentifiers);

                return new ResponseEntity<String>(HttpStatus.OK);
            } else {
                return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);

            }
        } else if (typeName.equals("LEAVE")) {
            Object httpResponse = restorePatient(postUpdateIdentifiers, preUpdateIdentifiers);
            response.setStatus((Integer) httpResponse);

            if (response.equals(HttpServletResponse.SC_OK)) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Patient.restored");
                validatePostidentifiers(postUpdateIdentifiers);

                return new ResponseEntity<String>(HttpStatus.OK);
            } else {
                return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }
    return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
}

From source file:org.trustedanalytics.metadata.parser.MetadataParserIT.java

@Test
public void parseMetadata_accessForbidden() throws URISyntaxException, IOException, ServletException {

    authorizationAlways(false);//from   www.  jav a2 s  .  co m

    request.setTitle("title");
    request.setId("1234");
    request.setIdInObjectStore(idInStore);
    request.setSource(source);
    request.setCallbackUrl(new URI(baseUrl + "/callbacks/" + request.getId()));
    request.setOrgUUID(TEST_ORG_UUID);
    request.setPublicRequest(false);

    assertThat(postRequest(request).getStatusCode(), equalTo(HttpStatus.FORBIDDEN));

    verify(authorization).checkAccess(any(HttpServletRequest.class), eq(TEST_ORG_UUID));
}

From source file:net.maritimecloud.identityregistry.controllers.EntityController.java

/**
 * Updates an entity/*from w w w.jav a 2s. co m*/
 *
 * @return a reply...
 * @throws McBasicRestException
 */
protected ResponseEntity<?> updateEntity(HttpServletRequest request, String orgMrn, String entityMrn, T input)
        throws McBasicRestException {
    if (!entityMrn.equals(input.getMrn())) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                request.getServletPath());
    }
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being updated belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(entityMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        T entity = this.entityService.getByMrn(entityMrn);
        if (entity == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND,
                    request.getServletPath());
        }
        if (entity.getIdOrganization().compareTo(org.getId()) == 0) {
            input.selectiveCopyTo(entity);
            this.entityService.save(entity);
            return new ResponseEntity<>(HttpStatus.OK);
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:de.steilerdev.myVerein.server.controller.admin.UserManagementController.java

/**
 * If a modification on a division needs to be stored durable, this function is invoked by POSTing the parameters to the URI /api/admin/user.
 * @param firstName The first name of the user.
 * @param lastName The last name of the user.
 * @param email The email (unique identifier) of the user.
 * @param birthday The birthday of the user (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param password The initial password of a new user (Only allowed for a new user).
 * @param gender The gender of the user.
 * @param street The street of the user's address.
 * @param streetNumber The street number of the user's address.
 * @param zip The zip code of the user's address.
 * @param city The city of the user's address.
 * @param country The country of the user.
 * @param activeMemberSince The date, when the user became an active member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param passiveMemberSince The date, when the user became a passive member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param resignationDate The date, when the user resigned (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param iban The IBAN of the user's bank account.
 * @param bic The BIC of the user's bank account.
 * @param divisions A comma seperated list of divisions, the user is part of.
 * @param userFlag If it is a new user, the user flag is "true", otherwise it is holding the identifier (email) of the user, in case it changed.
 * @param parameters The complete map of all parameters, containing the custom user fields.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *//*from  w w  w  . ja  v a  2  s .  co  m*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveUser(@RequestParam String firstName, @RequestParam String lastName,
        @RequestParam String email, @RequestParam String birthday, @RequestParam String password,
        @RequestParam(required = false) String gender, @RequestParam String street,
        @RequestParam String streetNumber, @RequestParam String zip, @RequestParam String city,
        @RequestParam String country, @RequestParam String activeMemberSince,
        @RequestParam String passiveMemberSince, @RequestParam String resignationDate,
        @RequestParam String iban, @RequestParam String bic, @RequestParam String divisions,
        @RequestParam String userFlag, @RequestParam Map<String, String> parameters,
        @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Starting to save a user.");
    User userObject;

    logger.debug("[" + currentUser + "] Loading user");

    if (email.isEmpty() || userFlag.isEmpty()) {
        logger.warn("[" + currentUser + "] The email/user flag can not be empty");
        return new ResponseEntity<>("The email can not be empty", HttpStatus.BAD_REQUEST);
    } else if (userFlag.equals("true")) {
        logger.info("[" + currentUser + "] A new user is created using the email " + email);
        if (userRepository.findByEmail(email) == null) {
            userObject = new User();
            if (password.isEmpty()) {
                logger.warn(
                        "[" + currentUser + "] The password of the new user " + email + " can not be empty");
                return new ResponseEntity<>("The password can not be empty", HttpStatus.BAD_REQUEST);
            } else {
                userObject.setPassword(password);
            }
        } else {
            logger.warn("[" + currentUser + "] A user with the given email " + email + " already exists");
            return new ResponseEntity<>("A user with the given email already exists.", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.info("[" + currentUser + "] An existing user " + userFlag + " is modified");
        if ((userObject = userRepository.findByEmail(userFlag)) == null) {
            logger.warn("[{}] Unable to find existing user object", currentUser);
            return new ResponseEntity<>("Unable to retrieve the user", HttpStatus.BAD_REQUEST);
        } else if (!userObject.getEmail().equals(email) && userRepository.findByEmail(email) != null) {
            logger.warn("[{}] The new email {} is already taken", currentUser, email);
            return new ResponseEntity<>("The new email is already taken", HttpStatus.BAD_REQUEST);
        }
    }

    logger.debug("[" + currentUser + "] Checking permissions");

    if (!currentUser.isAllowedToAdministrate(userObject, divisionRepository)) {
        logger.warn("[" + currentUser + "] The user is not allowed to save the user");
        return new ResponseEntity<>("You are not allowed to perform these changes.", HttpStatus.FORBIDDEN);
    }

    logger.debug("[" + currentUser + "] Parsing parameters and updating user");

    if (firstName.isEmpty() || lastName.isEmpty()) {
        logger.warn("[" + currentUser + "] Required parameter missing");
        return new ResponseEntity<>("Required parameter missing", HttpStatus.BAD_REQUEST);
    }
    userObject.setFirstName(firstName);
    userObject.setLastName(lastName);
    userObject.setEmail(email);

    if (!birthday.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing birthday for " + userObject.getEmail());
        try {
            userObject.setBirthday(LocalDate.parse(birthday, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + birthday + ")");
            return new ResponseEntity<>("Wrong date format within birthday field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing birthday field for " + userObject.getEmail());
        userObject.setBirthday(null);
    }

    if (gender != null && !gender.isEmpty() && !gender.equals("default")) {
        logger.debug("[" + currentUser + "] Parsing gender for " + userObject.getEmail());
        try {
            userObject.setGender(User.Gender.valueOf(gender));
        } catch (IllegalArgumentException e) {
            logger.warn("[" + currentUser + "] Unable to parse gender: " + e.getMessage());
            return new ResponseEntity<>("Unable to parse gender", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing gender field for " + userObject.getEmail());
        userObject.setGender(null);
    }

    userObject.setStreet(street);
    userObject.setStreetNumber(streetNumber);
    userObject.setZipCode(zip);
    userObject.setCity(city);
    userObject.setCountry(country);

    if (!activeMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing active member field for " + userObject.getEmail());
        try {
            userObject
                    .setActiveSince(LocalDate.parse(activeMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + activeMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within active member field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing active member field for " + userObject.getEmail());
        userObject.setActiveSince(null);
    }

    if (!passiveMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing passive member field for " + userObject.getEmail());
        try {
            userObject.setPassiveSince(
                    LocalDate.parse(passiveMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + passiveMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within passive member field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing passive member field for " + userObject.getEmail());
        userObject.setPassiveSince(null);
    }

    if (!resignationDate.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing resignation date field for " + userObject.getEmail());
        try {
            userObject.setResignationDate(
                    LocalDate.parse(resignationDate, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + resignationDate + ")");
            return new ResponseEntity<>("Wrong date format within resignation date field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing resignation date field for " + userObject.getEmail());
        userObject.setResignationDate(null);
    }

    userObject.setIban(iban);
    userObject.setBic(bic);

    if (!divisions.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing divisions for " + userObject.getEmail());
        String[] divArray = divisions.split(",");
        List<Division> divisionList = new ArrayList<>();
        for (String division : divArray) {
            Division div = divisionRepository.findByName(division);
            if (div == null) {
                logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")");
                return new ResponseEntity<>("Division " + division + " does not exist", HttpStatus.BAD_REQUEST);
            } else {
                divisionList.add(div);
            }
        }
        userObject.replaceDivisions(divisionRepository, eventRepository, divisionList);
    } else {
        logger.debug("[" + currentUser + "] Clearing divisions for " + userObject.getEmail());
        userObject.replaceDivisions(divisionRepository, eventRepository, (List<Division>) null);
    }

    logger.debug("[" + currentUser + "] Parsing and setting custom user fields");
    userObject.setCustomUserField(parameters.keySet().parallelStream()
            .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty()) //Filtering all custom user fields, which are not empty
            .collect(Collectors.toMap(key -> key.substring(4), key -> parameters.get(key).trim()))); //Creating map of all fields

    logger.debug("[" + currentUser + "] Saving user " + userObject.getEmail());

    try {
        logger.debug("[{}] Saving user {}", currentUser, userObject);
        userRepository.save(userObject);
        logger.info("[" + currentUser + "] Successfully saved user " + userObject.getEmail());
        return new ResponseEntity<>("Successfully saved user", HttpStatus.OK);
    } catch (ConstraintViolationException e) {
        logger.warn("[" + currentUser + "] A database constraint was violated while saving the user: "
                + e.getMessage());
        return new ResponseEntity<>("A database constraint was violated while saving the user.",
                HttpStatus.BAD_REQUEST);
    }
}