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.springframework.boot.actuate.endpoint.mvc.MvcEndpointSecurityInterceptor.java

private void sendFailureResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (request.getUserPrincipal() != null) {
        String roles = StringUtils.collectionToDelimitedString(this.roles, " ");
        response.sendError(HttpStatus.FORBIDDEN.value(),
                "Access is denied. User must have one of the these roles: " + roles);
    } else {// w ww . j  a v a2 s .c  o m
        logUnauthorizedAttempt();
        response.sendError(HttpStatus.UNAUTHORIZED.value(),
                "Full authentication is required to access this resource.");
    }
}

From source file:org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator.java

private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("OAuth error.", e);
    }// w w  w .  ja  v a2  s  .  co m

    int status = e.getHttpErrorCode();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    if (status == HttpStatus.UNAUTHORIZED.value()) {
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
    }

    ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(e, headers,
            HttpStatus.valueOf(status));

    return response;

}

From source file:org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.java

/**
 * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise
 * returns a 401 error code.//from ww  w .  j a va  2s.c om
 * <p>
 * If redirecting or forwarding, {@code saveException} will be called to cache the
 * exception for use in the target view.
 */
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {

    if (defaultFailureUrl == null) {
        logger.debug("No failure URL set, sending 401 Unauthorized error");

        response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
    } else {
        saveException(request, exception);

        if (forwardToDestination) {
            logger.debug("Forwarding to " + defaultFailureUrl);

            request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
        } else {
            logger.debug("Redirecting to " + defaultFailureUrl);
            redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
        }
    }
}

From source file:org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    // compute a nonce (do not use remote IP address due to proxy farms)
    // format of nonce is:
    // base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
    long expiryTime = System.currentTimeMillis() + (nonceValiditySeconds * 1000);
    String signatureValue = DigestAuthUtils.md5Hex(expiryTime + ":" + key);
    String nonceValue = expiryTime + ":" + signatureValue;
    String nonceValueBase64 = new String(Base64.getEncoder().encode(nonceValue.getBytes()));

    // qop is quality of protection, as defined by RFC 2617.
    // we do not use opaque due to IE violation of RFC 2617 in not
    // representing opaque on subsequent requests in same session.
    String authenticateHeader = "Digest realm=\"" + realmName + "\", " + "qop=\"auth\", nonce=\""
            + nonceValueBase64 + "\"";

    if (authException instanceof NonceExpiredException) {
        authenticateHeader = authenticateHeader + ", stale=\"true\"";
    }/*w w  w.  j  a  v  a2s  .  co m*/

    if (logger.isDebugEnabled()) {
        logger.debug("WWW-Authenticate header sent to user agent: " + authenticateHeader);
    }

    httpResponse.addHeader("WWW-Authenticate", authenticateHeader);
    httpResponse.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}

From source file:org.springframework.social.cloudplaylists.api.impl.CloudPlaylistsErrorHandler.java

void handleCloudPlaylistsError(HttpStatus statusCode, Map errorDetails) {

    String message = (String) errorDetails.get("error_description");
    HttpStatus httpStatus = statusCode;/*from w  w w .  ja v a2  s  .c om*/

    if (httpStatus == HttpStatus.OK) {
        // Should never happen
    } else if (httpStatus == HttpStatus.BAD_REQUEST) {

        String error = (String) errorDetails.get("error");
        String error_description = (String) errorDetails.get("error_description");

        if (error != null && PlaylistUpdateException.class.getName().equals(error)) {
            throw new PlaylistUpdateException(error_description);
        }
        if (error != null && PlaylistCreationException.class.getName().equals(error)) {
            throw new PlaylistCreationException(error_description);
        }

        throw new ResourceNotFoundException("cloudplaylists", message);

    } else if (httpStatus == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("cloudplaylists", message);

    } else if (httpStatus == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("cloudplaylists", message);
    } else if (httpStatus == HttpStatus.FORBIDDEN) {
        String provider = (String) errorDetails.get("provider");
        String error = (String) errorDetails.get("error");
        if (error != null && provider != null && NotConnectedException.class.getName().equals(error)) {
            throw new NotConnectedException(provider);
        }
        if (error != null && provider != null && ExpiredAuthorizationException.class.getName().equals(error)) {
            throw new ExpiredAuthorizationException(provider);
        }
        throw new OperationNotPermittedException("cloudplaylists", message);
    } else if (httpStatus == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("cloudplaylists", message);
    } else if (httpStatus == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("cloudplaylists", message);
    }
}

From source file:org.springframework.social.exfm.api.impl.ExFmErrorHandler.java

