@Test
  public void testGetCredentialsValid() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Cookie[] cookies =
        new Cookie[] {
          new Cookie("sdfsd", "fsdfs"),
          new Cookie("sdfsd1", "fsdfs"),
          null,
          new Cookie("sdfsd3", "fsdfs"),
          new Cookie("sdfsd4", "fsdfs"),
        };
    EasyMock.expect(request.getCookies()).andReturn(cookies);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    replay();
    trustedTokenService.activate(context);
    Cookie secureCookie = new Cookie("secure-cookie", trustedTokenService.encodeCookie("ieb"));
    cookies[2] = secureCookie;
    Credentials ieb = trustedTokenService.getCredentials(request, response);
    Assert.assertTrue(ieb instanceof SimpleCredentials);
    SimpleCredentials sc = (SimpleCredentials) ieb;
    TrustedUser tu = (TrustedUser) sc.getAttribute(TrustedTokenService.CA_AUTHENTICATION_USER);
    Assert.assertNotNull(tu);
    Assert.assertEquals("ieb", tu.getUser());
    verify();
  }
 @Override
 protected boolean isPreAuthenticated(final Credentials creds) {
   if (super.isPreAuthenticated(creds)) {
     SimpleCredentials simpleCreds = (SimpleCredentials) creds;
     String preAuth = (String) simpleCreds.getAttribute(getPreAuthAttributeName());
     boolean preAuthenticated = preAuthenticationTokens.contains(preAuth);
     if (preAuthenticated) {
       if (logger.isDebugEnabled()) {
         logger.debug(simpleCreds.getUserID() + " is pre-authenticated"); // $NON-NLS-1$
       }
     } else {
       if (logger.isDebugEnabled()) {
         logger.debug("pre-authentication token rejected"); // $NON-NLS-1$
       }
     }
     return preAuthenticated;
   }
   return false;
 }
  @Override
  protected String getUserID(Credentials credentials) {
    if (!(credentials instanceof SimpleCredentials)) {
      return super.getUserID(credentials);
    }

    SimpleCredentials cred = (SimpleCredentials) credentials;
    String id = cred.getUserID();
    if (id == null) {
      return super.getUserID(credentials);
    }

    String key = id + String.valueOf(cred.getPassword());
    String userId = ids.get(key);
    if (userId != null) {
      return userId;
    }

    boolean realId = false;
    Object realIdAttr = cred.getAttribute(JackrabbitConstants.REAL_USER_ID_USED);
    if (realIdAttr instanceof String) {
      realId = Boolean.valueOf((String) realIdAttr);
    }

    if (!realId) {
      try {
        LoginTable loginTable = LoginDBHandler.getUserLoginByUserName(id);
        userId = loginTable == null ? null : String.valueOf(loginTable.getUserId());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (userId == null) {
      userId = super.getUserID(credentials);
    }

    if (userId != null) {
      ids.put(key, userId);
    }

    return userId;
  }
  @Test
  public void testGetCredentialsValidSession() {
    ComponentContext context = configureForSession();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpSession session = createMock(HttpSession.class);
    EasyMock.expect(request.getSession(true)).andReturn(session);

    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn(null);
    EasyMock.expect(request.getRemoteUser()).andReturn("ieb");
    Capture<SimpleCredentials> attributeValue = new Capture<SimpleCredentials>();
    Capture<String> attributeName = new Capture<String>();
    session.setAttribute(EasyMock.capture(attributeName), EasyMock.capture(attributeValue));

    HttpServletResponse response = createMock(HttpServletResponse.class);

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response);
    Assert.assertTrue(attributeName.hasCaptured());
    Assert.assertTrue(attributeValue.hasCaptured());
    Credentials credentials = attributeValue.getValue();

    verify();
    reset();

    EasyMock.expect(request.getSession(false)).andReturn(session);
    EasyMock.expect(session.getAttribute(TrustedTokenService.SA_AUTHENTICATION_CREDENTIALS))
        .andReturn(credentials);

    replay();
    Credentials ieb = trustedTokenService.getCredentials(request, response);
    Assert.assertTrue(ieb instanceof SimpleCredentials);
    SimpleCredentials sc = (SimpleCredentials) ieb;
    TrustedUser tu = (TrustedUser) sc.getAttribute(TrustedTokenService.CA_AUTHENTICATION_USER);
    Assert.assertNotNull(tu);
    Assert.assertEquals("ieb", tu.getUser());
    verify();
  }
Esempio n. 5
0
 /**
  * Method tries to acquire an Impersonator in the following order:
  *
  * <ul>
  *   <li>Try to access it from the {@link Credentials} via {@link
  *       SimpleCredentials#getAttribute(String)}
  *   <li>Ask CallbackHandler for Impersonator with use of {@link ImpersonationCallback}.
  * </ul>
  *
  * @param credentials which, may contain an impersonation Subject
  * @return impersonation subject or null if non contained
  * @see #login()
  * @see #impersonate(java.security.Principal, javax.jcr.Credentials)
  */
 protected Subject getImpersonatorSubject(Credentials credentials) {
   Subject impersonator = null;
   if (credentials == null) {
     try {
       ImpersonationCallback impers = new ImpersonationCallback();
       callbackHandler.handle(new Callback[] {impers});
       impersonator = impers.getImpersonator();
     } catch (UnsupportedCallbackException e) {
       log.warn(
           e.getCallback().getClass().getName()
               + " not supported: Unable to perform Impersonation.");
     } catch (IOException e) {
       log.error(
           "Impersonation-Callback failed: "
               + e.getMessage()
               + ": Unable to perform Impersonation.");
     }
   } else if (credentials instanceof SimpleCredentials) {
     SimpleCredentials sc = (SimpleCredentials) credentials;
     impersonator = (Subject) sc.getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE);
   }
   return impersonator;
 }
  /**
   * 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;
  }