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.alfresco.bm.dataload.rm.records.DeclareInPlaceRecordsUnitTest.java

@Test
public void testDeclareAsRecordWithFail() throws Exception {
    String fileId = "testFileId";
    String username = "testUserName";
    String password = "testPassword";
    String summary = "testSummary";
    String stack = "testStack";
    long delay = 10L;

    declareInPlaceRecords.setDeclareInPlaceRecordDelay(delay);
    Event mockedEvent = mock(Event.class);
    DBObject mockedData = mock(DBObject.class);
    when(mockedData.get(FIELD_ID)).thenReturn(fileId);
    when(mockedData.get(FIELD_USERNAME)).thenReturn(username);
    when(mockedData.get(FIELD_PASSWORD)).thenReturn(password);
    when(mockedEvent.getData()).thenReturn(mockedData);

    RecordData dbRecord = new RecordData(fileId, RecordContext.IN_PLACE_RECORD, "testFileName", "testFilePath",
            "testInPlacePath", ExecutionState.SCHEDULED);
    when(mockedRecordService.getRecord(fileId)).thenReturn(dbRecord);

    FilesAPI mockedFilesAPI = mock(FilesAPI.class);
    when(mockedRestAPIFactory.getFilesAPI(any(UserModel.class))).thenReturn(mockedFilesAPI);
    RMRestWrapper mockedRmRestWrapper = mock(RMRestWrapper.class);
    when(mockedRmRestWrapper.getStatusCode()).thenReturn(Integer.toString(HttpStatus.UNAUTHORIZED.value()));
    RestErrorModel mockedRestErrorModel = mock(RestErrorModel.class);
    when(mockedRestErrorModel.getBriefSummary()).thenReturn(summary);
    when(mockedRestErrorModel.getStackTrace()).thenReturn(stack);

    when(mockedRmRestWrapper.assertLastError()).thenReturn(mockedRestErrorModel);
    when(mockedRestAPIFactory.getRmRestWrapper()).thenReturn(mockedRmRestWrapper);

    EventResult result = declareInPlaceRecords.processEvent(mockedEvent, new StopWatch());
    assertEquals(true, result.isSuccess());
    assertEquals("Declaring file as record: \nFailed with code 401.\n " + summary + ". \n" + stack,
            result.getData());/*w  w  w.j a  v  a 2 s. c o m*/
    assertEquals(1, result.getNextEvents().size());
    assertEquals(declareInPlaceRecords.getEventNameInPlaceRecordsDeclared(),
            result.getNextEvents().get(0).getName());
}

From source file:org.apache.kylin.rest.controller.BasicController.java

@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException.class)
@ResponseBody//from  www . j  a  v a  2 s. co m
ErrorResponse handleUnauthorized(HttpServletRequest req, Exception ex) {
    return new ErrorResponse(req.getRequestURL().toString(), ex);
}

From source file:org.apache.metron.rest.controller.RestExceptionHandlerTest.java

@Test
public void handleControllerExceptionShouldProperlyReturnRestError() throws Exception {
    when(request.getAttribute("javax.servlet.error.status_code")).thenReturn(401);
    Throwable throwable = new RuntimeException("unauthorized");

    ResponseEntity responseEntity = restExceptionHandler.handleControllerException(request, throwable);
    assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode());
    RestError actualRestError = (RestError) responseEntity.getBody();
    assertEquals("unauthorized", actualRestError.getMessage());
    assertEquals("RuntimeException: unauthorized", actualRestError.getFullMessage());
    assertEquals(401, actualRestError.getResponseCode());
}

From source file:org.cloudfoundry.identity.uaa.account.PasswordChangeEndpoint.java

@ExceptionHandler
public View handleException(ScimResourceNotFoundException e) {
    // There's no point throwing BadCredentialsException here because it is
    // caught and
    // logged (then ignored) by the caller.
    return new ConvertingExceptionView(new ResponseEntity<>(
            new ExceptionReport(new BadCredentialsException("Invalid password change request"), false),
            HttpStatus.UNAUTHORIZED), messageConverters);
}

