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:org.shaigor.rest.retro.service.security.IntegrationTest.java

/**
 * Logic to test unauthorized access to protected resource
 * @param uri/*from   w w w .j  a va 2 s .c  o  m*/
 */
protected void testInvalidTokenErrorMessge(String uri) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer FOO");
    ResponseEntity<String> response = helper.getForResponse(uri, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    String authenticate = response.getHeaders().getFirst("WWW-Authenticate");
    assertTrue("Wrong header: " + authenticate, authenticate.contains("error=\"invalid_token\""));
}

From source file:org.craftercms.profile.services.AuthenticationServiceIT.java

@Test
@DirtiesContext//  w  ww. j a va2 s . co  m
public void testMissingAccessTokenIdParamError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(null);

    try {
        authenticationService.authenticate(DEFAULT_TENANT_NAME, ADMIN_USERNAME, ADMIN_PASSWORD);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatus());
        assertEquals(ErrorCode.MISSING_ACCESS_TOKEN_ID_PARAM, e.getErrorCode());
    }
}

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

@ExceptionHandler({ AuthenticationException.class, UnauthorizedException.class })
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public void handleUnauthorizedExceptions(Exception e, HttpServletResponse response) {
    respond(e, "errors.unauthorized", response);
}

From source file:org.cloudfoundry.identity.uaa.integration.NativeApplicationIntegrationTests.java

/**
 * tests that an error occurs if you attempt to use bad client credentials.
 *///w w  w.  ja  v  a  2s.com
@Test
// Need a custom auth entry point to get the correct JSON response here.
public void testInvalidClient() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    List<String> newCookies = response.getHeaders().get("Set-Cookie");
    if (newCookies != null && !newCookies.isEmpty()) {
        fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
    }
    assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));

    @SuppressWarnings("unchecked")
    OAuth2Exception error = OAuth2Exception.valueOf(response.getBody());
    assertEquals("invalid_client", error.getOAuth2ErrorCode());
}

From source file:ch.heigvd.gamification.api.PointScalesEndpoint.java

@Override
@RequestMapping(value = "/{pointScaleId}", method = RequestMethod.GET)
public ResponseEntity<PointScaleDTO> pointScalesPointScaleIdGet(
        @ApiParam(value = "pointScaleId", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "pointScaleId", required = true) @PathVariable("pointScaleId") Long pointScaleId) {

    AuthenKey apiKey = authenRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }/*from ww  w  .ja v a2s. c  o m*/

    PointScale p = pointscaleRepository.findByIdAndApp(pointScaleId, apiKey.getApp());

    if (p == null) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }

    PointScaleDTO dto = toDTO(p);
    dto.setId(p.getId());

    return new ResponseEntity(dto, HttpStatus.CREATED);
}

From source file:org.cloudfoundry.identity.uaa.login.integration.AutologinContollerIntegrationTests.java

@Test
public void testUnauthorizedWithoutPassword() {
    AutologinRequest request = new AutologinRequest();
    request.setUsername(testAccounts.getUserName());
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/autologin"),
            HttpMethod.POST, new HttpEntity<AutologinRequest>(request, headers), 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:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping("/unauthorized")
public Callable<ResponseEntity<Message>> unauthorized() {
    return () -> {
        final Message message = new Message();
        message.setValue("Hello, world!");
        return new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED);
    };/*from  w  w w  .j  a  v  a2 s .  c om*/
}

From source file:org.craftercms.profile.services.TenantServiceIT.java

@Test
@DirtiesContext/*from w  ww  .  j a v  a2  s . co m*/
public void testMissingAccessTokenIdParamError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(null);

    try {
        tenantService.createTenant(getCorporateTenant());
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatus());
        assertEquals(ErrorCode.MISSING_ACCESS_TOKEN_ID_PARAM, e.getErrorCode());
    }
}

From source file:org.lanqiao.examples.library.functional.BookEndpointTest.java

@Test
public void applyRequestWithError() {
    // token/*from  ww  w.ja v  a  2  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);

    BookDto 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.devnexus.ting.web.controller.CalendarController.java

@RequestMapping(value = "/{eventKey}/usercalendar/{id}", method = { RequestMethod.POST, RequestMethod.PUT })
@ResponseBody//  w  w  w.  j av  a2s. c  om
public ResponseEntity<UserCalendar> updateCalendar(@PathVariable("eventKey") String eventKey,
        @PathVariable("id") String id, HttpServletRequest request) {

    HttpHeaders headers = new HttpHeaders();

    if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) {
        headers.add("WWW-Authenticate", "Google realm=\"http://www.devnexus.org\"");
        return new ResponseEntity<>(new UserCalendar(), headers, HttpStatus.UNAUTHORIZED);
    }

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    UserCalendar calendar = null;
    try {
        calendar = GSON.fromJson(request.getReader(), UserCalendar.class);

        calendar = calendarService.updateEntry(calendar.getId(), user, calendar);

        UnifiedMessage unifiedMessage = new UnifiedMessage.Builder().pushApplicationId(PUSH_APP_ID)
                .masterSecret(PUSH_APP_SECRET).aliases(Arrays.asList(user.getEmail()))
                .attribute("org.devnexus.sync.UserCalendar", "true").build();

        javaSender.send(unifiedMessage);

        return new ResponseEntity<>(calendar, headers, HttpStatus.OK);
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e);
        throw new RuntimeException(e);
    }

}