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:de.sainth.recipe.backend.rest.controller.CookbookController.java
@Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping("{id}") HttpEntity<Cookbook> get(@PathVariable("id") Long id) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof RecipeManagerAuthenticationToken) { RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication; Cookbook cookbook = repository.findOne(id); if (cookbook == null) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); }// w ww . j a v a 2s. co m if (ROLE_ADMIN.name().equals(token.getRole()) || token.getPrincipal().equals(cookbook.getAuthor().getId())) { return new ResponseEntity<>(cookbook, HttpStatus.OK); } } return new ResponseEntity<>(HttpStatus.FORBIDDEN); }
From source file:org.mitre.oauth2.web.RevocationEndpoint.java
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_CLIENT')") @RequestMapping("/" + URL) public String revoke(@RequestParam("token") String tokenValue, @RequestParam(value = "token_type_hint", required = false) String tokenType, Principal principal, Model model) {//from w w w. ja v a 2 s. c o m // This is the token as passed in from OAuth (in case we need it some day) //OAuth2AccessTokenEntity tok = tokenServices.getAccessToken((OAuth2Authentication) principal); OAuth2Request authRequest = null; if (principal instanceof OAuth2Authentication) { // if the client is acting on its own behalf (the common case), pull out the client authorization request authRequest = ((OAuth2Authentication) principal).getOAuth2Request(); } try { // check and handle access tokens first OAuth2AccessTokenEntity accessToken = tokenServices.readAccessToken(tokenValue); if (authRequest != null) { // client acting on its own, make sure it owns the token if (!accessToken.getClient().getClientId().equals(authRequest.getClientId())) { // trying to revoke a token we don't own, throw a 403 model.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } } // if we got this far, we're allowed to do this tokenServices.revokeAccessToken(accessToken); model.addAttribute(HttpCodeView.CODE, HttpStatus.OK); return HttpCodeView.VIEWNAME; } catch (InvalidTokenException e) { // access token wasn't found, check the refresh token try { OAuth2RefreshTokenEntity refreshToken = tokenServices.getRefreshToken(tokenValue); if (authRequest != null) { // client acting on its own, make sure it owns the token if (!refreshToken.getClient().getClientId().equals(authRequest.getClientId())) { // trying to revoke a token we don't own, throw a 403 model.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } } // if we got this far, we're allowed to do this tokenServices.revokeRefreshToken(refreshToken); model.addAttribute(HttpCodeView.CODE, HttpStatus.OK); return HttpCodeView.VIEWNAME; } catch (InvalidTokenException e1) { // neither token type was found, simply say "OK" and be on our way. model.addAttribute(HttpCodeView.CODE, HttpStatus.OK); return HttpCodeView.VIEWNAME; } } }
From source file:de.steilerdev.myVerein.server.controller.admin.SettingsController.java
/** * This function is gathering the current settings of the application. The function is invoked by GETting the URI /api/admin/settings. * @param currentUser The currently logged in user. * @return An HTTP response with a status code. If an error occurred a error code is returned, otherwise the map of all available settings is returned. *//*from w w w . jav a 2 s .c om*/ @RequestMapping(method = RequestMethod.GET, produces = "application/json") public ResponseEntity<Map<String, Object>> loadSettings(@CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Starting to load settings"); Map<String, Object> settings; if (!currentUser.isAdmin()) { logger.warn("[" + currentUser + "] The user is a non-admin and tries to access the settings"); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } else if (!currentUser.isSuperAdmin()) { logger.info("[" + currentUser + "] The user is a non-superadmin and is accessing the settings"); settings = new HashMap<>(); settings.put("administrationNotAllowedMessage", "You are not the super admin, and therefore you cannot adjust system settings."); } else { logger.debug("[" + currentUser + "] Loading settings for super admin"); settings = Settings.loadSettings(settingsRepository).getSettingsMap(); if (gridFSRepository.findClubLogo() != null) { logger.debug("[" + currentUser + "] The club logo is available"); settings.put("clubLogoAvailable", true); } } settings.put("currentAdmin", currentUser.getSendingObjectOnlyEmailNameId()); logger.info("[" + currentUser + "] Finished loading settings"); return new ResponseEntity<>(settings, HttpStatus.OK); }
From source file:app.api.swagger.SwaggerConfig.java
private List<ResponseMessage> defaultHttpResponses() { final List<ResponseMessage> results = new ArrayList<ResponseMessage>(); results.add(response(HttpStatus.FORBIDDEN, null)); results.add(response(HttpStatus.UNAUTHORIZED, null)); results.add(response(HttpStatus.BAD_REQUEST, null)); results.add(response(HttpStatus.UNPROCESSABLE_ENTITY, ERROR_MODEL)); return results; }
From source file:de.hska.ld.core.controller.RoleControllerIntegrationTest.java
@Test public void testDeleteRoleUsesHttpForbiddenOnAuthorizationFailure() throws Exception { Role role = roleService.save(newRole()); HttpResponse response = UserSession.user().delete(RESOURCE_ROLE + "/" + role.getId(), null); Assert.assertEquals(HttpStatus.FORBIDDEN, ResponseHelper.getStatusCode(response)); }
From source file:org.mitre.openid.connect.web.UserInfoEndpoint.java
/** * Get information about the user as specified in the accessToken included in this request *//*from w w w .ja v a2s . com*/ @PreAuthorize("hasRole('ROLE_USER') and #oauth2.hasScope('" + SystemScopeService.OPENID_SCOPE + "')") @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE, UserInfoJWTView.JOSE_MEDIA_TYPE_VALUE }) public String getInfo(@RequestParam(value = "claims", required = false) String claimsRequestJsonString, @RequestHeader(value = HttpHeaders.ACCEPT, required = false) String acceptHeader, OAuth2Authentication auth, Model model) { if (auth == null) { logger.error("getInfo failed; no principal. Requester is not authorized."); model.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } String username = auth.getName(); UserInfo userInfo = userInfoService.getByUsernameAndClientId(username, auth.getOAuth2Request().getClientId()); if (userInfo == null) { logger.error("getInfo failed; user not found: " + username); model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } model.addAttribute(UserInfoView.SCOPE, auth.getOAuth2Request().getScope()); model.addAttribute(UserInfoView.AUTHORIZED_CLAIMS, auth.getOAuth2Request().getExtensions().get("claims")); if (!Strings.isNullOrEmpty(claimsRequestJsonString)) { model.addAttribute(UserInfoView.REQUESTED_CLAIMS, claimsRequestJsonString); } model.addAttribute(UserInfoView.USER_INFO, userInfo); // content negotiation // start off by seeing if the client has registered for a signed/encrypted JWT from here ClientDetailsEntity client = clientService.loadClientByClientId(auth.getOAuth2Request().getClientId()); model.addAttribute(UserInfoJWTView.CLIENT, client); List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader); MediaType.sortBySpecificityAndQuality(mediaTypes); if (client.getUserInfoSignedResponseAlg() != null || client.getUserInfoEncryptedResponseAlg() != null || client.getUserInfoEncryptedResponseEnc() != null) { // client has a preference, see if they ask for plain JSON specifically on this request for (MediaType m : mediaTypes) { if (!m.isWildcardType() && m.isCompatibleWith(UserInfoJWTView.JOSE_MEDIA_TYPE)) { return UserInfoJWTView.VIEWNAME; } else if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) { return UserInfoView.VIEWNAME; } } // otherwise return JWT return UserInfoJWTView.VIEWNAME; } else { // client has no preference, see if they asked for JWT specifically on this request for (MediaType m : mediaTypes) { if (!m.isWildcardType() && m.isCompatibleWith(MediaType.APPLICATION_JSON)) { return UserInfoView.VIEWNAME; } else if (!m.isWildcardType() && m.isCompatibleWith(UserInfoJWTView.JOSE_MEDIA_TYPE)) { return UserInfoJWTView.VIEWNAME; } } // otherwise return JSON return UserInfoView.VIEWNAME; } }
From source file:org.openbaton.nfvo.api.exceptions.GlobalExceptionHandler.java
@ExceptionHandler({ UnauthorizedUserException.class }) @ResponseStatus(value = HttpStatus.FORBIDDEN) protected ResponseEntity<Object> handleUnauthorized(Exception e, WebRequest request) { if (log.isDebugEnabled()) { log.error("Exception was thrown -> Return message: " + e.getMessage(), e); } else {/*from w w w .j a v a 2s.com*/ log.error("Exception was thrown -> Return message: " + e.getMessage()); } ExceptionResource exc = new ExceptionResource("Unauthorized exception", e.getMessage()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(e, exc, headers, HttpStatus.FORBIDDEN, request); }
From source file:com.himanshu.poc.springbootsec.SampleControllerSecurityTestIT.java
@Test public void testSecureGetWithToken() { ResponseEntity<String> response = new TestRestTemplate("Himanshu", "Bhardwaj") .getForEntity(url.concat("/secure/generate/token/Himanshu"), String.class); logger.info("Response is :->" + response); String tokenReceived = response.getBody(); Assert.assertThat(response.getStatusCode(), Matchers.equalTo(HttpStatus.OK)); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic ".concat(generateAuthorizationToken(tokenReceived))); HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers); ResponseEntity<String> response2 = new TestRestTemplate().exchange(url.concat("/secure/sample/test"), HttpMethod.GET, requestEntity, String.class); logger.info("Response2 is :->" + response2); Assert.assertThat(response2.getStatusCode(), Matchers.equalTo(HttpStatus.OK)); ResponseEntity<String> response3 = new TestRestTemplate() .exchange(url.concat("/secure/sample/test/forbidden"), HttpMethod.GET, requestEntity, String.class); logger.info("Response3 is :->" + response3); Assert.assertThat(response3.getStatusCode(), Matchers.equalTo(HttpStatus.FORBIDDEN)); }
From source file:org.mitre.uma.web.ClaimsAPI.java
@RequestMapping(value = "/{rsid}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE) public String getClaimsForResourceSet(@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; }// ww w. j av a 2 s .c o m if (!rs.getOwner().equals(auth.getName())) { // authenticated user didn't match the owner of the resource set m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } m.addAttribute(JsonEntityView.ENTITY, rs.getClaimsRequired()); return JsonEntityView.VIEWNAME; }
From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java
/** * When a User does a POST request to /orders, a new Order is created. The requestbody is a TicketDTO, so an order * always contains at least one ticket. Optional next tickets should be added to the order by POSTing to the * location provided./* ww w. java 2s . co m*/ * * @param auth The User that is currently logged in * @param ticketDTO Object containing information about the Ticket that is being ordered. * * @return A message informing about the result of the request */ @PreAuthorize("isAuthenticated()") @RequestMapping(value = "/orders", method = RequestMethod.POST) @JsonView(View.OrderOverview.class) public ResponseEntity<?> createOrder(Authentication auth, @RequestBody @Validated TicketDTO ticketDTO) { HttpHeaders headers = new HttpHeaders(); User user = (User) auth.getPrincipal(); // You can't buy non-buyable Tickts for yourself, this should be done via the createAdminOrder() method. if (!ticketDTO.getType().isBuyable()) { return createResponseEntity(HttpStatus.FORBIDDEN, "Can't order tickets with type " + ticketDTO.getType().getText()); } Order order = orderService.create(user.getId(), ticketDTO); headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(order.getId()).toUri()); return createResponseEntity(HttpStatus.CREATED, headers, "Ticket available and order successfully created at " + headers.getLocation(), order); }