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:ch.heigvd.gamification.api.BadgesEndpoint.java

@Override
@RequestMapping(value = "/{badgeId}", method = RequestMethod.PUT)
public ResponseEntity<Void> badgesBadgeIdPut(
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "Badge's id", required = true) @PathVariable("badgeId") Long badgeId,
        @ApiParam(value = "Modification of the badge") @RequestBody BadgeDTO body) {

    AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }//from w w w  .  ja va  2  s.co m
    Application app = apiKey.getApp();

    if (app != null) {

        Badge badge = badgeRepository.findByIdAndApp(badgeId, app);
        if (badge == null) {
            return new ResponseEntity("no content is available", HttpStatus.NOT_FOUND);
        }

        if (body.getDescription() != null) {

            if (!body.getDescription().equals(" ")) {
                badge.setDescription(body.getDescription());
            } else {
                body.setDescription(badge.getDescription());
            }
        }

        if (body.getImageURI() != null) {
            if (!body.getImageURI().equals(" ") || body.getImageURI() != null) {
                badge.setImage(body.getImageURI());
            } else {
                body.setImageURI(badge.getImage());
            }
        }
        if (body.getName() != null) {
            if (!body.getName().equals(" ") || body.getName() != null) {
                badge.setName(body.getName());
            } else {
                body.setName(badge.getName());
            }
        }

        badgeRepository.save(badge);
        return new ResponseEntity(HttpStatus.OK);
    } else {

        return new ResponseEntity("no content is available", HttpStatus.NOT_FOUND);

    }
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.basic.services.presentation.BasicAuthenticationServiceImpl.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest/*from   w  w  w  .j  av a 2 s .  co  m*/
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@RequestMapping(value = "${appverse.frontfacade.rest.basicAuthenticationEndpoint.path:/sec/login}", method = RequestMethod.POST)
public ResponseEntity<AuthorizationData> login(@RequestHeader("Authorization") String authorizationHeader,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    String[] userNameAndPassword;

    try {
        userNameAndPassword = obtainUserAndPasswordFromBasicAuthenticationHeader(httpServletRequest);
    } catch (BadCredentialsException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED);
    }

    if (securityEnableCsrf) {
        // Obtain XSRFToken and add it as a response header
        // The token comes in the request (CsrFilter adds it) and we need to set it in the response so the clients 
        // have it to use it in the next requests
        CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute(CSRF_TOKEN_SESSION_ATTRIBUTE);
        httpServletResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken());
    }

    try {
        // Authenticate principal and return authorization data
        AuthorizationData authData = userAndPasswordAuthenticationManager
                .authenticatePrincipal(userNameAndPassword[0], userNameAndPassword[1]);
        // AuthorizationDataVO
        return new ResponseEntity<AuthorizationData>(authData, HttpStatus.OK);
    } catch (AuthenticationException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED);
    }
}

From source file:eu.cloudwave.wp5.feedbackhandler.metricsources.NewRelicClient.java

/**
 * {@inheritDoc}/*from  w  ww  . j a  v  a 2 s .c  om*/
 */
@Override
protected void handleHttpServerException(final HttpStatusCodeException serverError)
        throws MetricSourceClientException, IOException {
    // if the status code is 401 UNAUTHORIZED -> the API key is not valid
    if (serverError.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
        throw new MetricSourceClientException(ErrorType.NEW_RELIC__INVALID_API_KEY,
                Messages.ERRORS__NEW_RELIC__INVALID_API_KEY);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode errorNode = mapper.readTree(serverError.getResponseBodyAsString());
    final JsonNode titleNode = errorNode.findValue(JSON__TITLE);
    if (titleNode != null) {
        final String message = titleNode.asText();
        ErrorType type = ErrorType.NEW_RELIC__GENERAL;

        if (message.contains(ERROR__INVALID_APPLICATION_ID)
                || message.equals(ERROR__INVALID_PARAMETER_APPLICATION_ID)) {
            type = ErrorType.NEW_RELIC__INVALID_APPLICATION_ID;
        } else if (message.contains(ERROR__UNKNOWN_METRIC)) {
            type = ErrorType.UNKNOWN_METRIC;
        } else if (message.contains(ERROR__INVALID_PARAMETER)) {
            type = ErrorType.INVALID_PARAMETER;
        }
        throw new MetricSourceClientException(type, message);
    }
}

From source file:net.prasenjit.auth.config.CustomAjaxAwareHandler.java

/** {@inheritDoc} */
@Override//from ww  w  . j a va  2 s. com
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (checkIfAjaxRequest(request)) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    } else {
        delegatedAuthenticationEntryPoint.commence(request, response, authException);
    }
}

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