From source file:org.cloudfoundry.identity.uaa.approval.ApprovalsAdminEndpoints.java

@RequestMapping(value = "/approvals", method = RequestMethod.PUT)
@ResponseBody// w ww  .  j  av a2s  .  com
@Override
public List<Approval> updateApprovals(@RequestBody Approval[] approvals) {
    String currentUserId = getCurrentUserId();
    logger.debug("Updating approvals for user: " + currentUserId);
    approvalStore.revokeApprovals(String.format(USER_FILTER_TEMPLATE, currentUserId));
    for (Approval approval : approvals) {
        if (StringUtils.hasText(approval.getUserId()) && !isValidUser(approval.getUserId())) {
            logger.warn(String.format("Error[2] %s attempting to update approvals for %s", currentUserId,
                    approval.getUserId()));
            throw new UaaException("unauthorized_operation",
                    "Cannot update approvals for another user. Set user_id to null to update for existing user.",
                    HttpStatus.UNAUTHORIZED.value());
        } else {
            approval.setUserId(currentUserId);
        }
        approvalStore.addApproval(approval);
    }
    return approvalStore.getApprovals(String.format(USER_FILTER_TEMPLATE, currentUserId));
}

From source file:org.cloudfoundry.identity.uaa.approval.ApprovalsAdminEndpoints.java

@RequestMapping(value = "/approvals/{clientId}", method = RequestMethod.PUT)
@ResponseBody// w  ww  . j  av  a2s.  c  o m
@Override
public List<Approval> updateClientApprovals(@PathVariable String clientId, @RequestBody Approval[] approvals) {
    String currentUserId = getCurrentUserId();
    logger.debug("Updating approvals for user: " + currentUserId);
    approvalStore.revokeApprovals(String.format(USER_AND_CLIENT_FILTER_TEMPLATE, currentUserId, clientId));
    for (Approval approval : approvals) {
        if (StringUtils.hasText(approval.getUserId()) && !isValidUser(approval.getUserId())) {
            logger.warn(String.format("Error[1] %s attemting to update approvals for %s.", currentUserId,
                    approval.getUserId()));
            throw new UaaException("unauthorized_operation",
                    "Cannot update approvals for another user. Set user_id to null to update for existing user.",
                    HttpStatus.UNAUTHORIZED.value());
        } else {
            approval.setUserId(currentUserId);
        }
        approvalStore.addApproval(approval);
    }
    return approvalStore.getApprovals(String.format(USER_AND_CLIENT_FILTER_TEMPLATE, currentUserId, clientId));
}

From source file:org.cloudfoundry.identity.uaa.authentication.login.RemoteAuthenticationEndpoint.java

