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.cloudfoundry.identity.uaa.integration.TokenAdminEndpointsIntegrationTests.java
@Test @OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.ClientCredentials.class) public void testCannotListTokensOfAnotherClient() throws Exception { assertEquals(HttpStatus.FORBIDDEN, serverRunning.getForString("/oauth/clients/token/tokens").getStatusCode()); }
From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java
@Test public void basicAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception { RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO(); logRequestVO.setMessage("Test mesage!"); logRequestVO.setLogLevel("DEBUG"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8")))); HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath); ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode()); }
From source file:com.auditbucket.engine.endpoint.TrackEP.java
@ResponseBody @RequestMapping(value = "/log/", consumes = "application/json", produces = "application/json", method = RequestMethod.POST) public ResponseEntity<LogResultBean> trackLog(@RequestBody LogInputBean input, String apiKey, @RequestHeader(value = "Api-Key", required = false) String apiHeaderKey) throws DatagioException { // If we have a valid company we are good to go. Company company = getCompany(apiHeaderKey, apiKey); LogResultBean resultBean = mediationFacade.processLogForCompany(company, input); LogInputBean.LogStatus ls = resultBean.getStatus(); if (ls.equals(LogInputBean.LogStatus.FORBIDDEN)) return new ResponseEntity<>(resultBean, HttpStatus.FORBIDDEN); else if (ls.equals(LogInputBean.LogStatus.NOT_FOUND)) { input.setAbMessage("Illegal meta key"); return new ResponseEntity<>(resultBean, HttpStatus.NOT_FOUND); } else if (ls.equals(LogInputBean.LogStatus.IGNORE)) { input.setAbMessage("Ignoring request to change as the 'what' has not changed"); return new ResponseEntity<>(resultBean, HttpStatus.NOT_MODIFIED); } else if (ls.equals(LogInputBean.LogStatus.ILLEGAL_ARGUMENT)) { return new ResponseEntity<>(resultBean, HttpStatus.NO_CONTENT); }/*from w w w . j ava2 s . com*/ return new ResponseEntity<>(resultBean, HttpStatus.OK); }
From source file:org.mitre.oauth2.web.OAuthConfirmationController.java
@PreAuthorize("hasRole('ROLE_USER')") @RequestMapping("/oauth/confirm_access") public String confimAccess(Map<String, Object> model, @ModelAttribute("authorizationRequest") AuthorizationRequest authRequest, Principal p) { // Check the "prompt" parameter to see if we need to do special processing String prompt = (String) authRequest.getExtensions().get(PROMPT); List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt)); ClientDetailsEntity client = null;/*from w w w . ja v a 2 s . co m*/ try { client = clientService.loadClientByClientId(authRequest.getClientId()); } catch (OAuth2Exception e) { logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } if (client == null) { logger.error("confirmAccess: could not find client " + authRequest.getClientId()); model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } if (prompts.contains("none")) { // if we've got a redirect URI then we'll send it String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client); try { URIBuilder uriBuilder = new URIBuilder(url); uriBuilder.addParameter("error", "interaction_required"); if (!Strings.isNullOrEmpty(authRequest.getState())) { uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given } return "redirect:" + uriBuilder.toString(); } catch (URISyntaxException e) { logger.error("Can't build redirect URI for prompt=none, sending error instead", e); model.put("code", HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } } model.put("auth_request", authRequest); model.put("client", client); String redirect_uri = authRequest.getRedirectUri(); model.put("redirect_uri", redirect_uri); // pre-process the scopes Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope()); Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size()); Set<SystemScope> systemScopes = scopeService.getAll(); // sort scopes for display based on the inherent order of system scopes for (SystemScope s : systemScopes) { if (scopes.contains(s)) { sortedScopes.add(s); } } // add in any scopes that aren't system scopes to the end of the list sortedScopes.addAll(Sets.difference(scopes, systemScopes)); model.put("scopes", sortedScopes); // get the userinfo claims for each scope UserInfo user = userInfoService.getByUsername(p.getName()); Map<String, Map<String, String>> claimsForScopes = new HashMap<>(); if (user != null) { JsonObject userJson = user.toJson(); for (SystemScope systemScope : sortedScopes) { Map<String, String> claimValues = new HashMap<>(); Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue()); for (String claim : claims) { if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) { // TODO: this skips the address claim claimValues.put(claim, userJson.get(claim).getAsString()); } } claimsForScopes.put(systemScope.getValue(), claimValues); } } model.put("claims", claimsForScopes); // client stats Integer count = statsService.getCountForClientId(client.getId()); model.put("count", count); // contacts if (client.getContacts() != null) { String contacts = Joiner.on(", ").join(client.getContacts()); model.put("contacts", contacts); } // if the client is over a week old and has more than one registration, don't give such a big warning // instead, tag as "Generally Recognized As Safe" (gras) Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000)); if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) { model.put("gras", true); } else { model.put("gras", false); } return "approve"; }
From source file:de.sainth.recipe.backend.rest.controller.CookbookController.java
@Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping(value = "{id}", method = RequestMethod.PUT) HttpEntity<Cookbook> update(@PathVariable("id") Long id, @Valid @RequestBody Cookbook cookbook) { if (id.equals(cookbook.getId())) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof RecipeManagerAuthenticationToken) { RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication; Cookbook existingCookbook = repository.findOne(cookbook.getId()); if (existingCookbook != null) { if (ROLE_ADMIN.name().equals(token.getRole()) || existingCookbook.getAuthor().getId().equals(authentication.getPrincipal())) { repository.save(cookbook); return new ResponseEntity<>(cookbook, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.FORBIDDEN); }// w ww .ja va2 s . c o m } } } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); }
From source file:org.avidj.zuul.rs.Zuul.java
/** * Release the given lock if it is held by the given {@code session}. * @param session the session id to release the lock for * @param request the request//from w ww . j a va 2 s . c o m * @param uriBuilder a builder for the response location header URI * @return {@code true}, iff the lock was released */ @RequestMapping(value = "/s/{id}/**", method = RequestMethod.DELETE) public ResponseEntity<String> release(@PathVariable("id") String session, HttpServletRequest request, UriComponentsBuilder uriBuilder) { final List<String> path = getLockPath(request, session); final boolean deleted = lm.release(session, path); HttpStatus httpStatus = deleted ? HttpStatus.NO_CONTENT : HttpStatus.FORBIDDEN; UriComponents uriComponents = uriBuilder.path("/s/{id}/{lockPath}").buildAndExpand(session, Strings.join("/", path)); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<String>(headers, httpStatus); }
From source file:com.wiiyaya.consumer.web.main.controller.ExceptionController.java
/** * /*from w w w . j a v a 2 s.com*/ * @param request ? * @param exception * @return ExceptionDto JSON */ @ExceptionHandler(value = ValidateException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public ModelAndView businessException(HttpServletRequest request, ValidateException exception) { String filedName = messageSource.getMessage(exception.getCode(), null, LocaleContextHolder.getLocale()); return prepareExceptionInfo(request, HttpStatus.FORBIDDEN, MSG_ERROR_VALIDATE, filedName + exception.getDefaultMessage()); }
From source file:plbtw.klmpk.barang.hilang.controller.UserController.java
@RequestMapping(value = "/auth", method = RequestMethod.POST, produces = "application/json") public CustomResponseMessage authLogin(@RequestHeader String apiKey, @RequestBody UserAuthRequest userAuthRequest) { try {//from w w w.j a va 2s . c o m if (!authApiKey(apiKey)) { return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication"); } if (checkRateLimit(RATE_LIMIT, apiKey)) { return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED, "Please wait a while, you have reached your rate limit"); } LogRequest temp = DependencyFactory.createLog(apiKey, "Post"); Log log = new Log(); log.setApiKey(temp.getApiKey()); log.setStatus(temp.getStatus()); log.setTimeRequest(temp.getTime_request()); logService.addLog(log); User user = userService.authLoginUser(userAuthRequest.getEmail(), userAuthRequest.getPassword()); List<User> listUser = new ArrayList<User>(); if (user == null) { return new CustomResponseMessage(HttpStatus.NOT_FOUND, "Login Failed", listUser); } listUser.add(user); CustomResponseMessage result = new CustomResponseMessage(); result.setResult(listUser); result.setHttpStatus(HttpStatus.ACCEPTED); result.setMessage("Auth Success"); return result; } catch (Exception ex) { return new CustomResponseMessage(HttpStatus.BAD_REQUEST, "Please use your api key to authentication"); } }
From source file:com.cicdaas.nasasoundapiautomation.test.NASASoundAPITest.java
@Test(groups = { "nasa-sound-api-regression", "real-svc-only", "nasa-sound-api-sanity" }) public void testNegNASASoundAPIGETCallwithInvalidKey() { try {//from w ww .j av a2 s.c o m String key = "123"; client.getSoundTrackWithSpecificAPIKey(key); fail("Sound API returned valid response for invalid API Key!"); } catch (HttpClientErrorException hcee) { assertEquals(HttpStatus.FORBIDDEN, hcee.getStatusCode(), "HTTP Status code didn't match!"); } catch (Exception e) { fail(defaultAPIClientErrorMsg, e); } }
From source file:org.avidj.zuul.rs.ZuulTest.java
@Test public void itShallRejectLockNestedIntoDeepLockOnRoot() { final Zuul zuul = createZuul(); given().standaloneSetup(zuul).param("t", "w").param("s", "d").when().put("/s/1/").then() .statusCode(HttpStatus.CREATED.value()); given().standaloneSetup(zuul).param("t", "r").when().put("/s/2/foo/bar").then() .statusCode(HttpStatus.FORBIDDEN.value()); }