@ApiOperation(value = "Edit 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.PUT)
public ResponseEntity<String> editPrintShopReview(@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  ava 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);

    String reviewText = request.getParameter("review");
    int rating = Integer.parseInt(request.getParameter("rating"));

    review.setDescription(reviewText);
    review.setRating(rating);

    pShop.addReview(review);
    pShop.updatePrintShopRating();

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

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

@Test
public void testProtectedResourceIsProtected() throws Exception {
    ResponseEntity<String> response = restTemplate
            .getForEntity(resourceServerBaseUrl + baseApiPath + "/protected", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    assertTrue("Wrong header: " + response.getHeaders(),
            response.getHeaders().getFirst("WWW-Authenticate").startsWith("Bearer realm="));
}

From source file:org.jasig.portlet.notice.service.ssp.SSPApi.java

/**
 * {@inheritDoc}/*from  w  w  w .  j a v  a2s.  c  o m*/
 */
@Override
public <T> ResponseEntity<T> doRequest(SSPApiRequest<T> request)
        throws MalformedURLException, RestClientException {
    SSPToken token = getAuthenticationToken(false);

    request.setHeader(AUTHORIZATION, token.getTokenType() + " " + token.getAccessToken());

    URL url = getSSPUrl(request.getUrlFragment(), true);
    ResponseEntity<T> response = restTemplate.exchange(url.toExternalForm(), request.getMethod(),
            request.getRequestEntity(), request.getResponseClass(), request.getUriParameters());
    // if we get a 401, the token may have unexpectedly expired (eg. ssp server restart).
    // Clear it, get a new token and replay the request one time.
    if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        token = getAuthenticationToken(true);
        request.setHeader(AUTHORIZATION, token.getTokenType() + " " + token.getAccessToken());
        return restTemplate.exchange(url.toExternalForm(), request.getMethod(), request.getRequestEntity(),
                request.getResponseClass(), request.getUriParameters());
    }

    return response;
}

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

/**
 * tests that a client secret is required.
 *//*from   w  w w .  j  a va2  s  .  c o m*/
@Test
public void testSecretRequired() 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));
    ResponseEntity<String> response = serverRunning.postForString("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}

From source file:de.zib.gndms.gndmc.dspace.Test.SliceClientTest.java

@Test(groups = { "sliceServiceTest" })
public void testCreateSubspace() {
    final String mode = "CREATE";

    ResponseEntity<Facets> subspace = null;
    try {//from ww w .  ja  va2  s. c om
        subspace = subspaceClient.createSubspace(subspaceId, subspaceConfig, admindn);

        Assert.assertNotNull(subspace);
        Assert.assertEquals(subspace.getStatusCode(), HttpStatus.CREATED);
    } catch (HttpClientErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.UNAUTHORIZED))
            throw e;
    }

    final ResponseEntity<Facets> res = subspaceClient.listAvailableFacets(subspaceId, admindn);
    Assert.assertNotNull(res);
    Assert.assertEquals(res.getStatusCode(), HttpStatus.OK);
}

From source file:org.awesomeagile.testing.google.FakeGoogleController.java

@ResponseBody
@ExceptionHandler({ AuthenticationException.class })
public ResponseEntity<String> handleAuthenticationException(AuthenticationException ex) {
    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ex.getMessage());
}