List of usage examples for org.springframework.http HttpStatus UNAUTHORIZED
HttpStatus UNAUTHORIZED
To view the source code for org.springframework.http HttpStatus UNAUTHORIZED.
Click Source Link
From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java
/** * Test authentication failure to method secure endpoint that requires only authentication * using no authentication/*www .java2 s .c o m*/ */ @Test public void testClientCredentialsMethodNotLoggedIn() { RestTemplate restTemplate = new RestTemplate(); try { restTemplate.getForEntity(METHOD_SECURE_ENDPOINT, String.class); fail("Expected exception. None was thrown."); } catch (HttpClientErrorException ex) { assertEquals(ex.getStatusCode(), HttpStatus.UNAUTHORIZED); } catch (ResourceAccessException ex) { fail("It appears that the server may not be running. Please start it before running tests"); } catch (Exception ex) { fail(ex.getMessage()); } }
From source file:spring.AbstractAuthorizationCodeProviderTests.java
@Test @OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false) public void testWrongClientIdTokenEndpoint() throws Exception { approveAccessTokenGrant("http://anywhere?key=value", true); ((BaseOAuth2ProtectedResourceDetails) context.getResource()).setClientId("non-existent"); try {//from www .j a v a2 s . co m assertNotNull(context.getAccessToken()); fail("Expected HttpClientErrorException"); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); } }
From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java
@Test public void testClientIdMustBeConsistent() throws Exception { webDriver.get(baseUrl + "/logout.do"); HttpHeaders headers = getAppBasicAuthHttpHeaders(); Map<String, String> requestBody = new HashMap<>(); requestBody.put("username", testAccounts.getUserName()); requestBody.put("password", testAccounts.getPassword()); ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("scope", "openid").queryParam("client_id", "stealer_of_codes") .queryParam("code", autologinCode).build().toUriString(); try {/*from ww w .j a va 2 s.c om*/ restOperations.exchange(authorizeUrl, HttpMethod.GET, null, Void.class); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); } }
From source file:com.capstone.giveout.controllers.GiftsController.java
@PreAuthorize("hasRole(mobile)") @RequestMapping(value = Routes.GIFTS_ID_PATH, method = RequestMethod.DELETE) public @ResponseBody void delete(@PathVariable("id") long id, Principal p, HttpServletResponse response) throws IOException { Gift gift = gifts.findOne(id);/*from www . ja va 2 s . c o m*/ if (gift == null) { response.sendError(HttpStatus.NOT_FOUND.value()); return; } gift.allowAccessToGiftChain = true; User currentUser = users.findByUsername(p.getName()); if (gift.getUser().getId() != currentUser.getId()) { response.sendError(HttpStatus.UNAUTHORIZED.value(), "You are not the owner of this gift"); return; } gifts.delete(gift); long giftsRemaining = gifts.countByGiftChain(gift.getGiftChain()); if (giftsRemaining == 0) { giftChains.delete(gift.getGiftChain()); } }
From source file:org.fineract.module.stellar.controller.BridgeController.java
@ExceptionHandler @ResponseStatus(HttpStatus.UNAUTHORIZED) public String handleInvalidApiKeyException(final SecurityException ex) { return ex.getMessage(); }
From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java
/** * <pre>/* w ww . j av a2s. c om*/ * RHEV Manager API . * </pre> * @param api RHEV Manager API (/api, /api/vms ) * @param body xml contents * @param clazz ? Target Object Class * @return * @throws RestClientException * @throws Exception */ public synchronized <T> T submit(String api, HttpMethod method, Object body, String rootElementName, Class<T> clazz) throws RestClientException, Exception { Assert.isTrue(StringUtils.isNotEmpty(api), "api must not be null"); Assert.notNull(clazz, "clazz must not be null."); // Multi RHEV Manager ? ?? HostnameVerifier ??, // ?? ? ?.(java.io.IOException: HTTPS hostname wrong: should be <{host}>) //init(); try { RestTemplate rt = new RestTemplate(); ResponseEntity<?> response = rt.exchange(new URI(getUrl(api)), method, setHTTPEntity(body, rootElementName), clazz); logger.debug("[Request URL] : {}", getUrl(api)); logger.debug("[Response] : {}", response); if (response.getStatusCode().equals(HttpStatus.BAD_REQUEST) || response.getStatusCode().equals(HttpStatus.UNAUTHORIZED) || response.getStatusCode().equals(HttpStatus.PAYMENT_REQUIRED) || response.getStatusCode().equals(HttpStatus.FORBIDDEN) || response.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED) || response.getStatusCode().equals(HttpStatus.NOT_ACCEPTABLE) || response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR) || response.getStatusCode().equals(HttpStatus.NOT_IMPLEMENTED) || response.getStatusCode().equals(HttpStatus.BAD_GATEWAY) || response.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE) || response.getStatusCode().equals(HttpStatus.GATEWAY_TIMEOUT)) { throw new Exception(response.getStatusCode().value() + " " + response.getStatusCode().toString()); } return clazz.cast(response.getBody()); } catch (RestClientException e) { logger.error("RestClientException has occurred.", e); throw e; } catch (Exception e) { logger.error("Unhandled Exception has occurred.", e); throw e; } }
From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java
@Test public void testInvalidAccessToken() throws Exception { // now make sure an unauthorized request fails the right way. HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, "FOO")); ResponseEntity<String> response = http.getForString("/admin/beans", headers); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); String authenticate = response.getHeaders().getFirst("WWW-Authenticate"); assertNotNull(authenticate);//from w ww . jav a2 s . co m assertTrue(authenticate.startsWith("Bearer")); // Resource Server doesn't know what scopes are required until the token can be validated assertFalse(authenticate.contains("scope=\"")); }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.SpringApiClientImplIntegrationTest.java
/** * Tests {@link SpringApiClientImpl#getMyChannels} in the case where HTTP response code 401 Unauthorized is returned. * This can occur if the API credentials that the API client is configured to use are deemed invalid by the API * service./*from www . j a v a 2 s .c om*/ */ @Test public void getMyChannelsWhenAuthenticationFails() { String expectedRequestUrl = this.apiClient.getApiServiceBaseUri() + ChannelsResource.MY_CHANNELS_RELATIVE_URI_TEMPLATE; // Configure mock API service to respond to API call with a canned collection of API resources read from file this.mockReportingApiService.expect(method(HttpMethod.GET)).andExpect(requestTo(expectedRequestUrl)) .andRespond(withUnauthorizedRequest()); try { this.apiClient.getMyChannels(null); fail("Expected exception to be thrown."); } catch (ApiErrorResponseException e) { assertThat(e.getStatusCode(), is(HttpStatus.UNAUTHORIZED.value())); } this.mockReportingApiService.verify(); }
From source file:org.apigw.authserver.AuthorizationCodeProviderIntegrationtest.java
@Test public void testInvalidAccessToken() throws Exception { log.debug("testInvalidAccessToken"); // now make sure an unauthorized request fails the right way. HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, "FOO")); ResponseEntity<String> response = serverRunning.getForString("/crm-scheduling-api/crm/scheduling/booking", headers);/*from w w w . j av a 2 s. c om*/ assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); String authenticate = response.getHeaders().getFirst("WWW-Authenticate"); assertNotNull(authenticate); assertTrue(authenticate.startsWith("Bearer")); // Resource Server doesn't know what scopes are required until teh token can be validated assertFalse(authenticate.contains("scope=\"")); }
From source file:de.hska.ld.etherpad.controller.DocumentEtherpadController.java
@RequestMapping(method = RequestMethod.POST, value = "/etherpad/conversations") public Callable getConversations(@RequestBody EtherpadDocumentUpdateDto etherpadDocumentUpdateDto) { return () -> { if (env.getProperty("module.etherpad.apikey").equals(etherpadDocumentUpdateDto.getApiKey())) { String sessionId = etherpadDocumentUpdateDto.getAuthorId(); UserEtherpadInfo userEtherpadInfo = userEtherpadInfoService.findBySessionId(sessionId); if (userEtherpadInfo == null) { return new ResponseEntity<>("sessionID is invalid", HttpStatus.UNAUTHORIZED); }/*from w w w . j a v a 2 s.c o m*/ DocumentEtherpadInfo documentEtherpadInfo = documentEtherpadInfoService .findByGroupPadId(etherpadDocumentUpdateDto.getPadId()); return userService.callAs(userEtherpadInfo.getUser(), () -> { // retrieve all conversations the user has access to Long documentId = documentEtherpadInfo.getDocument().getId(); int pageNumber = 0; int pageSize = 10; String sortDirection = "DESC"; String sortProperty = "createdAt"; Page<Document> documentPage = documentService.getDiscussionDocumentsPage(documentId, pageNumber, pageSize, sortDirection, sortProperty); System.out.println(documentPage); List<Document> documentList = documentPage.getContent(); List<DocumentInfo> documentInfoList = new ArrayList<DocumentInfo>(); documentList.forEach(d -> { DocumentInfo documentInfo = new DocumentInfo(); documentInfo.setId(d.getId()); documentInfo.setTitle(d.getTitle()); documentInfoList.add(documentInfo); }); return new ResponseEntity<>(documentInfoList, HttpStatus.OK); }); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } }; }