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:org.createnet.raptor.auth.service.controller.AuthenticationController.java
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) @ApiOperation(value = "Login an user with provided credentials", notes = "", response = JwtResponse.class, nickname = "login") public ResponseEntity<?> login(@RequestBody JwtRequest authenticationRequest) throws AuthenticationException { try {/*from w ww . ja va2 s .c o m*/ final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.username, authenticationRequest.password)); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.username); final Token token = tokenService.createLoginToken((User) userDetails); // Return the token return ResponseEntity.ok(new JwtResponse((User) userDetails, token.getToken())); } catch (AuthenticationException ex) { logger.error("Authentication exception: {}", ex.getMessage()); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication failed"); } }
From source file:com.coinblesk.server.controller.UserController.java
@RequestMapping(value = "/login", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<?> login(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginDTO.getUsername().toLowerCase(Locale.ENGLISH), loginDTO.getPassword()); try {/* w w w . ja v a 2s.co m*/ Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = tokenProvider.createToken(authentication); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(Collections.singletonMap("token", jwt)); } catch (AuthenticationException exception) { return new ResponseEntity<>( Collections.singletonMap("AuthenticationException", exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } }
From source file:org.zaizi.SensefyResourceApplicationTests.java
@Test public void testKeywordSearchAnauthorized() { RestTemplate template = new TestRestTemplate(); // keywordSearch ResponseEntity<String> response = template.getForEntity(baseTestServerUrl() + "keywordSearch", String.class); Assert.assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); }
From source file:org.kaaproject.kaa.sandbox.web.services.CacheServiceImpl.java
@Override @Caching(evict = { @CacheEvict(value = SDK_CACHE, allEntries = true), @CacheEvict(value = FILE_CACHE, allEntries = true) }) public void flushAllCaches() throws SandboxServiceException { final AdminClient client = clientProvider.getClient(); client.login(tenantDeveloperUser, tenantDeveloperPassword); try {/*from w ww . j a va 2 s.c o m*/ retryRestCall(new RestCall() { @Override public void executeRestCall() throws Exception { client.flushSdkCache(); } }, 3, 5000, HttpStatus.UNAUTHORIZED); } catch (Exception e) { throw Utils.handleException(e); } LOG.info("All caches have been completely flushed."); }
From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); parameters.set("username", username); parameters.set("password", password); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = restTemplate.exchange(loginUrl, HttpMethod.POST, new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class); if (response.getStatusCode() == HttpStatus.OK) { String userFromUaa = (String) response.getBody().get("username"); if (userFromUaa.equals(userFromUaa)) { logger.info("Successful authentication request for " + authentication.getName()); return new UsernamePasswordAuthenticationToken(username, null, UaaAuthority.USER_AUTHORITIES); }//from w w w . ja v a2 s . co m } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.info("Failed authentication request"); throw new BadCredentialsException("Authentication failed"); } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) { logger.info("Internal error from UAA. Please Check the UAA logs."); } else { logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA." + " Is a compatible version running?"); } throw new RuntimeException("Could not authenticate with remote server"); }
From source file:eu.freme.broker.integration_tests.UserControllerTest.java
@Test public void testUserSecurity() throws UnirestException { String username = "myuser"; String password = "mypassword"; logger.info("create user"); logger.info(baseUrl + "/user"); HttpResponse<String> response = Unirest.post(baseUrl + "/user").queryString("username", username) .queryString("password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); String responseUsername = new JSONObject(response.getBody()).getString("name"); assertTrue(username.equals(responseUsername)); logger.info("create user with dublicate username - should not work, exception is ok"); loggerIgnore("eu.freme.broker.exception.BadRequestException"); response = Unirest.post(baseUrl + "/user").queryString("username", username) .queryString("password", password).asString(); assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value()); loggerUnignore("eu.freme.broker.exception.BadRequestException"); logger.info("create users with invalid usernames - should not work"); loggerIgnore("eu.freme.broker.exception.BadRequestException"); response = Unirest.post(baseUrl + "/user").queryString("username", "123").queryString("password", password) .asString();//from w ww . ja va2 s . c om assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value()); response = Unirest.post(baseUrl + "/user").queryString("username", "*abc").queryString("password", password) .asString(); assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value()); response = Unirest.post(baseUrl + "/user").queryString("username", adminUsername) .queryString("password", password).asString(); assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value()); response = Unirest.post(baseUrl + "/user").queryString("username", "").queryString("password", password) .asString(); assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value()); loggerUnignore("eu.freme.broker.exception.BadRequestException"); logger.info("login with bad password should fail"); loggerIgnore(accessDeniedExceptions); response = Unirest.post(baseUrl + BaseRestController.authenticationEndpoint) .header("X-Auth-Username", username).header("X-Auth-Password", password + "xyz").asString(); assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value()); loggerUnignore(accessDeniedExceptions); logger.info("login with new user / create token"); response = Unirest.post(baseUrl + BaseRestController.authenticationEndpoint) .header("X-Auth-Username", username).header("X-Auth-Password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); String token = new JSONObject(response.getBody()).getString("token"); assertTrue(token != null); assertTrue(token.length() > 0); logger.info("delete user without providing credentials - should fail, exception is ok"); loggerIgnore(accessDeniedExceptions); response = Unirest.delete(baseUrl + "/user/" + username).asString(); assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value()); loggerUnignore(accessDeniedExceptions); logger.info("create a 2nd user"); String otherUsername = "otheruser"; response = Unirest.post(baseUrl + "/user").queryString("username", otherUsername) .queryString("password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); String responseOtherUsername = new JSONObject(response.getBody()).getString("name"); assertTrue(otherUsername.equals(responseOtherUsername)); logger.info("delete other user should fail"); loggerIgnore(accessDeniedExceptions); response = Unirest.delete(baseUrl + "/user/" + otherUsername).header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value()); loggerUnignore(accessDeniedExceptions); logger.info("cannot do authenticated call with username / password, only token should work"); loggerIgnore(accessDeniedExceptions); response = Unirest.delete(baseUrl + "/user/" + username).header("X-Auth-Username", username) .header("X-Auth-Password", password).asString(); assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value()); loggerUnignore(accessDeniedExceptions); logger.info("get user information"); response = Unirest.get(baseUrl + "/user/" + username).header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); responseUsername = new JSONObject(response.getBody()).getString("name"); assertTrue(responseUsername.equals(username)); logger.info("delete own user - should work"); response = Unirest.delete(baseUrl + "/user/" + username).header("X-Auth-Token", token).asString(); assertTrue(response.getStatus() == HttpStatus.NO_CONTENT.value()); }
From source file:com.epam.catgenome.controller.ExceptionHandlerAdvice.java
@ResponseBody @Order(Ordered.HIGHEST_PRECEDENCE)// w w w . j a v a 2 s. c o m @ExceptionHandler(Throwable.class) public final ResponseEntity<Result<String>> handleUncaughtException(final Throwable exception, final WebRequest request) { // adds information about encountered error to application log LOG.error(MessageHelper.getMessage("logger.error", request.getDescription(true)), exception); HttpStatus code = HttpStatus.OK; String message; if (exception instanceof FileNotFoundException) { // any details about real path of a resource should be normally prevented to send to the client message = MessageHelper.getMessage("error.io.not.found"); } else if (exception instanceof DataAccessException) { // any details about data access error should be normally prevented to send to the client, // as its message can contain information about failed SQL query or/and database schema if (exception instanceof BadSqlGrammarException) { // for convenience we need to provide detailed information about occurred BadSqlGrammarException, // but it can be retrieved SQLException root = ((BadSqlGrammarException) exception).getSQLException(); if (root.getNextException() != null) { LOG.error(MessageHelper.getMessage("logger.error.root.cause", request.getDescription(true)), root.getNextException()); } message = MessageHelper.getMessage("error.sql.bad.grammar"); } else { message = MessageHelper.getMessage("error.sql"); } } else if (exception instanceof UnauthorizedClientException) { message = exception.getMessage(); code = HttpStatus.UNAUTHORIZED; } else { message = exception.getMessage(); } return new ResponseEntity<>(Result.error(StringUtils.defaultString(StringUtils.trimToNull(message), MessageHelper.getMessage("error" + ".default"))), code); }
From source file:org.cloudfoundry.identity.uaa.login.integration.AutologinContollerIntegrationTests.java
@Test public void testClientUnauthorized() { AutologinRequest request = new AutologinRequest(); request.setUsername(testAccounts.getUserName()); request.setPassword(testAccounts.getPassword()); @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/autologin"), HttpMethod.POST, new HttpEntity<AutologinRequest>(request), Map.class); assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) entity.getBody(); assertNull(result.get("code")); }
From source file:edu.kit.scc.RestServiceController.java
/** * Linking endpoint.//from w ww .j a va 2s .c o m * * @param basicAuthorization authorization header value * @param scimUsers a JSON serialized list of SCIM users for linking * @param response the HttpServletResponse * @return a JSON serialized list of SCIM users containing the modifications done */ @RequestMapping(path = "/link", method = RequestMethod.POST, consumes = "application/scim+json", produces = "application/scim+json") public ResponseEntity<?> linkUsers(@RequestHeader("Authorization") String basicAuthorization, @RequestBody List<ScimUser> scimUsers, HttpServletResponse response) { if (!verifyAuthorization(basicAuthorization)) { return new ResponseEntity<String>("REST Service Unauthorized", HttpStatus.UNAUTHORIZED); } log.debug("Request body {}", scimUsers); List<ScimUser> modifiedUsers = identityHarmonizer.harmonizeIdentities(scimUsers); if (!modifiedUsers.isEmpty()) { return new ResponseEntity<List<ScimUser>>(modifiedUsers, HttpStatus.OK); } return new ResponseEntity<String>("Conflicting information", HttpStatus.CONFLICT); }
From source file:org.sharetask.controller.UserController.java
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void performLogin(@RequestBody final UserPassword login, final HttpServletRequest request, final HttpServletResponse response) { final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( login.getUsername(), login.getPassword()); try {//w ww . ja va2 s . c o m final Authentication auth = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(auth); repository.saveContext(SecurityContextHolder.getContext(), request, response); rememberMeServices.loginSuccess(request, response, auth); // language cookie final UserInfoDTO user = userService.read(SecurityUtil.getCurrentSignedInUsername()); final Cookie locale = new Cookie(RequestUltil.LOCALE, user.getLanguage()); locale.setMaxAge(-1); locale.setPath("/"); response.addCookie(locale); response.setStatus(HttpStatus.OK.value()); } catch (final BadCredentialsException ex) { response.setStatus(HttpStatus.UNAUTHORIZED.value()); } }