/** tests that an error occurs if you attempt to use bad client credentials. */
  @Test
  @Ignore
  // Need a custom auth entry point to get the correct JSON response here.
  public void testInvalidClient() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set(
        "Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    List<String> newCookies = response.getHeaders().get("Set-Cookie");
    if (newCookies != null && !newCookies.isEmpty()) {
      fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
    }
    assertEquals(
        "no-cache, no-store, max-age=0, must-revalidate",
        response.getHeaders().getFirst("Cache-Control"));

    assertEquals(401, response.getStatusCode().value());

    @SuppressWarnings("unchecked")
    OAuth2Exception error = OAuth2Exception.valueOf(response.getBody());
    assertEquals("Bad credentials", error.getMessage());
    assertEquals("invalid_request", error.getOAuth2ErrorCode());
  }
  public View getUnsuccessfulView(
      AuthorizationRequest authorizationRequest, OAuth2Exception failure) {

    if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) {
      // we have no redirect for the user. very sad.
      throw new UnapprovedClientAuthenticationException(
          "Authorization failure, and no redirect URI.", failure);
    }

    Map<String, String> query = new LinkedHashMap<String, String>();

    query.put("error", failure.getOAuth2ErrorCode());
    query.put("error_description", failure.getMessage());

    if (authorizationRequest.getState() != null) {
      query.put("state", authorizationRequest.getState());
    }

    if (failure.getAdditionalInformation() != null) {
      for (Map.Entry<String, String> additionalInfo :
          failure.getAdditionalInformation().entrySet()) {
        query.put(additionalInfo.getKey(), additionalInfo.getValue());
      }
    }

    String url =
        append(
            authorizationRequest.getRedirectUri(), query, appendToFragment(authorizationRequest));
    return new RedirectView(url, false, true, false);
  }
  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 {

      Authentication authentication = tokenExtractor.extract(request);

      if (authentication == null) {
        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));
        }
        Authentication authResult = authenticationManager.authenticate(authentication);

        if (debug) {
          logger.debug("Authentication success: " + authResult);
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);
      }
    } catch (OAuth2Exception failed) {
      SecurityContextHolder.clearContext();

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

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

      return;
    }

    chain.doFilter(request, response);
  }
 private void maybeThrowExceptionFromHeader(String authenticateHeader, String headerType) {
   headerType = headerType.toLowerCase();
   if (authenticateHeader.toLowerCase().startsWith(headerType)) {
     Map<String, String> headerEntries =
         StringSplitUtils.splitEachArrayElementAndCreateMap(
             StringSplitUtils.splitIgnoringQuotes(
                 authenticateHeader.substring(headerType.length()), ','),
             "=",
             "\"");
     throw OAuth2Exception.valueOf(headerEntries);
   }
 }