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:de.zib.gndms.dspace.service.SliceServiceImpl.java

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<Void> handleUnAuthorizedException(UnauthorizedException ex, HttpServletResponse response)
        throws IOException {
    logger.debug("handling exception for: " + ex.getMessage());
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    response.sendError(HttpStatus.UNAUTHORIZED.value());
    return new ResponseEntity<Void>(null, setHeaders(ex.getMessage(), null, null, null),
            HttpStatus.UNAUTHORIZED);/*  w w w. j ava2s.  c o  m*/
}

From source file:resources.RedSocialColaborativaRESTFUL.java

/**
 *
 * @return//w w  w . j  a  v a  2s  .  co m
 */
@RequestMapping(value = "/username", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody ResponseEntity<?> prueba2() {
    UsernameDTO aux = new UsernameDTO();
    String usernameConectado = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
        usernameConectado = ((UserDetails) principal).getUsername();
    }

    if (usernameConectado == null) {
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    }

    aux.setUsername(usernameConectado);

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

From source file:org.eclipse.cft.server.core.internal.client.CloudFoundryServerBehaviour.java

/**
 * Called by getClient(...) to prompt the user and reacquire token with
 * passcode, if an exception occurs while connecting with SSO
 *///  w ww.  ja  va2s  . c  o m
private void reestablishSsoSessionIfNeeded(CloudFoundryException e, CloudFoundryServer cloudServer)
        throws CoreException {
    // Status Code: 401 / Description = Invalid Auth Token, or;
    // Status Code: 403 / Description: Access token denied.
    if (cloudServer.isSso()
            && (e.getStatusCode() == HttpStatus.UNAUTHORIZED || e.getStatusCode() == HttpStatus.FORBIDDEN)) {
        boolean result = CloudFoundryPlugin.getCallback().ssoLoginUserPrompt(cloudServer);
        if (client != null) {
            // Success: another thread has established the client.
            return;
        }

        if (result) {
            // Client is null but the login did succeed, so recreate w/ new
            // token stored in server
            CloudCredentials credentials = CloudUtil.createSsoCredentials(cloudServer.getPasscode(),
                    cloudServer.getToken());
            client = createClientWithCredentials(cloudServer.getUrl(), credentials,
                    cloudServer.getCloudFoundrySpace(), cloudServer.isSelfSigned());
            return;
        }
    }

    // Otherwise, rethrow the exception
    throw e;

}

From source file:com.ksa.myanmarlottery.controller.FBResultController.java

@GetMapping(path = "/webhook")
public ResponseEntity<String> challenge(@RequestParam(name = "hub.verify_token") String verify_token,
        @RequestParam(name = "hub.challenge") String challenge) {
    log.info("challenge request " + verify_token);
    if (verify_token.equals(env.getProperty("facebook.hub.verify_token"))) {
        return new ResponseEntity<>(challenge, HttpStatus.OK);
    }//from ww  w.  j a  v a2  s. c  o  m
    return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@Override
public String approveClient(String approvalQuery, String cookie) {
    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; ");
    while (cookieTokenizer.hasMoreTokens()) {
        headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken());
    }/*from w w  w.ja va 2 s. c  o  m*/

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    for (final String pair : approvalQuery.split("&")) {
        final String[] nv = pair.split("=");
        formData.add(nv[0], nv[1]);
    }
    formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE)));

    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
            .build();

    final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData,
            headers, String.class);

    if (approvalQuery.contains("false")) {
        return null; // approval declined.
    }

    // accepted, but location contains error
    if (response.getHeaders().getLocation().getQuery().startsWith("error")) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
                response.getHeaders().getLocation().getQuery());
    }

    // accepted with related auth code
    return response.getHeaders().getLocation().getQuery().split("=")[1];
}

From source file:com.vmware.bdd.cli.rest.RestClient.java

/**
 * connect to a Serengeti server/*w w w . j ava2s  . c  o  m*/
 *
 * @param host
 *           host url with optional port
 * @param username
 *           serengeti login user name
 * @param password
 *           serengeti password
 */
