Example usage for org.springframework.security.oauth2.common.exceptions OAuth2Exception getMessage

List of usage examples for org.springframework.security.oauth2.common.exceptions OAuth2Exception getMessage

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions OAuth2Exception getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.epam.reportportal.auth.OAuthErrorHandler.java

@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

    if (e instanceof OAuth2Exception) {
        ResponseEntity<OAuth2Exception> translate = super.translate(e);
        OAuth2Exception body = translate.getBody();
        body.addAdditionalInformation("message", body.getMessage());
        body.addAdditionalInformation("error_code", String.valueOf(ErrorType.ACCESS_DENIED.getCode()));
        return translate;
    } else {/*from  w  ww.j  av a  2 s . com*/
        RestError restError = errorResolver.resolveError(e);
        OAuth2Exception exception = OAuth2Exception.create(
                String.valueOf(restError.getErrorRS().getErrorType().getCode()),
                restError.getErrorRS().getMessage());
        exception.addAdditionalInformation("message", restError.getErrorRS().getMessage());
        return new ResponseEntity<>(exception, restError.getHttpStatus());
    }

}

From source file:org.springframework.security.oauth2.common.exception.OAuth2ExceptionJackson2DeserializerTests.java

@Test
public void readValueUndefinedException() throws Exception {
    String accessToken = createResponse("notdefinedcode");
    OAuth2Exception result = mapper.readValue(accessToken, OAuth2Exception.class);
    assertEquals(DETAILS, result.getMessage());
    assertEquals(null, result.getAdditionalInformation());
}

From source file:org.springframework.security.oauth2.common.exception.OAuth2ExceptionJackson2DeserializerTests.java

@Test
public void readValueWithObjects() throws Exception {
    String accessToken = "{\"error\": [\"invalid\",\"client\"], \"error_description\": {\"some\":\"detail\"}, \"foo\": [\"bar\"]}";
    OAuth2Exception result = mapper.readValue(accessToken, OAuth2Exception.class);
    assertEquals("{some=detail}", result.getMessage());
    assertEquals("{foo=[bar]}", result.getAdditionalInformation().toString());
}

From source file:com.hundsun.sso.controller.OAuthRestController.java

@ExceptionHandler(OAuth2Exception.class)
public ResponseEntity<OAuth2Exception> handleException(OAuth2Exception e) throws Exception {
    LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
    return getExceptionTranslator().translate(e);
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Serializer.java

@Override
public void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    jgen.writeStartObject();// ww  w  .jav a 2  s.c om
    jgen.writeStringField("error", value.getOAuth2ErrorCode());
    jgen.writeStringField("error_description", value.getMessage());
    if (value.getAdditionalInformation() != null) {
        for (Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
            String key = entry.getKey();
            String add = entry.getValue();
            jgen.writeStringField(key, add);
        }
    }
    jgen.writeEndObject();
}

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

void handleHttpStatusCodeException(HttpStatusCodeException e, RedirectAttributes attributes)
        throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info("authentication failed (message={},X-Track={})", e.getMessage(),
                e.getResponseHeaders().get("X-Track"));
    }/*from w ww  .  j av a2s .co  m*/
    try {
        OAuth2Exception oAuth2Exception = objectMapper.readValue(e.getResponseBodyAsByteArray(),
                OAuth2Exception.class);
        attributes.addAttribute("error", oAuth2Exception.getMessage());
    } catch (JsonMappingException | JsonParseException ex) {
        attributes.addAttribute("error", e.getMessage());
    }
}

From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {/*from   w w  w . j a v a  2  s . com*/

        String tokenValue = parseToken(request);
        if (HttpMethod.OPTIONS.equals(HttpMethod.valueOf(request.getMethod()))) {
            chain.doFilter(request, response);
            //            throw new OAuth2Exception("options");
        } else if (tokenValue == null) {
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
            throw new OAuth2Exception("empty token");
        } else {
            ResourceCallAuthenticationToken authentication = new ResourceCallAuthenticationToken(tokenValue,
                    "");
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, tokenValue);
            authentication.setDetails(authenticationDetailsSource.buildDetails(request));
            authentication.setRequestPath(getFullURL(request));
            authentication.setHttpMethod(HttpMethod.valueOf(request.getMethod()));
            Authentication authResult = authenticationManager.authenticate(authentication);

            SecurityContextHolder.getContext().setAuthentication(authResult);

            chain.doFilter(request, response);

        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

}

From source file:org.openmhealth.shim.OAuth2ShimBase.java

@Override
public AuthorizationResponse handleAuthorizationResponse(HttpServletRequest servletRequest)
        throws ShimException {

    String state = servletRequest.getParameter("state");
    String code = servletRequest.getParameter("code");

    AuthorizationRequestParameters authorizationRequestParameters = authorizationRequestParametersRepo
            .findByStateKey(state);/*from  www  .j a v  a2s .c  o  m*/

    if (authorizationRequestParameters == null) {
        throw new IllegalStateException(
                "Could not find corresponding authorization " + "request parameters, cannot continue.");
    }

    OAuth2RestOperations restTemplate = restTemplate(state, code);
    try {
        /**
         * Create a persistable access parameters entity so that
         * spring oauth2's client token services can relate
         * the serialized OAuth2AccessToken to it.
         */
        AccessParameters accessParameters = new AccessParameters();
        accessParameters.setUsername(authorizationRequestParameters.getUsername());
        accessParameters.setShimKey(getShimKey());
        accessParameters.setStateKey(state);
        accessParametersRepo.save(accessParameters);

        trigger(restTemplate, getTriggerDataRequest());

        /**
         * By this line we will have an approved access token or
         * not, if we do not then we delete the access parameters entity.
         */
        if (restTemplate.getAccessToken() == null) {
            accessParametersRepo.delete(accessParameters);
            return AuthorizationResponse.error("Did not receive approval");
        } else {
            accessParameters = accessParametersRepo.findByUsernameAndShimKey(
                    authorizationRequestParameters.getUsername(), getShimKey(),
                    new Sort(Sort.Direction.DESC, "dateCreated"));
        }
        return AuthorizationResponse.authorized(accessParameters);
    } catch (OAuth2Exception e) {
        //TODO: OAuth2Exception may include other stuff
        System.out.println("Problem trying out the token!");
        e.printStackTrace();
        return AuthorizationResponse.error(e.getMessage());
    }
}

From source file:com.skywell.social.custom.OAuth2AuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {//from   w  w w  . j a v a2  s.  c om

        Authentication authentication = tokenExtractor.extract(request);

        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            User user = userRepository.findByAccessToken(authentication.getName());
            UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
                    user.getProviderUserId(), user.getAccessToken(), user.getAuthorities());
            authenticate.setDetails(authentication.getDetails());

            SecurityContextHolder.getContext().setAuthentication(authenticate);

        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
                new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

    chain.doFilter(request, response);
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

@ExceptionHandler(OAuth2Exception.class)
public ModelAndView handleOAuth2Exception(OAuth2Exception e, ServletWebRequest webRequest) throws Exception {
    logger.info(e.getSummary());/*from w  w  w. ja  v a  2  s . c om*/
    int errorCode = e.getHttpErrorCode();
    if (errorCode != 401 && "Bad credentials".equals(e.getMessage())) {
        //https://github.com/spring-projects/spring-security-oauth/issues/191
        errorCode = 401;
    }
    webRequest.getResponse().setStatus(errorCode);
    return new ModelAndView("forward:/home", Collections.singletonMap("error", e.getSummary()));
}