Example usage for org.springframework.http HttpStatus UNAUTHORIZED

List of usage examples for org.springframework.http HttpStatus UNAUTHORIZED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus UNAUTHORIZED.

Prototype

HttpStatus UNAUTHORIZED

To view the source code for org.springframework.http HttpStatus UNAUTHORIZED.

Click Source Link

Document

401 Unauthorized .

Usage

From source file:ca.hec.tenjin.tool.controller.SyllabusController.java

@ExceptionHandler(DeniedAccessException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public @ResponseBody String handleDeniedAccessException(DeniedAccessException ex) {
    return msgs.getString("tenjin.error.unauthorized");
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void simpleAuthenticationServiceTestNoCredentials() throws Exception {
    CredentialsVO credentialsVO = new CredentialsVO();
    HttpEntity<CredentialsVO> entity = new HttpEntity<CredentialsVO>(credentialsVO);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + simpleAuthenticationEndpointPath, HttpMethod.POST,
            entity, AuthorizationData.class);
    assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode());
}

From source file:ca.hec.tenjin.tool.controller.SyllabusController.java

@ExceptionHandler(SyllabusLockedException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public @ResponseBody SyllabusLockedException handleSyllabusLockedException(SyllabusLockedException ex) {
    return ex;//from   www. j ava2 s. co m
}

From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testPasswordRequired() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    Map<String, String> requestBody = new HashMap<>();
    requestBody.put("username", testAccounts.getUserName());

    try {//from ww  w  .jav  a2s  . co m
        restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody, headers),
                Map.class);
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:org.osiam.addons.selfadministration.controller.ChangeEmailController.java

/**
 * Validating the confirm token and saving the new email value as primary email if the validation was successful.
 * //from w  w w .j a v a 2  s  .c o m
 * @param authorization
 *        Authorization header with HTTP Bearer authorization and a valid access token
 * @param userId
 *        The user id for the user whom email address should be changed
 * @param confirmToken
 *        The previously generated confirmation token from the confirmation email
 * @return The HTTP status code and the updated user if successful
 */
@RequestMapping(method = RequestMethod.POST, value = "/confirm", produces = "application/json")
public ResponseEntity<String> confirm(@RequestHeader("Authorization") final String authorization,
        @RequestParam("userId") final String userId, @RequestParam("confirmToken") final String confirmToken)
        throws IOException, MessagingException {

    if (Strings.isNullOrEmpty(confirmToken)) {
        LOGGER.log(Level.WARNING, "Confirmation token miss match!");
        return getErrorResponseEntity("No ongoing email change!", HttpStatus.UNAUTHORIZED);
    }

    User updatedUser;
    Optional<Email> oldEmail;

    try {
        AccessToken accessToken = new AccessToken.Builder(RegistrationHelper.extractAccessToken(authorization))
                .build();
        User user = connectorBuilder.createConnector().getUser(userId, accessToken);

        Extension extension = user.getExtension(internalScimExtensionUrn);
        String existingConfirmToken = extension.getField(confirmationTokenField, ExtensionFieldType.STRING);

        if (!existingConfirmToken.equals(confirmToken)) {
            LOGGER.log(Level.WARNING, "Confirmation token mismatch!");
            return getErrorResponseEntity("No ongoing email change!", HttpStatus.FORBIDDEN);
        }

        String newEmail = extension.getField(tempEmail, ExtensionFieldType.STRING);
        oldEmail = SCIMHelper.getPrimaryOrFirstEmail(user);

        UpdateUser updateUser = getPreparedUserForEmailChange(extension, newEmail, oldEmail.get());

        updatedUser = connectorBuilder.createConnector().updateUser(userId, updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.log(Level.WARNING, e.getMessage());
        return getErrorResponseEntity(e.getMessage(), HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        return getErrorResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    Locale locale = RegistrationHelper.getLocale(updatedUser.getLocale());

    // build the Map with the link for replacement
    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("user", updatedUser);

    try {
        renderAndSendEmailService.renderAndSendEmail("changeemailinfo", fromAddress, oldEmail.get().getValue(),
                locale, mailVariables);
    } catch (OsiamException e) {
        return getErrorResponseEntity("Problems creating email for confirming new user: \"" + e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java

@SuppressWarnings("deprecation")
private RestTemplate setErrorHandler(final RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        private final Set<HttpStatus> errorStatuses = new HashSet<>();

        /* non-static */ {
            errorStatuses.add(HttpStatus.BAD_REQUEST);
            errorStatuses.add(HttpStatus.UNAUTHORIZED);
            errorStatuses.add(HttpStatus.FORBIDDEN);
            errorStatuses.add(HttpStatus.NOT_FOUND);
            errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED);
            errorStatuses.add(HttpStatus.NOT_ACCEPTABLE);
            errorStatuses.add(HttpStatus.REQUEST_TIMEOUT);
            errorStatuses.add(HttpStatus.CONFLICT);
            errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
            errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG);
            errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS);
            errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR);
            errorStatuses.add(HttpStatus.NOT_IMPLEMENTED);
            errorStatuses.add(HttpStatus.BAD_GATEWAY);
            errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE);
        }//  w  ww  .j  a  va2 s . c o  m

        @Override
        public boolean hasError(final ClientHttpResponse response) throws IOException {
            return errorStatuses.contains(response.getStatusCode());
        }

        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText());
            System.err.println(readBody(response));
        }

        private String readBody(final ClientHttpResponse response) throws IOException {
            BufferedReader responseBodyReader = null;

            try {
                responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody()));

                StringBuilder buffer = new StringBuilder();
                String line;

                while ((line = responseBodyReader.readLine()) != null) {
                    buffer.append(line).append(System.getProperty("line.separator"));
                }

                return buffer.toString().trim();
            } finally {
                FileSystemUtils.close(responseBodyReader);
            }
        }
    });

    return restTemplate;
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void simpleAuthenticationServiceTestInvalidCredentials() throws Exception {
    CredentialsVO credentialsVO = new CredentialsVO();
    credentialsVO.setUsername("user");
    credentialsVO.setPassword("badpassword");
    HttpEntity<CredentialsVO> entity = new HttpEntity<CredentialsVO>(credentialsVO);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + simpleAuthenticationEndpointPath, HttpMethod.POST,
            entity, AuthorizationData.class);
    assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode());
}

