List of usage examples for org.springframework.http HttpStatus FORBIDDEN
HttpStatus FORBIDDEN
To view the source code for org.springframework.http HttpStatus FORBIDDEN.
Click Source Link
From source file:org.springside.examples.bootapi.functional.BookEndpointTest.java
@Test public void applyRequestWithError() { // token//from w w w . j av a2s.co m ResponseEntity<String> response = restTemplate.getForEntity(resourceUrl + "/{id}/request", String.class, 1L); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); ErrorResult errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class); assertThat(errorResult.code).isEqualTo(ErrorCode.NO_TOKEN.code); Book book = bookDao.findOne(1L); assertThat(book.borrower).isNull(); // token response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 1L, "abc"); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class); assertThat(errorResult.code).isEqualTo(ErrorCode.UNAUTHORIZED.code); book = bookDao.findOne(1L); assertThat(book.borrower).isNull(); // String token = login("calvin.xiao@springside.io"); response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 1L, token); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class); assertThat(errorResult.code).isEqualTo(ErrorCode.BOOK_OWNERSHIP_WRONG.code); book = bookDao.findOne(1L); assertThat(book.borrower).isNull(); logout(token); // token = login("calvin.xiao@springside.io"); response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 3L, token); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 3L, token); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class); assertThat(errorResult.code).isEqualTo(ErrorCode.BOOK_STATUS_WRONG.code); // ? response = restTemplate.getForEntity(resourceUrl + "/{id}/cancel?token={token}", String.class, 3L, token); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); logout(token); }
From source file:de.sainth.recipe.backend.rest.controller.RecipeController.java
@Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping(value = "{id}", method = RequestMethod.PUT) HttpEntity<Recipe> update(@PathVariable("id") Long id, @Valid @RequestBody Recipe recipe) { if (id.equals(recipe.getId())) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof RecipeManagerAuthenticationToken) { RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication; Recipe existingRecipe = repository.findOne(id); if (existingRecipe != null && (ROLE_ADMIN.name().equals(token.getRole()) || existingRecipe.getAuthor().getId().equals(token.getPrincipal()))) { repository.save(recipe); return new ResponseEntity<>(recipe, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.FORBIDDEN); }/*from w w w . ja va 2 s .c o m*/ } } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); }
From source file:net.maritimecloud.identityregistry.controllers.RoleController.java
/** * Returns info about the role identified by the given ID * * @return a reply.../*from ww w. j ava 2 s. co m*/ * @throws McBasicRestException */ @RequestMapping(value = "/api/org/{orgMrn}/role/{roleId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseBody @PreAuthorize("hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)") public ResponseEntity<Role> getRole(HttpServletRequest request, @PathVariable String orgMrn, @PathVariable Long roleId) throws McBasicRestException { Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { Role role = this.roleService.getById(roleId); if (role == null) { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ROLE_NOT_FOUND, request.getServletPath()); } if (role.getIdOrganization().compareTo(org.getId()) == 0) { return new ResponseEntity<>(role, 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:org.trustedanalytics.user.invite.RestErrorHandler.java
@ResponseBody @ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(AccessDeniedException.class) public String accessDenied(Exception e) throws IOException { return e.getMessage(); }
From source file:org.mitre.uma.web.PolicyAPI.java
/** * Delete the indicated resource set//www .ja v a 2 s. c om * @param rsid * @param m * @param auth * @return */ @RequestMapping(value = "/{rsid}", method = RequestMethod.DELETE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE) public String deleteResourceSet(@PathVariable(value = "rsid") Long rsid, Model m, Authentication auth) { ResourceSet rs = resourceSetService.getById(rsid); if (rs == null) { m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } if (!rs.getOwner().equals(auth.getName())) { logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got " + auth.getName()); // authenticated user didn't match the owner of the resource set m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } resourceSetService.remove(rs); m.addAttribute(HttpCodeView.CODE, HttpStatus.NO_CONTENT); return HttpCodeView.VIEWNAME; }
From source file:org.craftercms.profile.controllers.rest.ExceptionHandlers.java
@ExceptionHandler(DisabledProfileException.class) public ResponseEntity<Object> handleDisabledProfileException(DisabledProfileException e, WebRequest request) { return handleExceptionInternal(e, HttpStatus.FORBIDDEN, ErrorCode.DISABLED_PROFILE, request); }
From source file:com.basicservice.controller.UserController.java
@RequestMapping(value = "/register", method = RequestMethod.POST) public ResponseEntity<String> register(HttpServletRequest request, @RequestParam(value = "name") String name, @RequestParam(value = "email") EmailValidatedString email, @RequestParam(value = "password") String password) { if (email == null || email.getValue() == null || password == null) { return new ResponseEntity<String>(HttpStatus.FORBIDDEN); }/*from w ww . ja v a2 s. c o m*/ LOG.debug("Got register request: email:" + email.getValue() + ", pass:" + password + ", name:" + name); User user = null; try { user = userService.register(name, email.getValue(), password); } catch (UserRegistrationException e) { if (e.getReason() == UserRegistrationException.reason.EMAIL_EXISTS) { return new ResponseEntity<String>(HttpStatus.FORBIDDEN); } } if (user == null) { return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } LOG.debug("Preparing to save user to db"); final String id = userService.save(user); if (id != null) { String from = Constants.REGISTRATION_FROM_ADDRESS; String to = email.getValue(); Locale locale = LocaleContextHolder.getLocale(); String subject = messageLocalizationService.getMessage(Constants.MLS_REGISTRATION_CONFIRMATION_SUBJECT, locale); Object[] args = new String[1]; String path = Utils.getBasicPath(request); ConfirmationString cs = confirmationEmailService.getConfirmationString(user.getId()); URI uri = new UriTemplate("{requestUrl}/api/users/registrationConfirmation/?key={key}").expand(path, cs.getKey()); args[0] = uri.toASCIIString(); String messageHtml = messageLocalizationService.getMessage(Constants.MLS_REGISTRATION_CONFIRMATION_HTML, args, locale); try { mailService.sendEmail(from, to, subject, messageHtml); } catch (Exception e) { LOG.debug("Failed to send confirmation email to: " + to, e); } } final HttpHeaders headers = new HttpHeaders(); headers.add("Set-Cookie", Constants.AUTHENTICATED_USER_ID_COOKIE + "=" + id + "; Path=/"); return new ResponseEntity<String>(headers, HttpStatus.CREATED); }
From source file:net.maritimecloud.identityregistry.controllers.EntityController.java
/** * Returns info about the entity identified by the given ID * * @return a reply...// ww w .j a v a2 s.c o m * @throws McBasicRestException */ protected ResponseEntity<T> getEntity(HttpServletRequest request, String orgMrn, String entityMrn) throws McBasicRestException { Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { // Check that the entity being queried 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) { return new ResponseEntity<>(entity, 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:org.syncope.core.rest.AuthenticationTestITCase.java
@Test public void testUserSchemaAuthorization() { // 0. create a role that can only read schemas RoleTO authRoleTO = new RoleTO(); authRoleTO.setName("authRole"); authRoleTO.setParent(8L);/*from ww w. j a va 2s.c o m*/ authRoleTO.addEntitlement("SCHEMA_READ"); authRoleTO = restTemplate.postForObject(BASE_URL + "role/create", authRoleTO, RoleTO.class); assertNotNull(authRoleTO); // 1. create a schema (as admin) SchemaTO schemaTO = new SchemaTO(); schemaTO.setName("authTestSchema"); schemaTO.setMandatoryCondition("false"); schemaTO.setType(SchemaType.String); SchemaTO newSchemaTO = restTemplate.postForObject(BASE_URL + "schema/user/create", schemaTO, SchemaTO.class); assertEquals(schemaTO, newSchemaTO); // 2. create an user with the role created above (as admin) UserTO userTO = UserTestITCase.getSampleTO("auth@test.org"); MembershipTO membershipTO = new MembershipTO(); membershipTO.setRoleId(authRoleTO.getId()); AttributeTO testAttributeTO = new AttributeTO(); testAttributeTO.setSchema("testAttribute"); testAttributeTO.addValue("a value"); membershipTO.addAttribute(testAttributeTO); userTO.addMembership(membershipTO); userTO = restTemplate.postForObject(BASE_URL + "user/create", userTO, UserTO.class); assertNotNull(userTO); // 3. read the schema created above (as admin) - success schemaTO = restTemplate.getForObject(BASE_URL + "schema/user/read/authTestSchema.json", SchemaTO.class); assertNotNull(schemaTO); // 4. read the schema created above (as user) - success PreemptiveAuthHttpRequestFactory requestFactory = ((PreemptiveAuthHttpRequestFactory) restTemplate .getRequestFactory()); ((DefaultHttpClient) requestFactory.getHttpClient()).getCredentialsProvider().setCredentials( requestFactory.getAuthScope(), new UsernamePasswordCredentials(userTO.getUsername(), "password123")); schemaTO = restTemplate.getForObject(BASE_URL + "schema/user/read/authTestSchema.json", SchemaTO.class); assertNotNull(schemaTO); // 5. update the schema create above (as user) - failure HttpClientErrorException exception = null; try { restTemplate.postForObject(BASE_URL + "schema/role/update", schemaTO, SchemaTO.class); } catch (HttpClientErrorException e) { exception = e; } assertNotNull(exception); assertEquals(HttpStatus.FORBIDDEN, exception.getStatusCode()); // reset admin credentials for restTemplate super.setupRestTemplate(); userTO = restTemplate.getForObject(BASE_URL + "user/read/{userId}.json", UserTO.class, userTO.getId()); assertNotNull(userTO); assertNotNull(userTO.getLastLoginDate()); assertEquals(Integer.valueOf(0), userTO.getFailedLogins()); }