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.awesomeagile.webapp.security.BasicSecurityConfigTest.java

/**
 * Returns a ResultMatcher that asserts that the result status is either 401 (Unauthorized).
 *
 * @return a ResultMatcher/*  w ww .j a  v a  2  s .c  o m*/
 */
private ResultMatcher isUnauthorized() {
    return new ResultMatcher() {
        @Override
        public void match(MvcResult result) throws Exception {
            HttpStatus status = HttpStatus.valueOf(result.getResponse().getStatus());
            assertTrue("Response status", status == HttpStatus.UNAUTHORIZED);
        }
    };
}

From source file:cloudserviceapi.app.controller.SRCrudService.java

@ApiOperation(httpMethod = "POST", value = "Resource to create/change an item", nickname = "saveSR")
@ApiImplicitParams({// w w  w.j  ava2s .c  o m
        @ApiImplicitParam(name = "sr", defaultValue = "", value = "Service Registry JSON object", required = true, dataType = "tapp.model.ServiceRegistry", paramType = "body") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
        @ApiResponse(code = 401, message = "Failure") })
@RequestMapping(value = "/saveSR", method = RequestMethod.POST, consumes = {
        "application/json;charset=UTF-8" }, produces = { "application/json;charset=UTF-8" })
@Secured("ROLE_ADMIN")
public @ResponseBody ResponseEntity<ServiceRegistry> createOrUpdate(@RequestBody ServiceRegistry sr) {
    try {
        if (sr != null) {
            //repository.save(sr);
            if (sr.getLastUpdated() == null) {
                sr.setLastUpdated(new Date());
            }
            (new ServiceRegistryDAO()).save(sr);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<ServiceRegistry>(HttpStatus.UNAUTHORIZED);
    }

    return new ResponseEntity<ServiceRegistry>(HttpStatus.OK);
}

From source file:org.echocat.marquardt.authority.spring.SpringAuthorityController.java

@ExceptionHandler(InvalidCertificateException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Invalid jsonWrappedCertificate.")
public void handleInvalidCertificateException(final InvalidCertificateException ex) {
    LOGGER.info(ex.getMessage());// w w  w  .  jav a2  s.  c  o  m
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

@Test
@OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false)
public void testUnauthenticatedAuthorizationRespondsUnauthorized() throws Exception {

    AccessTokenRequest request = context.getAccessTokenRequest();
    request.setCurrentUri("http://anywhere");
    request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");

    try {/*from ww w  .  ja v  a2 s.  co m*/
        String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request);
        assertNotNull(code);
        fail("Expected UserRedirectRequiredException");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }

}

From source file:com.appglu.impl.UserTemplateTest.java

@Test
public void loginUnauthorized() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/users/login")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", jsonMediaType.toString()))
            .andExpect(content().string(compactedJson("data/user_login")))
            .andRespond(withStatus(HttpStatus.UNAUTHORIZED).body(compactedJson("data/user_unauthorized"))
                    .headers(responseHeaders));

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    AuthenticationResult result = userOperations.login("username", "password");
    Assert.assertFalse(result.succeed());

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    Assert.assertEquals(ErrorCode.APP_USER_UNAUTHORIZED, result.getError().getCode());
    Assert.assertEquals("Unauthorized to access resource because credentials are wrong or missing.",
            result.getError().getMessage());

    mockServer.verify();/*from  www  . j  a  va 2  s  .c  om*/
}

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

@RequestMapping(method = RequestMethod.POST)
@Override/*  ww w.ja  va  2 s. co  m*/

public ResponseEntity<Void> pointScalesPost(
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "PointScale to add", required = true) @RequestBody PointScaleDTO body) {

    AuthenKey apiKey = authenRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }

    PointScale pointScale = new PointScale();
    Application app = apiKey.getApp();

    if (pointscaleRepository.findByNameAndApp(body.getName(), apiKey.getApp()) != null) {

        return new ResponseEntity("poinscat exist already", HttpStatus.UNPROCESSABLE_ENTITY);
    }

    if (body != null) {

        pointScale.setDescription(body.getDescription());
        pointScale.setName(body.getName());
        pointScale.setMinpoint(body.getNbrDePoints());
        pointScale.setApplication(app);
        pointScale.setApplication(app);
        pointscaleRepository.save(pointScale);

        StringBuffer location = request.getRequestURL();
        if (!location.toString().endsWith("/")) {
            location.append("/");
        }
        location.append(pointScale.getId().toString());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", location.toString());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);

    } else {
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
}

From source file:com.create.controller.AuthenticationIT.java

@Test
public void shouldReturnUnauthorizedForUnauthorizedUser() {
    final ResponseEntity<User> response = testRestTemplate.getForEntity(TEST_GET_PATH, User.class);
    assertThat(response.getStatusCode(), is(HttpStatus.UNAUTHORIZED));
}

From source file:org.echocat.marquardt.authority.spring.SpringAuthorityController.java

@ExceptionHandler(ExpiredSessionException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Session is expired.")
public void handleInvalidSessionException(final ExpiredSessionException ex) {
    LOGGER.info(ex.getMessage());/*from  w  w w .ja  v a2  s . com*/
}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

@Test
public void testRemoteLogIsProtected() throws Exception {
    RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO();
    remoteLogRequest.setLogLevel("DEBUG");
    remoteLogRequest.setMessage("This is my log message!");

    // We call remote log WITHOUT the access token
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath);
    ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);

    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    assertTrue("Wrong header: " + result.getHeaders(),
            result.getHeaders().getFirst("WWW-Authenticate").startsWith("Bearer realm="));
}

From source file:io.github.proxyprint.kitchen.controllers.printshops.ReviewController.java

@ApiOperation(value = "Delete an existing printshop review", notes = "404 if the printshop or the review doesn't exist.")
@Secured({ "ROLE_USER" })
@RequestMapping(value = "/printshops/{printShopId}/reviews/{reviewId}", method = RequestMethod.DELETE)
public ResponseEntity<String> deletePrintShopReview(@PathVariable("printShopId") long printShopId,
        @PathVariable("reviewId") long reviewId, Principal principal, WebRequest request) {
    PrintShop pShop = this.printshops.findOne(printShopId);
    if (pShop == null) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }//from   w w  w  .j  a  v  a 2 s .  c o m

    Review review = this.reviews.findOne(reviewId);
    if (review == null) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    } else if (!review.getConsumer().getUsername().equals(principal.getName())) {
        return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }

    pShop.removeReview(review);
    this.printshops.save(pShop);
    return new ResponseEntity(this.GSON.toJson(review), HttpStatus.OK);
}