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:com.hypersocket.auth.json.AuthenticatedController.java

@ExceptionHandler(SessionTimeoutException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public void sessionTimeout(HttpServletRequest request, HttpServletResponse response,
        UnauthorizedException redirect) {

}

From source file:com.javiermoreno.springboot.rest.App.java

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
    //factory.setPort(7777); (est definido en el application.properties
    factory.setSessionTimeout(10, TimeUnit.MINUTES);
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errores/error404.html"),
            new ErrorPage(HttpStatus.UNAUTHORIZED, "/errores/error401.html"),
            new ErrorPage(HttpStatus.FORBIDDEN, "/errores/error403.html"));
    // Activacin gzip sobre http (*NO* activar sobre ssl, induce ataques.)
    // http://stackoverflow.com/questions/21410317/using-gzip-compression-with-spring-boot-mvc-javaconfig-with-restful
    factory.addConnectorCustomizers((TomcatConnectorCustomizer) (Connector connector) -> {
        AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
        httpProtocol.setCompression("on");
        httpProtocol.setCompressionMinSize(256);
        String mimeTypes = httpProtocol.getCompressableMimeTypes();
        String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
        httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
    });/* www  .j av  a2s.co m*/

    factory.addAdditionalTomcatConnectors(createSslConnector());
    /* En el caso de que se desee sustitur http por https: ************************
     // keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
     final String keystoreFilePath = "keystore.p12";
     final String keystoreType = "PKCS12";
     final String keystoreProvider = "SunJSSE";
     final String keystoreAlias = "tomcat"; 
     factory.addConnectorCustomizers((TomcatConnectorCustomizer) (Connector con) -> {
     con.setScheme("https");
     con.setSecure(true);
     Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
     proto.setSSLEnabled(true);
     // @todo: Descarga el fichero con el certificado actual 
     File keystoreFile = new File(keystoreFilePath);
     proto.setKeystoreFile(keystoreFile.getAbsolutePath());
     proto.setKeystorePass(remoteProps.getKeystorePass());
     proto.setKeystoreType(keystoreType);
     proto.setProperty("keystoreProvider", keystoreProvider);
     proto.setKeyAlias(keystoreAlias);
     });
     ***************************************************************************** */
    return factory;
}

From source file:com.cfitzarl.cfjwed.controller.ApiExceptionHandler.java

@ExceptionHandler({ BadCredentialsException.class })
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public void handleBadCredsException(BadCredentialsException e, HttpServletResponse response) {
    respond(e, "errors.creds", response);
}

From source file:org.springside.examples.bootapi.functional.BookEndpointTest.java

@Test
public void applyRequestWithError() {
    // token// w  ww . j  ava2  s.c o  m
    ResponseEntity<String> response = restTemplate.getForEntity(resourceUrl + "/{id}/request", String.class,
            1L);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    ErrorResult errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.NO_TOKEN.code);

    Book book = bookDao.findOne(1L);
    assertThat(book.borrower).isNull();

    // token
    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 1L, "abc");
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
    errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.UNAUTHORIZED.code);

    book = bookDao.findOne(1L);
    assertThat(book.borrower).isNull();

    // 
    String token = login("calvin.xiao@springside.io");

    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 1L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
    errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.BOOK_OWNERSHIP_WRONG.code);

    book = bookDao.findOne(1L);
    assertThat(book.borrower).isNull();

    logout(token);

    // 
    token = login("calvin.xiao@springside.io");

    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 3L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

    response = restTemplate.getForEntity(resourceUrl + "/{id}/request?token={token}", String.class, 3L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
    errorResult = jsonMapper.fromJson(response.getBody(), ErrorResult.class);
    assertThat(errorResult.code).isEqualTo(ErrorCode.BOOK_STATUS_WRONG.code);

    // ?
    response = restTemplate.getForEntity(resourceUrl + "/{id}/cancel?token={token}", String.class, 3L, token);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

    logout(token);
}

From source file:com.indeed.iupload.web.controller.AppController.java

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedOperationException.class)
public @ResponseBody BasicResponse handleResourceNotFoundException() {
    return BasicResponse.error("You are not allowed to process this operation");
}

From source file:org.createnet.raptor.auth.service.controller.TokenController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/token/{tokenId}", method = RequestMethod.PUT)
@ApiOperation(value = "Update a token", notes = "", response = Token.class, nickname = "updateToken")
public ResponseEntity<?> update(@AuthenticationPrincipal User user, @PathVariable Long tokenId,
        @RequestBody Token token) {/* w w w .j  av  a 2s . c om*/

    // TODO add ACL checks        
    if (user.getId().longValue() != token.getUser().getId().longValue()) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(new JsonErrorResponse(HttpStatus.UNAUTHORIZED.value(), "Not authorized"));
    }

    if (token.getSecret().isEmpty()) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new JsonErrorResponse(400, "Secret cannot be empty"));
    }

    token.setId(tokenId);

    // Generate the JWT token
    tokenService.generateToken(token);

    return ResponseEntity.status(HttpStatus.OK).body(tokenService.update(token));
}

From source file:com.wiiyaya.consumer.web.main.controller.ExceptionController.java

/**
 * ??// w w  w  .  j  a v a2 s  . c o m
 * @param request ?
 * @return ExceptionDto JSON
 */
@ExceptionHandler(value = MaxSessionException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView maxSessionException(HttpServletRequest request) {
    String errorMessage = messageSource.getMessage(MSG_ERROR_SESSION_MAXIMUM, null,
            LocaleContextHolder.getLocale());
    return prepareExceptionInfo(request, HttpStatus.UNAUTHORIZED, MSG_ERROR_SESSION_MAXIMUM, errorMessage);
}

From source file:org.osiam.addons.self_administration.controller.AccountManagementService.java

/**
 * Logs the given exception and returns a suitable response status.
 * /*w  w  w. j a va  2 s . c  o m*/
 * @param e
 *            the exception to handle
 * @param {@link ResponseEntity} with the resulting error information and status code
 */
public ResponseEntity<String> handleException(RuntimeException e) {
    StringBuilder messageBuilder = new StringBuilder();
    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;

    if (e instanceof MailException) {
        messageBuilder.append("Failed to send email: ");
    } else if (e instanceof UnauthorizedException) {
        messageBuilder.append("Authorization failed: ");
        status = HttpStatus.UNAUTHORIZED;
    } else if (e instanceof NoResultException) {
        messageBuilder.append("No such entity: ");
        status = HttpStatus.NOT_FOUND;
    } else {
        messageBuilder.append("An exception occurred: ");
    }
    LOGGER.error(messageBuilder.toString());
    messageBuilder.insert(0, "{\"error\":\"");
    messageBuilder.append(e.getMessage());
    messageBuilder.append("\"}");
    return new ResponseEntity<String>(messageBuilder.toString(), status);
}

From source file:org.openlmis.fulfillment.service.BaseCommunicationServiceTest.java

@Test
public void shouldRetryObtainingAccessTokenIfResponseBodyIsEmpty() throws Exception {
    // given//  w  ww. jav  a  2  s.c o  m
    BaseCommunicationService<T> service = prepareService();
    HttpStatusCodeException exception = mock(HttpStatusCodeException.class);
    when(exception.getStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED);
    when(exception.getResponseBodyAsString()).thenReturn("");

    // when
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class),
            eq(service.getArrayResultClass()))).thenThrow(exception);

    expectedException.expect(DataRetrievalException.class);
    service.findAll("", RequestParameters.init());

    verify(authService, times(1)).clearTokenCache();
    verify(authService, times(2)).obtainAccessToken();
}