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:ch.heigvd.gamification.api.BadgesEndpoint.java
@Override @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Void> badgesPost( @ApiParam(value = "Badge to add", required = true) @RequestBody BadgeDTO body, @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken) { AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken); if (apiKey == null) { return new ResponseEntity(HttpStatus.UNAUTHORIZED); }/*from w w w.ja v a 2 s . c om*/ Application app = apiKey.getApp(); if (body != null && app != null) { if (badgeRepository.findByNameAndApp(body.getName(), app) != null) { return new ResponseEntity("name already use", HttpStatus.UNPROCESSABLE_ENTITY); } Badge badge = new Badge(); badge.setDescription(body.getDescription()); badge.setName(body.getName()); badge.setImage(body.getImageURI()); badge.setApp(app); badgeRepository.save(badge); HttpHeaders responseHeaders = new HttpHeaders(); UriComponents uriComponents = MvcUriComponentsBuilder .fromMethodName(BadgesEndpoint.class, "badgesBadgeIdGet", 1, badge.getId()).build(); URI locationUri = uriComponents.toUri(); responseHeaders.add("Location", uriComponents.toString()); return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED); } else { return new ResponseEntity("no content is available", HttpStatus.BAD_REQUEST); } }
From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.implicit.Oauth2ImplicitFlowPredefinedTests.java
@Test public void oauth2FlowTest() throws Exception { // Obtains the token obtainTokenFromOuth2LoginEndpoint(); // Call remotelog ResponseEntity<String> result = callRemoteLogWithAccessToken(); assertEquals(HttpStatus.OK, result.getStatusCode()); if (!isJwtTokenStore) { // The following code is executed only if the token store is not a JwtTokenStore. The reason is that using this kind of store // the tokens can't be revoked (they just expire) and so this part of the test would fail. // A JwtTokenStore is not a proper store as the tokens are not stored anywhere (as they contain all the required info about the user // themselves. That's why the token revocation is not possible. // We call logout endpoint (we need to use the access token for this) UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(authServerBaseUrl + baseApiPath + oauth2LogoutEndpointPath); builder.queryParam("access_token", accessToken); ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, null, String.class); assertEquals(HttpStatus.OK, result2.getStatusCode()); // We try to call the protected API again (after having logged out which removes the token) - We expect not to be able to call the service. // This will throw a exception. In this case here in the test we receive an exception but really what happened was 'access denied' // A production client will receive the proper http error result = callRemoteLogWithAccessToken(); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); }/*from w w w.ja v a 2 s . c o m*/ }
From source file:de.thm.arsnova.controller.LoginController.java
@RequestMapping(value = { "/auth/login", "/doLogin" }, method = { RequestMethod.POST, RequestMethod.GET }) public void doLogin(@RequestParam("type") final String type, @RequestParam(value = "user", required = false) String username, @RequestParam(required = false) final String password, @RequestParam(value = "role", required = false) final UserSessionService.Role role, final HttpServletRequest request, final HttpServletResponse response) throws IOException { String addr = request.getRemoteAddr(); if (userService.isBannedFromLogin(addr)) { response.sendError(429, "Too Many Requests"); return;//from w ww .ja v a 2 s.c om } userSessionService.setRole(role); if ("arsnova".equals(type)) { Authentication authRequest = new UsernamePasswordAuthenticationToken(username, password); try { Authentication auth = daoProvider.authenticate(authRequest); if (auth.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(auth); request.getSession(true).setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); return; } } catch (AuthenticationException e) { LOGGER.info("Authentication failed: {}", e.getMessage()); } userService.increaseFailedLoginCount(addr); response.setStatus(HttpStatus.UNAUTHORIZED.value()); } else if ("ldap".equals(type)) { if (!"".equals(username) && !"".equals(password)) { org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User( username, password, true, true, true, true, this.getAuthorities()); Authentication token = new UsernamePasswordAuthenticationToken(user, password, getAuthorities()); try { Authentication auth = ldapAuthenticationProvider.authenticate(token); if (auth.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(token); request.getSession(true).setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); return; } LOGGER.info("LDAPLOGIN: {}", auth.isAuthenticated()); } catch (AuthenticationException e) { LOGGER.info("No LDAP login: {}", e); } userService.increaseFailedLoginCount(addr); response.setStatus(HttpStatus.UNAUTHORIZED.value()); } } else if ("guest".equals(type)) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_GUEST")); if (username == null || !username.startsWith("Guest") || username.length() != MAX_USERNAME_LENGTH) { username = "Guest" + Sha512DigestUtils.shaHex(request.getSession().getId()).substring(0, MAX_GUESTHASH_LENGTH); } org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User( username, "", true, true, true, true, authorities); Authentication token = new UsernamePasswordAuthenticationToken(user, null, authorities); SecurityContextHolder.getContext().setAuthentication(token); request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); } }
From source file:eu.freme.broker.integration_tests.UserControllerTest.java
@Test public void testAdmin() throws UnirestException { String username = "carlos"; String password = "carlosss"; logger.info("create user \"" + username + "\" and get token"); HttpResponse<String> response = Unirest.post(baseUrl + "/user").queryString("username", username) .queryString("password", password).asString(); response = Unirest.post(baseUrl + BaseRestController.authenticationEndpoint) .header("X-Auth-Username", username).header("X-Auth-Password", password).asString(); String token = new JSONObject(response.getBody()).getString("token"); logger.info("try to access /user endpoint from user account - should not work"); loggerIgnore(accessDeniedExceptions); response = Unirest.get(baseUrl + "/user").header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value()); loggerUnignore(accessDeniedExceptions); logger.info("access /user endpoint with admin credentials"); response = Unirest.post(baseUrl + BaseRestController.authenticationEndpoint) .header("X-Auth-Username", adminUsername).header("X-Auth-Password", adminPassword).asString(); token = new JSONObject(response.getBody()).getString("token"); response = Unirest.get(baseUrl + "/user").header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); logger.info("access user through access token passed via query string"); response = Unirest.get(baseUrl + "/user").queryString("token", token).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); logger.info("admin can delete carlos"); response = Unirest.delete(baseUrl + "/user/" + username).header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.NO_CONTENT.value()); response = Unirest.get(baseUrl + "/user").header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); }
From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java
/** * Test secure endpoint without authentication */// w w w . java 2s . c om @Test public void testSecureEndpointNoAuthentication() { RestTemplate restTemplate = new RestTemplate(); try { restTemplate.getForEntity(SECURE_ENDPOINT, String.class); fail("Exception expected. 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:com.appglu.impl.UserTemplateTest.java
@Test public void refreshUserProfileUnauthorized() { mockServer.expect(requestTo("http://localhost/appglu/v1/users/me")).andExpect(method(HttpMethod.GET)) .andExpect(header(UserSessionPersistence.X_APPGLU_SESSION_HEADER, "sessionId")) .andRespond(withStatus(HttpStatus.UNAUTHORIZED).body(compactedJson("data/user_unauthorized")) .headers(responseHeaders)); Assert.assertFalse(appGluTemplate.isUserAuthenticated()); Assert.assertNull(appGluTemplate.getAuthenticatedUser()); appGluTemplate.setUserSessionPersistence(new LoggedInUserSessionPersistence("sessionId", new User("test"))); Assert.assertTrue(appGluTemplate.isUserAuthenticated()); Assert.assertNotNull(appGluTemplate.getAuthenticatedUser()); try {//from ww w . j a va 2 s . c om userOperations.refreshUserProfile(); Assert.fail("An unauthorized response should throw an AppGluHttpUserUnauthorizedException exception"); } catch (AppGluHttpUserUnauthorizedException e) { } Assert.assertFalse(appGluTemplate.isUserAuthenticated()); Assert.assertNull(appGluTemplate.getAuthenticatedUser()); mockServer.verify(); }
From source file:com.capstone.giveout.controllers.GiftsController.java
@PreAuthorize("hasRole(mobile)") @RequestMapping(value = Routes.GIFTS_UPDATE_IMAGE_PATH, method = RequestMethod.POST) public @ResponseBody Gift updateImages(@PathVariable("id") long id, @RequestParam("image") MultipartFile image, Principal p, HttpServletResponse response) throws IOException { Gift gift = gifts.findOne(id);/* w w w . ja v a2 s . co m*/ if (gift == null) { response.sendError(HttpStatus.NOT_FOUND.value()); return null; } 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 null; } saveImages(gift, image); return gift; }
From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java
@Test public void testNoClientIdProvided() throws Exception { ResponseEntity<String> response = attemptToGetConfirmationPage(null, "http://anywhere"); // With no client id you get an InvalidClientException on the server which is forwarded to /oauth/error assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); String body = response.getBody(); assertTrue("Wrong body: " + body, body.contains("<html")); assertTrue("Wrong body: " + body, body.contains("Bad client credentials")); }
From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java
@ResponseStatus(value = HttpStatus.UNAUTHORIZED) @ExceptionHandler(InvalidCredentials.class) public void handleException(InvalidCredentials exception, HttpServletRequest request, HttpServletResponse response) {/*from w w w .j a v a 2 s .c o m*/ handleBaseException((BaseException) exception, request, response); }