void handleExFmError(HttpStatus statusCode, Status status) {

    String message = status.getStatus_text();

    HttpStatus httpStatus = statusCode != HttpStatus.OK ? statusCode
            : HttpStatus.valueOf(Integer.parseInt(status.getStatus_code()));

    if (httpStatus == HttpStatus.OK) {
        // Should never happen
    } else if (httpStatus == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("exfm", message);

    } else if (httpStatus == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("exfm", message);

    } else if (httpStatus == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("exfm", message);
    } else if (httpStatus == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("exfm", message);
    } else if (httpStatus == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("exfm", message);
    } else if (httpStatus == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("exfm", message);
    }/*from   w w w .  j  a  va2  s  .co  m*/
}

From source file:org.springframework.social.lastfm.api.impl.LastFmErrorHandler.java

void handleLastFmError(HttpStatus statusCode, Map<Integer, String> errorDetails) {

    String message = errorDetails.values().iterator().next();
    if (statusCode == HttpStatus.OK) {
        // TODO I've just put a single error code in here for now - need to
        // complete with other error codes
        if (errorDetails.containsKey(3)) {
            throw new ResourceNotFoundException("lastfm", message);
        }/*from  w  ww .j  av  a2s. c om*/
        if (errorDetails.containsKey(6)) {
            throw new ResourceNotFoundException("lastfm", message);
        }
        if (errorDetails.containsKey(10)) {
            throw new NotAuthorizedException("lastfm", message);
        }
        if (errorDetails.containsKey(8)) {
            throw new ResourceNotFoundException("lastfm", message);
        }
        if (errorDetails.containsKey(13)) {
            throw new NotAuthorizedException("lastfm", message);
        }

    } else if (statusCode == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("lastfm", message);

    } else if (statusCode == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("lastfm", message);
    } else if (statusCode == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("lastfm", message);
    } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("lastfm", message);
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("lastfm", message);
    }
}

From source file:org.springframework.social.linkedin.api.impl.LinkedInErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    Map<String, Object> errorDetails = extractErrorDetailsFromResponse(response);
    String message = (String) errorDetails.get("message");
    HttpStatus statusCode = response.getStatusCode();
    if (statusCode.equals(HttpStatus.UNAUTHORIZED)) {
        throw new NotAuthorizedException("linkedIn", message);
    } else if (statusCode.equals(HttpStatus.FORBIDDEN)) {
        if (message.contains("Throttle")) {
            throw new RateLimitExceededException("linkedin");
        } else {//from   w  w  w  .  ja  va2s  . com
            throw new InsufficientPermissionException("linkedin");
        }
    } else if (statusCode.equals(HttpStatus.NOT_FOUND)) {
        throw new ResourceNotFoundException("linkedin", message);
    }

    handleUncategorizedError(response);
}

From source file:org.springframework.social.mixcloud.api.impl.MixcloudErrorHandler.java

/**
 * Examines the error data returned from Mixcloud and throws the most
 * applicable exception./*ww  w  .j av a  2 s .  com*/
 * 
 * @param errorDetails
 *            a Map containing an "error"
 */
void handleMixcloudError(HttpStatus statusCode, SocialException errorDetails) {
    if (statusCode == HttpStatus.OK) {

    } else if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorDetails instanceof UncategorizedApiException) {
            String message = errorDetails.getMessage();
            if (AUTHORIZATION_FAILURE_MESSAGES.contains(message)) {
                throw new NotAuthorizedException("mixcloud", message);
            } else {
                throw errorDetails;

            }
        } else {
            throw errorDetails;
        }

    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        throw new NotAuthorizedException("mixcloud", errorDetails.getMessage());
    } else if (statusCode == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("mixcloud", errorDetails.getMessage());
    } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("mixcloud", errorDetails.getMessage());
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("mixcloud", errorDetails.getMessage());
    }
}

From source file:org.springframework.social.soundcloud.api.impl.SoundCloudErrorHandler.java

/**
 * Examines the error data returned from SoundCloud and throws the most applicable exception.
 * @param errorDetails a Map containing an "error_message"
 *///from www  .  j av a 2s .  co m
void handleSoundCloudError(HttpStatus statusCode, List<Map<String, String>> errorDetailsList) {
    // Can't trust the type to be useful. It's often OAuthException, even for things not OAuth-related. 
    // Can rely only on the message (which itself isn't very consistent).
    List<String> messages = new ArrayList<String>();
    for (Map<String, String> errorDetails : errorDetailsList) {
        String message = errorDetails.get("error_message");
        messages.add(message);
    }
    String message = constructMessage(messages);

    if (statusCode == HttpStatus.OK) {

    } else if (statusCode == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("soundcloud", message);

    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("soundcloud", message);

    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (isMessageStartsWithText(messages, "invalid_token")) {
            handleInvalidAccessToken(message);
        }
        throw new NotAuthorizedException("soundcloud", message);
    } else if (statusCode == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("soundcloud", message);
    } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("soundcloud", message);
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("soundcloud", message);
    }
}