From source file:org.osiam.addons.selfadministration.controller.LostPasswordController.java

/**
 * Method to change the users password if the preconditions are satisfied.
 * /* w ww  .  j a v a 2s.  co  m*/
 * @param authorization
 *        authZ header with valid access token
 * @param oneTimePassword
 *        the previously generated one time password
 * @param newPassword
 *        the new user password
 * @return the response with status code and the updated user if successfully
 * @throws IOException
 */
@RequestMapping(value = "/change", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> change(@RequestHeader("Authorization") final String authorization,
        @RequestParam String oneTimePassword, @RequestParam String newPassword) throws IOException {

    if (Strings.isNullOrEmpty(oneTimePassword)) {
        String errorMessage = "The submitted one time password is invalid!";
        LOGGER.log(Level.SEVERE, errorMessage);
        return getErrorResponseEntity(errorMessage, HttpStatus.UNAUTHORIZED);
    }

    User updatedUser;
    try {
        AccessToken accessToken = new AccessToken.Builder(RegistrationHelper.extractAccessToken(authorization))
                .build();
        User user = connectorBuilder.createConnector().getCurrentUser(accessToken);

        // validate the oneTimePassword with the saved one from DB
        Extension extension = user.getExtension(internalScimExtensionUrn);
        String savedOneTimePassword = extension.getField(this.oneTimePassword, ExtensionFieldType.STRING);

        if (!savedOneTimePassword.equals(oneTimePassword)) {
            LOGGER.log(Level.SEVERE, "The submitted one time password is invalid!");
            return getErrorResponseEntity("The submitted one time password is invalid!", HttpStatus.FORBIDDEN);
        }

        UpdateUser updateUser = getPreparedUserToChangePassword(extension, newPassword);
        updatedUser = connectorBuilder.createConnector().updateUser(user.getId(), updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.log(Level.WARNING, e.getMessage());
        return getErrorResponseEntity(e.getMessage(), HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        return getErrorResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testClientAuthorization() throws Exception {
    Map<String, String> requestBody = new HashMap<>();
    requestBody.put("username", testAccounts.getUserName());
    requestBody.put("password", testAccounts.getPassword());

    try {//  w w w . ja  v a2s  . co m
        restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody),
                Map.class);
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.controllers.ManagerController.java

private void getErrorResponseEntityBasicAuth(HttpServletResponse resp) throws IOException {
    String errorMessage = "401 Unauthorized";

    resp.setHeader("WWW-Authenticate", "Basic realm=\"Download Realm\"");
    resp.setStatus(HttpStatus.UNAUTHORIZED.value());
    OutputStream outputStream = resp.getOutputStream();
    try {//  www  . j  a  v a2 s .co m
        outputStream.write(errorMessage.getBytes());
    } finally {
        Closeables.close(outputStream, true);
    }

}