/**
  * Remove credentials so that subsequent request don't contain credentials.
  *
  * @param request
  * @param response
  */
 public void dropCredentials(HttpServletRequest request, HttpServletResponse response) {
   if (testing) {
     calls.add(new Object[] {"dropCredentials", request, response});
     return;
   }
   if (usingSession) {
     HttpSession session = request.getSession(false);
     if (session != null) {
       session.setAttribute(SA_AUTHENTICATION_CREDENTIALS, null);
     }
   } else {
     clearCookie(response);
   }
 }
  /**
   * Extract credentials from the request.
   *
   * @param req
   * @return credentials associated with the request.
   */
  public Credentials getCredentials(HttpServletRequest req, HttpServletResponse response) {
    if (testing) {
      calls.add(new Object[] {"getCredentials", req, response});
      return new SimpleCredentials("testing", "testing".toCharArray());
    }
    Credentials cred = null;
    String userId = null;
    String sakaiTrustedHeader = req.getHeader("x-sakai-token");
    if (trustedTokenEnabled
        && sakaiTrustedHeader != null
        && sakaiTrustedHeader.trim().length() > 0) {
      String host = req.getRemoteAddr();
      if (!safeHostAddrSet.contains(host)) {
        LOG.warn("Ignoring Trusted Token request from {} ", host);
      } else {
        // we have a HMAC based token, we should see if it is valid against the key we
        // have
        // and if so create some credentials.
        String[] parts = sakaiTrustedHeader.split(";");
        if (parts.length == 3) {
          try {
            String hash = parts[0];
            String user = parts[1];
            String timestamp = parts[2];
            String hmac = Signature.calculateRFC2104HMAC(user + ";" + timestamp, sharedSecret);
            if (hmac.equals(hash)) {
              // the user is Ok, we will trust it.
              userId = user;
              cred = createCredentials(userId, TrustedTokenTypes.TRUSTED_TOKEN);
            } else {
              LOG.debug("HMAC Match Failed {} != {} ", hmac, hash);
            }
          } catch (SignatureException e) {
            LOG.warn(
                "Failed to validate server token : {} {} ", sakaiTrustedHeader, e.getMessage());
          }
        } else {
          LOG.warn(
              "Illegal number of elements in trusted server token:{} {}  ",
              sakaiTrustedHeader,
              parts.length);
        }
      }
    }
    if (userId == null) {
      if (usingSession) {
        HttpSession session = req.getSession(false);
        if (session != null) {
          Credentials testCredentials =
              (Credentials) session.getAttribute(SA_AUTHENTICATION_CREDENTIALS);
          if (testCredentials instanceof SimpleCredentials) {
            SimpleCredentials sc = (SimpleCredentials) testCredentials;
            Object o = sc.getAttribute(CA_AUTHENTICATION_USER);
            if (o instanceof TrustedUser) {
              TrustedUser tu = (TrustedUser) o;
              if (tu.getUser() != null) {
                userId = tu.getUser();
                cred = testCredentials;
              }
            }
          }
        } else {
          cred = null;
        }
      } else {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
          for (Cookie c : cookies) {
            if (trustedAuthCookieName.equals(c.getName())) {
              if (secureCookie && !c.getSecure()) {
                continue;
              }
              String cookieValue = c.getValue();
              String[] decodedToken = decodeCookie(c.getValue());
              if (decodedToken != null) {
                userId = decodedToken[0];
                String tokenType = decodedToken[1];
                TokenTrustValidator ttv = registeredTypes.get(tokenType);
                if (ttv == null || ttv.isTrusted(req)) {
                  LOG.debug("Token is valid and decoded to {} ", userId);
                  cred = createCredentials(userId, tokenType);
                  refreshToken(response, c.getValue(), userId, tokenType);
                  break;
                } else {
                  LOG.debug("Cookie cant be trusted for this request {} ", cookieValue);
                }
              } else {
                LOG.debug("Invalid Cookie {} ", cookieValue);
                clearCookie(response);
              }
            }
          }
        }
      }
    }
    if (userId != null) {
      LOG.debug("Trusted Authentication for {} with credentials {}  ", userId, cred);
    }

    return cred;
  }