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.DELETE)
public ResponseEntity<Void> badgesBadgeIdDelete(
        @ApiParam(value = "badgeId", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "badgeId", required = true) @PathVariable("badgeId") Long badgeId) {

    AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }//from   ww  w . j  ava 2 s.  c o m

    Application app = apiKey.getApp();
    Badge badge = badgeRepository.findByIdAndApp(badgeId, app);

    if (badge != null && app != null) {
        badgeRepository.delete(badge);
        return new ResponseEntity(HttpStatus.OK);
    } else {
        return new ResponseEntity("no content is valid", HttpStatus.NOT_FOUND);
    }
}

From source file:io.github.autsia.crowly.controllers.rest.AuthenticationController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<String> login(@RequestBody CrowlyUser user, HttpServletResponse response) {
    try {/* ww w. j av a 2s .c om*/
        Authentication request = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
        Authentication result = authenticationManager.authenticate(request);
        SecurityContextHolder.getContext().setAuthentication(result);
        return new ResponseEntity<>(HttpStatus.OK);
    } catch (AuthenticationException e) {
        logger.warn("Failed login attempt for username: " + e.getMessage());
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    }
}

From source file:ar.com.aleatoria.ue.rest.SimpleClientHttpResponse.java

public String getStatusText() throws IOException {
    try {//from  www  . j av  a 2  s .c om
        return this.connection.getResponseMessage();
    } catch (IOException ex) {
        /* 
         * If credentials are incorrect or not provided for Basic Auth, then 
         * Android throws this exception when an HTTP 401 is received. Checking 
         * for this response and returning the proper status.
         */
        if (ex.getLocalizedMessage().equals(AUTHENTICATION_ERROR)) {
            return HttpStatus.UNAUTHORIZED.getReasonPhrase();
        } else {
            throw ex;
        }
    }
}

From source file:org.zaizi.AuthServerApplicationTests.java

@Test
public void homePageProtected() {
    ResponseEntity<String> response = template.getForEntity("http://localhost:" + port + contextPath + "/",
            String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    String auth = response.getHeaders().getFirst("WWW-Authenticate");
    assertTrue("Wrong header: " + auth, auth.startsWith("Bearer realm=\""));
}

From source file:sample.jetty.SampleJetty8ApplicationTests.java

@Test
public void testHomeBasicAuthNoCredentials403() throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate()
            .getForEntity("http://localhost:" + this.port + "/static.html", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
}

From source file:com.abdin.noorsingles.web.AdminController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody ResponseEntity login(HttpServletRequest request, @RequestParam("username") String username,
        @RequestParam("paswd") String password) {

    HttpSession session = request.getSession(true);

    adminService.authenticate(username, password, session);

    if (adminService.isAuthenticated(session)) {
        return new ResponseEntity(HttpStatus.ACCEPTED);
    } else {/*ww  w.  j a va  2  s . c  om*/
        return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }
}

From source file:com.ge.predix.acs.commons.web.RestErrorHandler.java

/**
 * Handles the given exception and generates a response with error code and message description.
 *
 * @param e/*from   w ww.  j  av a 2 s .  c  o  m*/
 *            Given exception
 * @param request
 *            The http request
 * @param response
 *            The http response
 * @return The model view with the error response
 */
@SuppressWarnings("nls")
public ModelAndView createApiErrorResponse(final Exception e, final HttpServletRequest request,
        final HttpServletResponse response) {
    LOGGER.error(e.getMessage(), e);
    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    RestApiErrorResponse restApiErrorResponse = new RestApiErrorResponse();

    if (e instanceof RestApiException) {
        RestApiException restEx = (RestApiException) e;
        response.setStatus(restEx.getHttpStatusCode().value());
        restApiErrorResponse.setErrorMessage(restEx.getMessage());
        restApiErrorResponse.setErrorCode(restEx.getAppErrorCode());
    } else if (IllegalArgumentException.class.isAssignableFrom(e.getClass())) {
        // Illegal argument exceptions mapped to 400 errors by default
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        restApiErrorResponse.setErrorMessage(e.getMessage());
    } else if (UntrustedIssuerException.class.isAssignableFrom(e.getClass())
            || SecurityException.class.isAssignableFrom(e.getClass())) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        restApiErrorResponse.setErrorMessage(e.getMessage());
    } else if (HttpMessageNotReadableException.class.isAssignableFrom(e.getClass())) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        restApiErrorResponse.setErrorMessage("Malformed JSON syntax. " + e.getLocalizedMessage());
    }

    return new ModelAndView(new MappingJackson2JsonView(), "ErrorDetails", restApiErrorResponse);
}

From source file:io.kahu.hawaii.util.exception.HawaiiExceptionTest.java

