org.springframework.security.oauth2.common.exceptions.OAuth2Exception Java Examples

The following examples show how to use org.springframework.security.oauth2.common.exceptions.OAuth2Exception. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomAuthorizationServerConfigurer.java    From spring-microservice-exam with MIT License 7 votes vote down vote up
@Bean
@Lazy
public WebResponseExceptionTranslator<OAuth2Exception> webResponseExceptionTranslator() {
    return new DefaultWebResponseExceptionTranslator() {
        @Override
        public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
            if (e instanceof OAuth2Exception) {
                OAuth2Exception exception = (OAuth2Exception) e;
                // 转换返回结果
                return ResponseEntity.status(exception.getHttpErrorCode()).body(new CustomOauthException(e.getMessage()));
            } else {
                throw e;
            }
        }
    };
}
 
Example #2
Source File: OpenIdConnectFilter.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(
    HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {

    try {
        OAuth2AccessToken accessToken = restTemplate.getAccessToken();

        Claims claims = Claims.createFrom(jsonMapper, accessToken);
        GoogleUser googleUser = userIdentity.findOrCreateFrom(claims);
        repository.save(googleUser);

        Authentication authentication = new UsernamePasswordAuthenticationToken(
            googleUser, null, googleUser.getAuthorities());
        publish(new AuthenticationSuccessEvent(authentication));
        return authentication;
    } catch (OAuth2Exception e) {
        BadCredentialsException error = new BadCredentialsException(
                "Cannot retrieve the access token", e);
        publish(new OAuth2AuthenticationFailureEvent(error));
        throw error;
    }
}
 
Example #3
Source File: SecurityConfiguration.java    From nakadi with MIT License 6 votes vote down vote up
protected Object toJsonResponse(final Object object) throws UnknownStatusCodeException {
    if (object instanceof OAuth2Exception) {
        final OAuth2Exception oae = (OAuth2Exception) object;
        if (oae.getCause() != null) {
            if (oae.getCause() instanceof AuthenticationException) {
                return new ProblemResponse(UNAUTHORIZED, oae.getCause().getMessage());
            }
            return new ProblemResponse(INTERNAL_SERVER_ERROR, oae.getMessage());
        }

        return new ProblemResponse(fromStatusCode(oae.getHttpErrorCode()), oae.getMessage());
    }

    return new ProblemResponse(INTERNAL_SERVER_ERROR,
            "Unrecognized error happened in authentication path");
}
 
Example #4
Source File: OAuth2ExceptionDataResultJsonSerializer.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
		JsonProcessingException {
       jgen.writeStartObject();
	jgen.writeStringField("code", value.getOAuth2ErrorCode());
	jgen.writeStringField("message", value.getMessage());
	jgen.writeBooleanField("success", false);
	jgen.writeBooleanField("error", true);
	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();
}
 
Example #5
Source File: CloudResponseExceptionTranslator.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {

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

		// 客户端异常直接返回客户端,不然无法解析
		if (e instanceof ClientAuthenticationException) {
			return new ResponseEntity<>(e, headers,
				HttpStatus.valueOf(status));
		}
		return new ResponseEntity<>(new CloudAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers,
			HttpStatus.valueOf(status));

	}
 
Example #6
Source File: FacebookLoginFilter.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {

    try {
        OAuth2AccessToken accessToken = restTemplate.getAccessToken();
        FacebookUser facebookUser = userIdentity.findOrCreateFrom(accessToken);

        repository.save(facebookUser);

        Authentication authentication = new UsernamePasswordAuthenticationToken(
                facebookUser, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
        publish(new AuthenticationSuccessEvent(authentication));
        return authentication;
    } catch (OAuth2Exception e) {
        BadCredentialsException error = new BadCredentialsException(
                "Cannot retrieve the access token", e);
        publish(new OAuth2AuthenticationFailureEvent(error));
        throw error;
    }
}
 
Example #7
Source File: BootOAuth2WebResponseExceptionTranslator.java    From oauth-boot with MIT License 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {

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

        BootOAuth2Exception exception = new BootOAuth2Exception(e.getMessage(), e);

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

        return response;

    }
 
Example #8
Source File: CustomWebResponseExceptionTranslator.java    From Taroco with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {

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

        final CustomOauth2Exception exception = new CustomOauth2Exception(e.getMessage(), e);
        exception.setOauth2ErrorCode(e.getOAuth2ErrorCode());
        return new ResponseEntity<>(exception, headers,
                HttpStatus.valueOf(status));

    }
 
Example #9
Source File: ApiBootWebResponseExceptionTranslator.java    From api-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Handling Formatted OAuth2Exception Response
 *
 * @param e {@link OAuth2Exception}
 * @return {@link ResponseEntity}
 * @throws IOException
 */
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {
    int status = e.getHttpErrorCode();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    headers.set("Pragma", "no-cache");
    if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) {
        headers.set("WWW-Authenticate", String.format("%s %s", "Bearer", e.getSummary()));
    }

    // use ApiBootOAuth2Exception as the returned exception type
    ApiBootOAuth2Exception apiBootOAuth2Exception = new ApiBootOAuth2Exception(e.getMessage(), e, authorizationDeniedResponse);
    // get custom authorization definition response HttpStatus
    HttpStatus httpStatus = authorizationDeniedResponse.getHttpStatus();
    ResponseEntity<OAuth2Exception> response = new ResponseEntity(apiBootOAuth2Exception, headers, httpStatus);
    return response;
}
 
Example #10
Source File: SophiaWebResponseExceptionTranslator.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {

        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
        headers.set(HttpHeaders.PRAGMA, "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }

        // 客户端异常直接返回客户端,不然无法解析
        if (e instanceof ClientAuthenticationException) {
            return new ResponseEntity<>(e, headers,
                    HttpStatus.valueOf(status));
        }
        return new ResponseEntity<>(new SophiaAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers,
                HttpStatus.valueOf(status));

    }
 
Example #11
Source File: SophiaWebResponseExceptionTranslator.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {

        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
        headers.set(HttpHeaders.PRAGMA, "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }

        // 客户端异常直接返回客户端,不然无法解析
        if (e instanceof ClientAuthenticationException) {
            return new ResponseEntity<>(e, headers,
                    HttpStatus.valueOf(status));
        }
        return new ResponseEntity<>(new SophiaAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers,
                HttpStatus.valueOf(status));

    }
 
Example #12
Source File: SophiaWebResponseExceptionTranslator.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {

        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
        headers.set(HttpHeaders.PRAGMA, "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }

        // 客户端异常直接返回客户端,不然无法解析
        if (e instanceof ClientAuthenticationException) {
            return new ResponseEntity<>(e, headers,
                    HttpStatus.valueOf(status));
        }
        return new ResponseEntity<>(new SophiaAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers,
                HttpStatus.valueOf(status));

    }
 
Example #13
Source File: VerificationCodeIntegrationAuthenticator.java    From cola-cloud with MIT License 5 votes vote down vote up
@Override
public void prepare(IntegrationAuthentication integrationAuthentication) {
    String vcToken = integrationAuthentication.getAuthParameter("vc_token");
    String vcCode = integrationAuthentication.getAuthParameter("vc_code");
    //验证验证码
    Result<Boolean> result = verificationCodeClient.validate(vcToken, vcCode, null);
    if (!result.getData()) {
        throw new OAuth2Exception("验证码错误");
    }
}
 
Example #14
Source File: NakadiResourceServerTokenServicesTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenLocalBrokenRemote500Replaced() {
    when(featureToggleService.isFeatureEnabled(eq(Feature.REMOTE_TOKENINFO))).thenReturn(false);

    when(localService.loadAuthentication(any())).thenThrow(mock(RuntimeException.class));
    when(remoteService.loadAuthentication(any())).thenThrow(new RuntimeException("msg"));

    try{
        objectToTest.loadAuthentication("bbb");
        fail();
    } catch (OAuth2Exception ex) {
        assertEquals("msg", ex.getMessage());
        assertEquals(HttpStatus.SERVICE_UNAVAILABLE.value(), ex.getHttpErrorCode());
    }
}
 
Example #15
Source File: NakadiResourceServerTokenServicesTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenLocalBrokenRemoteBadUsed() {
    when(featureToggleService.isFeatureEnabled(eq(Feature.REMOTE_TOKENINFO))).thenReturn(false);

    when(localService.loadAuthentication(any())).thenThrow(mock(RuntimeException.class));
    final OAuth2Exception expectedException = mock(OAuth2Exception.class);
    when(remoteService.loadAuthentication(any())).thenThrow(expectedException);

    try{
        objectToTest.loadAuthentication("bbb");
        fail();
    } catch (OAuth2Exception ex) {
        assertSame(expectedException, ex);
    }
}
 
Example #16
Source File: NakadiResourceServerTokenServicesTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenLocalHasBadResponseRemoteIsNotCalled() {
    when(featureToggleService.isFeatureEnabled(eq(Feature.REMOTE_TOKENINFO))).thenReturn(false);

    final OAuth2Exception expectedException = mock(OAuth2Exception.class);
    when(localService.loadAuthentication(any())).thenThrow(expectedException);
    when(remoteService.loadAuthentication(any())).thenReturn(mock(OAuth2Authentication.class));

    try {
        objectToTest.loadAuthentication("bbb");
        fail();
    } catch (OAuth2Exception ex) {
        assertSame(expectedException, ex);
    }
}
 
Example #17
Source File: OAuth2CustomResultConfiguration.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if(xresponseViewManager!=null){
		xresponseViewManager.registerMatchPredicate(body->{
			if(OAuth2Exception.class.isInstance(body)){
				return false;
			}
			return RequestUtils.getCurrentServletPath().map(path->path.contains("/oauth/")).orElse(false);
		}, new OAuth2DataResultWrapper());
	}
}
 
Example #18
Source File: OAuth2CustomAuthenticationEntryPoint.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseEntity<OAuth2Exception> enhanceResponse(ResponseEntity<OAuth2Exception> response, Exception exception) {
	if(log.isErrorEnabled()){
		WebHolder.getRequest().ifPresent(request->{
			Authentication auth = tokenExtractor.extract(request);
			log.error("token:{}, auth: {}", auth==null?"null":auth.getPrincipal(), auth);
		});
		log.error("oauth2 error", exception);
	}
	return super.enhanceResponse(response, exception);
}
 
Example #19
Source File: DiscordTokenServices.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
        throws AuthenticationException, InvalidTokenException {
    try {
        return authorities.get(accessToken);
    } catch (ExecutionException | UncheckedExecutionException e) {
        if (e.getCause() instanceof OAuth2Exception) {
            throw (OAuth2Exception) e.getCause();
        }
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: OAuth2TokenRequestFilter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public OAuth2AccessToken load(TokenRequestDto requestDto) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    restTemplate.setAccessTokenProvider(tokenProvider);
    if (requestDto.getCode() != null) {
        AccessTokenRequest tokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest();
        tokenRequest.setCurrentUri(requestDto.getRedirectUri());
        tokenRequest.setAuthorizationCode(requestDto.getCode());
    }
    try {
        return restTemplate.getAccessToken();
    } catch (OAuth2Exception e) {
        throw new BadCredentialsException("Could not obtain access token", e);
    }
}
 
Example #21
Source File: CustomWebResponseExceptionTranslator.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) {

    OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
    return ResponseEntity.status(oAuth2Exception.getHttpErrorCode())
            .body(new CustomOauthException(oAuth2Exception));
}
 
Example #22
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({ OAuth2Exception.class })
public ResponseEntity<Object> handleOAuth2Exception(HttpClientErrorException ex, WebRequest request) {
    final String error = "Digits oauth authorization failed" ;
    final ApiError apiError = new ApiError(HttpStatus.FORBIDDEN, ex.getLocalizedMessage(), error);

    return new ResponseEntity<Object>(apiError, new HttpHeaders(), HttpStatus.FORBIDDEN);
}
 
Example #23
Source File: PageController.java    From docs-manage with MIT License 5 votes vote down vote up
@GetMapping("/oauth/error")
public String handleError(Map<String, Object> model, HttpServletRequest request) {
    Object error = request.getAttribute("error");
    String errorInfo;
    if (error instanceof OAuth2Exception) {
        OAuth2Exception oauthError = (OAuth2Exception) error;
        errorInfo = HtmlUtils.htmlEscape(oauthError.getSummary());
    } else {
        errorInfo = ((Exception) error).toString();
    }
    model.put("errorInfo", errorInfo);
    return "oauthError";
}
 
Example #24
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken retrieveToken(final AccessTokenRequest request,
                                          OAuth2ProtectedResourceDetails resource,
                                          MultiValueMap<String, String> form,
                                          HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        this.authenticationHandler.authenticateTokenRequest(resource, form, headers);
        this.tokenRequestEnhancer.enhance(request, resource, form, headers);
        final ResponseExtractor<OAuth2AccessToken> delegate = this.getResponseExtractor();

        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if(response.getHeaders().containsKey("Set-Cookie")) {
                    request.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }

                return (OAuth2AccessToken)delegate.extractData(response);
            }
        };
        System.out.println("URI == " + this.getAccessTokenUri(resource, form));
        return (OAuth2AccessToken)this.getRestTemplate().execute(this.getAccessTokenUri(resource, form),
                this.getHttpMethod(),
                this.getRequestCallback(resource, form, headers),
                extractor,
                form.toSingleValueMap());
    } catch (OAuth2Exception var8) {
        System.out.println(var8.toString());
        throw new OAuth2AccessDeniedException("Access token denied.", resource, var8);
    } catch (RestClientException var9) {
        System.out.println(var9.toString());
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, var9);
    }
}
 