@RequestMapping(value = { "/authenticate" }, method = RequestMethod.POST)
@ResponseBody//from  w  w w  .j a  va2 s. c  o  m
public HttpEntity<Map<String, String>> authenticate(HttpServletRequest request,
        @RequestParam(value = "username", required = true) String username,
        @RequestParam(value = "password", required = true) String password) {
    Map<String, String> responseBody = new HashMap<>();

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    token.setDetails(new UaaAuthenticationDetails(request));

    HttpStatus status = HttpStatus.UNAUTHORIZED;
    try {
        Authentication a = authenticationManager.authenticate(token);
        responseBody.put("username", a.getName());
        if (a.getPrincipal() != null && a.getPrincipal() instanceof UaaPrincipal) {
            responseBody.put("email", ((UaaPrincipal) a.getPrincipal()).getEmail());
        }
        processAdditionalInformation(responseBody, a);
        status = HttpStatus.OK;
    } catch (AccountNotVerifiedException e) {
        responseBody.put("error", "account not verified");
        status = HttpStatus.FORBIDDEN;
    } catch (AuthenticationException e) {
        responseBody.put("error", "authentication failed");
    } catch (Exception e) {
        logger.debug("Failed to authenticate user ", e);
        responseBody.put("error", "error");
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return new ResponseEntity<>(responseBody, status);
}

From source file:org.cloudfoundry.identity.uaa.authentication.login.RemoteAuthenticationEndpoint.java

@RequestMapping(value = { "/authenticate" }, method = RequestMethod.POST, params = { "source", "origin",
        UaaAuthenticationDetails.ADD_NEW })
@ResponseBody/*w ww. j  a v  a2s  .  co  m*/
public HttpEntity<Map<String, String>> authenticate(HttpServletRequest request,
        @RequestParam(value = "username", required = true) String username,
        @RequestParam(value = Origin.ORIGIN, required = true) String origin,
        @RequestParam(value = "email", required = false) String email) {
    Map<String, String> responseBody = new HashMap<>();
    HttpStatus status = HttpStatus.UNAUTHORIZED;

    if (!hasClientOauth2Authentication()) {
        responseBody.put("error", "authentication failed");
        return new ResponseEntity<>(responseBody, status);
    }

    Map<String, String> userInfo = new HashMap<>();
    userInfo.put("username", username);
    userInfo.put(Origin.ORIGIN, origin);
    if (StringUtils.hasText(email)) {
        userInfo.put("email", email);
    }

    AuthzAuthenticationRequest token = new AuthzAuthenticationRequest(userInfo,
            new UaaAuthenticationDetails(request));
    try {
        Authentication a = loginAuthenticationManager.authenticate(token);
        responseBody.put("username", a.getName());
        processAdditionalInformation(responseBody, a);
        status = HttpStatus.OK;
    } catch (AuthenticationException e) {
        responseBody.put("error", "authentication failed");
    } catch (Exception e) {
        logger.debug("Failed to authenticate user ", e);
        responseBody.put("error", "error");
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return new ResponseEntity<>(responseBody, status);
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.RestAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    HttpHeaders headers = getHeaders();/*  w  ww  .ja  va 2s  .  c  om*/

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = restTemplate.exchange(remoteUrl, HttpMethod.POST,
            new HttpEntity<Object>(getParameters(username, password), headers), Map.class);

    if (response.getStatusCode() == HttpStatus.OK || response.getStatusCode() == HttpStatus.CREATED) {
        if (evaluateResponse(authentication, response)) {
            logger.info("Successful authentication request for " + authentication.getName());
            //TODO - we can return a UAA principal containing the correct origin here.
            return new UsernamePasswordAuthenticationToken(username, nullPassword ? null : "",
                    UaaAuthority.USER_AUTHORITIES);
        }
    } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        logger.info("Failed authentication request");
        throw new BadCredentialsException("Authentication failed");
    } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
        logger.info("Internal error from UAA. Please Check the UAA logs.");
    } else {
        logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA."
                + " Is a compatible version running?");
    }
    throw new RuntimeException("Could not authenticate with remote server");
}

From source file:org.cloudfoundry.identity.uaa.authentication.RemoteAuthenticationEndpoint.java

@RequestMapping(value = { "/authenticate" }, method = RequestMethod.POST)
@ResponseBody//from   w w w  .ja  v  a  2s  . c  o  m
public HttpEntity<AuthenticationResponse> authenticate(HttpServletRequest request,
        @RequestParam(value = "username", required = true) String username,
        @RequestParam(value = "password", required = true) String password) {
    AuthenticationResponse response = new AuthenticationResponse();

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    token.setDetails(new UaaAuthenticationDetails(request));

    HttpStatus status = HttpStatus.UNAUTHORIZED;
    try {
        Authentication a = authenticationManager.authenticate(token);
        response.setUsername(a.getName());
        if (a.getPrincipal() != null && a.getPrincipal() instanceof UaaPrincipal) {
            response.setEmail(((UaaPrincipal) a.getPrincipal()).getEmail());
        }
        processAdditionalInformation(response, a);
        status = HttpStatus.OK;
    } catch (AccountNotVerifiedException e) {
        response.setError("account not verified");
        status = HttpStatus.FORBIDDEN;
    } catch (AuthenticationException e) {
        response.setError("authentication failed");
    } catch (Exception e) {
        logger.debug("Failed to authenticate user ", e);
        response.setError("error");
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return new ResponseEntity<>(response, status);
}