@Test
public void testGetStatus() throws Exception {

    ServerException e = new ServerException(TestServerError.S1);
    Assert.assertTrue(HttpStatus.INTERNAL_SERVER_ERROR.equals(e.getStatus()));

    AuthenticationException auth = new AuthenticationException();
    Assert.assertTrue(HttpStatus.FORBIDDEN.equals(auth.getStatus()));

    AuthorisationException autho = new AuthorisationException();
    Assert.assertTrue(HttpStatus.UNAUTHORIZED.equals(autho.getStatus()));

    ValidationException v = new ValidationException();
    Assert.assertTrue(HttpStatus.BAD_REQUEST.equals(v.getStatus()));
}

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

@Override
@RequestMapping(value = "/{pointScaleId}", method = RequestMethod.DELETE)
public ResponseEntity<Void> pointScalesPointScaleIdDelete(
        @ApiParam(value = "pointScaleIdt", 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. j  a v  a  2s  . c o  m

    PointScale pointScale = pointscaleRepository.findOne(pointScaleId);

    if (pointScale != null) {
        pointscaleRepository.delete(pointScale);
        return new ResponseEntity(HttpStatus.OK);
    } else {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
}

From source file:md.ibanc.rm.validators.CustomersValidator.java

public void validate() {
    if (customers == null) {
        CustomersDetails customersDetails = new CustomersDetails();
        customersDetails.setReturnCode(RetCodeConst.CUSTOMERS_NOT_FOUND);
        customersDetails.setReturnDescription(RetDescriptionConst.CUSTOMERS_NOT_FOUND);
        responseEntity = new ResponseEntity<>(customersDetails, HttpStatus.UNAUTHORIZED);
        isCustomersValid = false;//from w  ww.  ja va  2s . c  o m
        return;
    }

    String hashPassword = UtilHashMD5.createMD5Hash(
            FormatPassword.CreatePassword(customers.getRegisteDate().getSeconds(), loginForm.getmPassword()));

    if (!hashPassword.equals(customers.getPassword())) {
        CustomersDetails customersDetails = new CustomersDetails();
        customersDetails.setReturnCode(RetCodeConst.FAIL_PASSWORD);
        customersDetails.setReturnDescription(RetDescriptionConst.FAIL_PASSWORD);
        responseEntity = new ResponseEntity<>(customersDetails, HttpStatus.UNAUTHORIZED);
        isCustomersValid = false;

        WrongPasswordThread wrongPasswordThread = new WrongPasswordThread(customers, loginForm, request);

        wrongPasswordThread.setCustomersService(customersService);
        wrongPasswordThread.setDevicesService(devicesService);
        wrongPasswordThread.setMessageService(messageService);
        wrongPasswordThread.setWrongPasswordService(wrongPasswordService);
        wrongPasswordThread.setStatusService(statusService);

        wrongPasswordThread.start();

        return;
    }

    switch (customers.getStatus().getName()) {
    case StatusCodeConst.PASSWORD_EXPIRE: {
        CustomersDetails customersDetails = new CustomersDetails();
        customersDetails.setReturnCode(RetCodeConst.PASSWORD_EXPIRE);
        customersDetails.setReturnDescription(RetDescriptionConst.PASSWORD_EXPIRE);
        responseEntity = new ResponseEntity<>(customersDetails, HttpStatus.UNAUTHORIZED);
        isCustomersValid = false;
        return;
    }

    case StatusCodeConst.BLOCK_ACCOUNT: {
        CustomersDetails customersDetails = new CustomersDetails();
        customersDetails.setReturnCode(RetCodeConst.BLOCK_ACCOUNT);
        customersDetails.setReturnDescription(RetDescriptionConst.BLOCK_ACCOUNT);
        responseEntity = new ResponseEntity<>(customersDetails, HttpStatus.UNAUTHORIZED);
        isCustomersValid = false;
        return;
    }

    }

    if (!customers.getStatus().getName().equals(StatusCodeConst.ACTIVE)) {
        CustomersDetails customersDetails = new CustomersDetails();
        customersDetails.setReturnCode(RetCodeConst.UNAUTHORIZED);
        customersDetails.setReturnDescription(RetDescriptionConst.UNAUTHORIZED);
        responseEntity = new ResponseEntity<>(customersDetails, HttpStatus.UNAUTHORIZED);
        isCustomersValid = false;
    } else {
        CustomersDetails customersDetails = new CustomersDetails();
        customersDetails.setReturnCode(RetCodeConst.RETCOD_OK);
        customersDetails.setReturnDescription(RetDescriptionConst.RETCOD_OK);
        responseEntity = new ResponseEntity<>(customersDetails, HttpStatus.OK);
        isCustomersValid = true;
        customers.setUnSuccessfulAtempst(0);
        customersService.save(customers);

    }
}