Example #25
Source File: SmsIntegrationAuthenticator.java    From cola-cloud with MIT License 5 votes vote down vote up
@Override
public void prepare(IntegrationAuthentication integrationAuthentication) {
    String smsToken = integrationAuthentication.getAuthParameter("sms_token");
    String smsCode = integrationAuthentication.getAuthParameter("password");
    String username = integrationAuthentication.getAuthParameter("username");
    Result<Boolean> result = verificationCodeClient.validate(smsToken, smsCode, username);
    if (!result.getData()) {
        throw new OAuth2Exception("验证码错误或已过期");
    }
}
 
Example #26
Source File: ResourceServerConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<OAuth2Exception> translate(final Exception e) throws Exception {
    // Translate the exception with the default translator
    ResponseEntity<OAuth2Exception> defaultResponse = this.defaultTranslator.translate(e);
    // Build your own error object
    String errorCode = defaultResponse.getBody().getOAuth2ErrorCode();
    OAuth2Exception excBody = defaultResponse.getBody();
    log.info("Came here==>"+errorCode);
    if(errorCode.equals("unauthorized")) {
    	excBody.addAdditionalInformation("error_description", "Authentication required to access this resource");
    }
    return new ResponseEntity<OAuth2Exception>(excBody, defaultResponse.getStatusCode()) ;
}
 
