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.cloudfoundry.identity.uaa.oauth.approval.ApprovalsAdminEndpoints.java

@RequestMapping(value = "/approvals", method = RequestMethod.PUT)
@ResponseBody//from   w w w .jav  a2 s  .  co  m
@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 (approval.getUserId() != null && !isValidUser(approval.getUserId())) {
            logger.warn(String.format("Error[2] %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);
        }
        approval.setLastUpdatedAt(new Date());
        approvalStore.addApproval(approval);
    }
    return approvalStore.getApprovals(String.format(USER_FILTER_TEMPLATE, currentUserId));
}

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

@RequestMapping(value = "/approvals/{clientId}", method = RequestMethod.PUT)
@ResponseBody//from   ww w  .j  a  v a 2s . co  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 (approval.getUserId() != null && !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);
        }
        approval.setLastUpdatedAt(new Date());
        approvalStore.addApproval(approval);
    }
    return approvalStore.getApprovals(String.format(USER_AND_CLIENT_FILTER_TEMPLATE, currentUserId, clientId));
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private ModelAndView switchIdp(Map<String, Object> model, ClientDetails client, String clientId,
        HttpServletRequest request) {//w ww. j  av  a2  s  .c  o m
    Map<String, Object> additionalInfo = client.getAdditionalInformation();
    String clientDisplayName = (String) additionalInfo.get(ClientConstants.CLIENT_NAME);
    model.put("client_display_name", (clientDisplayName != null) ? clientDisplayName : clientId);

    String queryString = UaaHttpRequestUtils.paramsToQueryString(request.getParameterMap());
    String redirectUri = request.getRequestURL() + "?" + queryString;
    model.put("redirect", redirectUri);

    model.put("error", "The application is not authorized for your account.");
    model.put("error_message_code", "login.invalid_idp");

    return new ModelAndView("switch_idp", model, HttpStatus.UNAUTHORIZED);
}

From source file:org.cloudfoundry.identity.uaa.password.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<ExceptionReport>(
            new ExceptionReport(new BadCredentialsException("Invalid password change request"), false),
            HttpStatus.UNAUTHORIZED), messageConverters);
}

From source file:org.craftercms.core.controller.rest.RestControllerBase.java

@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody/* w  w  w.  j  a  v a2 s  .  co m*/
public Map<String, Object> handleAuthenticationException(HttpServletRequest request,
        AuthenticationException e) {
    return handleException(request, e);
}

From source file:org.fao.geonet.api.GlobalExceptionController.java

@ResponseBody
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler({ ServiceNotAllowedEx.class })
public Object unauthorizedHandler(final Exception exception) {
    return new ApiError("unauthorized", exception.getClass().getSimpleName(), exception.getMessage());
}

From source file:org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPoint.java

protected void commenceUnauthorizedResponse(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    response.addHeader(HttpHeaders.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\"", realm));
    response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}

From source file:org.openlmis.web.controller.DeliveryZoneProgramScheduleController.java

@RequestMapping(value = "deliveryZones/{zoneId}/programs/{programId}/periods", method = GET, headers = ACCEPT_JSON)
public ResponseEntity<OpenLmisResponse> getPeriodsForProgramInDeliveryZone(HttpServletRequest request,
        @PathVariable long zoneId, @PathVariable final long programId) {
    if (permissionService.hasPermissionOnZone(loggedInUserId(request), zoneId)) {
        Date elevenDaysFromNow = LocalDate.now().plusDays(11).toDate();
        List<ProcessingPeriod> periodsForDeliveryZoneAndProgram = scheduleService
                .getPeriodsForDeliveryZoneAndProgram(zoneId, programId, elevenDaysFromNow);
        final List<Long> syncedPeriods = distributionService.getSyncedPeriodsForDeliveryZoneAndProgram(zoneId,
                programId);/*from ww w. jav a  2 s .c o  m*/
        Collection unsyncedPeriodsForZoneAndProgram = CollectionUtils.select(periodsForDeliveryZoneAndProgram,
                new Predicate() {
                    @Override
                    public boolean evaluate(Object o) {
                        ProcessingPeriod period = (ProcessingPeriod) o;
                        return !syncedPeriods.contains(period.getId());
                    }
                });
        return OpenLmisResponse.response(PERIODS, unsyncedPeriodsForZoneAndProgram);
    } else {
        return OpenLmisResponse.error(FORBIDDEN_EXCEPTION, HttpStatus.UNAUTHORIZED);
    }
}

From source file:org.opentestsystem.shared.web.AbstractRestController.java

/**
 * Catch validation exception and return customized error message
 *///from   w  ww . j  a va  2s. c  o  m
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ResponseBody
public ResponseError handleAccessDeniedException(final AccessDeniedException except) {
    LOGGER.error("Permissions Issue", except);
    final ResponseError err = new ResponseError(
            "You are not authorized to access this portion of the application, please verify your roles with your Administrator");
    return err;
}

From source file:org.project.openbaton.nubomedia.paas.core.openshift.AuthenticationManager.java

public String authenticate(String baseURL, String username, String password) throws UnauthorizedException {

    String res = "";

    String authBase = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBase64String(authBase.getBytes());
    logger.debug("Auth header " + authHeader);

    String url = baseURL + suffix;

    HttpHeaders authHeaders = new HttpHeaders();
    authHeaders.add("Authorization", authHeader);
    authHeaders.add("X-CSRF-Token", "1");

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("client_id", "openshift-challenging-client").queryParam("response_type", "token");

    HttpEntity<String> authEntity = new HttpEntity<>(authHeaders);
    ResponseEntity<String> response = null;
    try {/*from  w  w  w  .j  a va2s  .  com*/
        response = template.exchange(builder.build().encode().toUriString(), HttpMethod.GET, authEntity,
                String.class);
    } catch (ResourceAccessException e) {
        return "PaaS Missing";
    } catch (HttpClientErrorException e) {
        throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid");
    }

    logger.debug("Response " + response.toString());

    if (response.getStatusCode().equals(HttpStatus.FOUND)) {

        URI location = response.getHeaders().getLocation();
        logger.debug("Location " + location);
        res = this.getToken(location.toString());

    } else if (response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {

        throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid");
    }

    return res;
}