public Connect.ConnectType connect(final String host, final String username, final String password) {
    String oldHostUri = hostUri;

    hostUri = Constants.HTTPS_CONNECTION_PREFIX + host + Constants.HTTPS_CONNECTION_LOGIN_SUFFIX;

    Connect.ConnectType connectType = null;
    try {
        LoginResponse response = loginClient.login(hostUri, username, password);
        //200
        if (response.getResponseCode() == HttpStatus.OK.value()) {
            if (CommonUtil.isBlank(response.getSessionId())) {
                if (isConnected()) {
                    System.out.println(Constants.CONNECTION_ALREADY_ESTABLISHED);
                    connectType = Connect.ConnectType.SUCCESS;
                } else {
                    System.out.println(Constants.CONNECT_FAILURE_NO_SESSION_ID);
                    connectType = Connect.ConnectType.ERROR;
                }
            } else {
                //normal response
                writeCookieInfo(response.getSessionId());
                System.out.println(Constants.CONNECT_SUCCESS);
                connectType = Connect.ConnectType.SUCCESS;
            }
        }
        //401
        else if (response.getResponseCode() == HttpStatus.UNAUTHORIZED.value()) {
            System.out.println(Constants.CONNECT_UNAUTHORIZATION_CONNECT);
            //recover old hostUri
            hostUri = oldHostUri;
            connectType = Connect.ConnectType.UNAUTHORIZATION;
        }
        //500
        else if (response.getResponseCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            System.out.println(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
            connectType = Connect.ConnectType.ERROR;
        } else {
            //error
            System.out.println(
                    String.format(Constants.UNSUPPORTED_HTTP_RESPONSE_CODE, response.getResponseCode()));
            //recover old hostUri
            hostUri = oldHostUri;
            connectType = Connect.ConnectType.ERROR;
        }
    } catch (Exception e) {
        System.out.println(Constants.CONNECT_FAILURE + ": " + (CommandsUtils.getExceptionMessage(e)));
        connectType = Connect.ConnectType.ERROR;
    }

    return connectType;
}

From source file:com.vmware.bdd.cli.rest.RestClient.java

/**
 * Disconnect the session/*w  w  w  .j  ava2 s. c  o  m*/
 */
public void disconnect() {
    try {
        checkConnection();

        getContentAsString(Constants.REST_PATH_LOGOUT);
    } catch (CliRestException cliRestException) {
        if (cliRestException.getStatus() == HttpStatus.UNAUTHORIZED) {
            writeCookieInfo("");
        }
    } catch (Exception e) {
        System.out.println(Constants.DISCONNECT_FAILURE + ": " + CommandsUtils.getExceptionMessage(e));
    }
}

From source file:com.vmware.bdd.cli.rest.RestClient.java

@SuppressWarnings("rawtypes")
private boolean validateAuthorization(ResponseEntity response) {
    if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        System.out.println(Constants.CONNECT_UNAUTHORIZATION_OPT);
        return false;
    }/*w ww .  j  a  va2s.c  o m*/
    return true;
}

From source file:com.yunmel.syncretic.core.BaseController.java

/**
 * ?//  www  . j  a v a2  s .  co  m
 * 
 * @param e
 * @return
 */
protected ResponseEntity<Result> unauthorized(Result result) {
    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
}

From source file:cu.uci.coj.restapi.controller.RestExtrasController.java

@ApiOperation(value = "Postear Entrada", notes = "Permite postear una entrada.", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "incorrect request"),
        @ApiResponse(code = 401, message = "username token mismatch<br> hash incorrect<br> token expirated<br> username apikey mismatch<br> apikey hash incorrect<br> apikey expirated<br> apikey secret incorrect<br> token or apikey incorrect"),
        @ApiResponse(code = 412, message = "text must not be empty<br> entry text too long") })
@RequestMapping(value = "/entry", method = RequestMethod.POST, headers = "Accept=application/json", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody/*from  ww w . j  a  va  2 s  .  c o  m*/
public ResponseEntity<?> addEntry(@ApiParam(value = "JSON para enviar") @RequestBody InputEntryRest bodyjson) {
    try {
        int error = ValidateApiAndToken(bodyjson.getApikey(), bodyjson.getToken());
        if (error > 0) {
            return new ResponseEntity<>(TokenUtils.ErrorMessage(error), HttpStatus.UNAUTHORIZED);
        }

        Entry entry = new Entry(bodyjson.getEntryText(), Calendar.getInstance().getTime());
        if (ValidateEntry(entry) != null)
            return new ResponseEntity<>("{\"error\":\"" + ValidateEntry(entry) + "\"}",
                    HttpStatus.PRECONDITION_FAILED);

        preProcessEntry(entry);
        String username = ExtractUser(bodyjson.getToken());
        entryDAO.addEntry(entry, isAdmin(username), username);

    } catch (Exception e) {
        return new ResponseEntity<>(TokenUtils.ErrorMessage(8), HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}