Example #27
Source File: AuthorizationController.java    From Taroco with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义 确认/拒绝授权
 *
 * @param approvalParameters
 * @param model
 * @param sessionStatus
 * @param principal
 * @return
 */
@RequestMapping(value = "/oauth/custom_authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public ResponseEntity<Response> approveOrDeny(@RequestParam Map<String, String> approvalParameters,
                                              Map<String, ?> model, SessionStatus sessionStatus, Principal principal) {
    try{
        final RedirectView redirectView = (RedirectView) authorizationEndpoint.approveOrDeny(
                approvalParameters, model, sessionStatus, principal);
        return ResponseEntity.ok(Response.success(redirectView.getUrl()));
    } catch (OAuth2Exception e) {
        log.error("确认/拒绝授权失败", e);
        return ResponseEntity.status(e.getHttpErrorCode()).body(Response.failure(e.getOAuth2ErrorCode(), e.getMessage()));
    }
}
 
Example #28
Source File: AuthorizationController.java    From Taroco with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义错误处理 重写{@link WhitelabelErrorEndpoint}
 *
 * @param request
 * @return
 */
@RequestMapping("/oauth/error")
@ResponseBody
public ResponseEntity<Response> handleError(HttpServletRequest request) {
    Object error = request.getAttribute("error");
    String errorSummary;
    if (error instanceof OAuth2Exception) {
        OAuth2Exception oauthError = (OAuth2Exception) error;
        errorSummary = oauthError.getMessage();
    } else {
        errorSummary = "Unknown error";
    }
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Response.failure(errorSummary));
}
 
Example #29
Source File: CustomExceptionHandler.java    From syhthems-platform with MIT License 5 votes vote down vote up
/**
 * OAuth2Exception 异常处理,拦截器中的异常是由 {@link DefaultWebResponseExceptionTranslator} 处理
 * @param e OAuth2Exception
 * @return ResultVO
 */
@ExceptionHandler(OAuth2Exception.class)
public ResultVO oAuth2ExceptionHandler(OAuth2Exception e) {
    log.error("-----> OAuth2 认证异常:{}", e.getOAuth2ErrorCode());
    e.printStackTrace();
    return ResultUtils.error(ResultEnum.AUTHENCATION_ERROR.getKey(), e.getOAuth2ErrorCode());
}
 
Example #30
Source File: CustomWebResponseExceptionTranslator.java    From lion with Apache License 2.0 5 votes vote down vote up
private ResponseEntity<CustomOAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {
    int code = e.getHttpErrorCode();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    headers.set("Pragma", "no-cache");
    if (code == ResponseCode.UNAUTHORIZED || (e instanceof InsufficientScopeException)) {
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
    }
    ResponseEntity<CustomOAuth2Exception> response = new ResponseEntity(e, headers, HttpStatus.valueOf(code));
    return response;
}