Search in sources :

Example 11 with InternalSession

use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.

the class OATH method process.

/**
     * Processes the OTP input by the user. Checks the OTP for validity, and
     * resynchronizes the server as needed.
     *
     * @param callbacks
     * @param state
     * @return -1 for success; 0 for failure
     * @throws AuthLoginException upon any errors
     */
@Override
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    try {
        //check for session and get username and UUID
        if (userName == null || userName.length() == 0) {
            // session upgrade case. Need to find the user ID from the old
            // session
            SSOTokenManager mgr = SSOTokenManager.getInstance();
            InternalSession isess = getLoginState("OATH").getOldSession();
            if (isess == null) {
                throw new AuthLoginException("amAuth", "noInternalSession", null);
            }
            SSOToken token = mgr.createSSOToken(isess.getID().toString());
            UUID = token.getPrincipal().getName();
            userName = token.getProperty("UserToken");
            if (debug.messageEnabled()) {
                debug.message("OATH.process(): Username from SSOToken : " + userName);
            }
            if (userName == null || userName.length() == 0) {
                throw new AuthLoginException("amAuth", "noUserName", null);
            }
        }
        switch(state) {
            case ISAuthConstants.LOGIN_START:
                // callback[1] = Confirmation CallBack (Submit OTP)
                if (callbacks == null || callbacks.length != 2) {
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                // check password length MUST be 6 or higher according to RFC
                if (passLen < MIN_PASSWORD_LENGTH) {
                    debug.error("OATH.process(): Password length is less than " + MIN_PASSWORD_LENGTH);
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                // get OTP
                String OTP = String.valueOf(((PasswordCallback) callbacks[0]).getPassword());
                if (StringUtils.isEmpty(OTP)) {
                    debug.error("OATH.process(): invalid OTP code");
                    setFailureID(userName);
                    throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
                }
                if (minSecretKeyLength <= 0) {
                    debug.error("OATH.process(): Min Secret Key Length is not a valid value");
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                if (StringUtils.isEmpty(secretKeyAttrName)) {
                    debug.error("OATH.process():  secret key attribute name is empty");
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                // get Arrival time of the OTP
                timeInSeconds = System.currentTimeMillis() / 1000L;
                if (checkOTP(OTP)) {
                    return ISAuthConstants.LOGIN_SUCCEED;
                } else {
                    // the OTP is out of the window or incorrect
                    setFailureID(userName);
                    throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
                }
        }
    } catch (SSOException e) {
        debug.error("OATH.process(): SSOException", e);
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    return ISAuthConstants.LOGIN_IGNORE;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) InternalSession(com.iplanet.dpro.session.service.InternalSession) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) SSOException(com.iplanet.sso.SSOException)

Example 12 with InternalSession

use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.

the class SessionAdapterTest method shouldSerialiseAndDeserialiseToken.

@Test
public void shouldSerialiseAndDeserialiseToken() {
    // Given
    // Sessions can only measure time to the closest second.
    Calendar now = Calendar.getInstance();
    now.set(Calendar.MILLISECOND, 0);
    long mockTimestamp = TimeUtils.toUnixTime(now);
    String userId = "ferret";
    String sessionId = "badger";
    String sessionHandle = SessionID.SHANDLE_SCHEME_PREFIX + "weasel";
    byte[] mockByteData = {};
    InternalSession session = mock(InternalSession.class);
    // Ensure Session ID is badger
    given(tokenIdFactory.toSessionTokenId(any(InternalSession.class))).willReturn(sessionId);
    // Ensure Session User is ferret
    given(coreTokenConfig.getUserId(any(InternalSession.class))).willReturn(userId);
    // Ensure the expiration time is set.
    given(session.getExpirationTime(TimeUnit.MILLISECONDS)).willReturn(TimeUnit.SECONDS.toMillis(mockTimestamp));
    SessionID mockSessionID = mock(SessionID.class);
    given(mockSessionID.toString()).willReturn(sessionId);
    given(session.getID()).willReturn(mockSessionID);
    given(session.getSessionHandle()).willReturn(sessionHandle);
    // Avoid serialisation when using mock InternalSessions
    given(jsonSerialisation.deserialise(anyString(), eq(InternalSession.class))).willReturn(session);
    given(jsonSerialisation.serialise(any())).willReturn(new String(mockByteData));
    adapter = new SessionAdapter(tokenIdFactory, coreTokenConfig, jsonSerialisation, blobUtils);
    Token token = new Token(sessionId, TokenType.SESSION);
    token.setUserId(userId);
    token.setExpiryTimestamp(now);
    token.setBlob(mockByteData);
    token.setAttribute(SessionTokenField.SESSION_ID.getField(), "badger");
    token.setAttribute(SessionTokenField.SESSION_HANDLE.getField(), sessionHandle);
    // When
    Token result = adapter.toToken(adapter.fromToken(token));
    // Then
    TokenTestUtils.assertTokenEquals(result, token);
}
Also used : InternalSession(com.iplanet.dpro.session.service.InternalSession) Calendar(java.util.Calendar) Token(org.forgerock.openam.cts.api.tokens.Token) SessionID(com.iplanet.dpro.session.SessionID) Test(org.testng.annotations.Test)

Example 13 with InternalSession

use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.

the class SessionAdapterTest method shouldRestoreLatestAccessTimeFromAttribute.

@Test
public void shouldRestoreLatestAccessTimeFromAttribute() {
    // Given
    String latestAccessTime = "12345";
    Token token = new Token("badger", TokenType.SESSION);
    token.setAttribute(SessionTokenField.LATEST_ACCESS_TIME.getField(), latestAccessTime);
    // blob contents are missing the latestAccessTime value
    token.setBlob("{\"clientDomain\":null,\"creationTime\":1376307674,\"isISStored\":true,\"maxCachingTime\":3}".getBytes());
    // need a real JSONSerialisation for this test
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE).withIsGetterVisibility(JsonAutoDetect.Visibility.NONE).withSetterVisibility(JsonAutoDetect.Visibility.NONE).withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    JSONSerialisation serialisation = new JSONSerialisation(mapper);
    adapter = new SessionAdapter(tokenIdFactory, coreTokenConfig, serialisation, blobUtils);
    // When
    InternalSession session = adapter.fromToken(token);
    // Then
    // if latestAccessTime was zero, this would fail
    long epochedSeconds = System.currentTimeMillis() / 1000;
    long idleTime = session.getIdleTime();
    assertTrue(idleTime < epochedSeconds);
}
Also used : JSONSerialisation(org.forgerock.openam.cts.utils.JSONSerialisation) InternalSession(com.iplanet.dpro.session.service.InternalSession) Token(org.forgerock.openam.cts.api.tokens.Token) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.testng.annotations.Test)

Example 14 with InternalSession

use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.

the class DestroyNextExpiringAction method action.

@Override
public boolean action(InternalSession is, Map<String, Long> sessions) {
    String nextExpiringSessionID = null;
    long smallestExpTime = Long.MAX_VALUE;
    for (Map.Entry<String, Long> entry : sessions.entrySet()) {
        String sid = entry.getKey();
        long expirationTime = entry.getValue();
        if (expirationTime < smallestExpTime) {
            smallestExpTime = expirationTime;
            nextExpiringSessionID = sid;
        }
    }
    if (nextExpiringSessionID != null) {
        SessionID sessID = new SessionID(nextExpiringSessionID);
        try {
            Session s = sessionCache.getSession(sessID);
            s.destroySession(s);
        } catch (SessionException e) {
            if (debug.messageEnabled()) {
                debug.message("Failed to destroy the next " + "expiring session.", e);
            }
            // in this case
            return true;
        }
    }
    return false;
}
Also used : SessionException(com.iplanet.dpro.session.SessionException) Map(java.util.Map) SessionID(com.iplanet.dpro.session.SessionID) Session(com.iplanet.dpro.session.Session) InternalSession(com.iplanet.dpro.session.service.InternalSession)

Example 15 with InternalSession

use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.

the class DestroyOldestAction method action.

@Override
public boolean action(InternalSession is, Map<String, Long> sessions) {
    long smallestExpTime = Long.MAX_VALUE;
    String oldestSessionID = null;
    for (Map.Entry<String, Long> entry : sessions.entrySet()) {
        try {
            Session session = sessionCache.getSession(new SessionID(entry.getKey()));
            session.refresh(false);
            long expTime = session.getTimeLeft();
            if (expTime < smallestExpTime) {
                smallestExpTime = expTime;
                oldestSessionID = entry.getKey();
            }
        } catch (SessionException ssoe) {
            if (debug.warningEnabled()) {
                debug.warning("Failed to create SSOToken", ssoe);
            }
            // in this case
            return true;
        }
    }
    if (oldestSessionID != null) {
        SessionID sessID = new SessionID(oldestSessionID);
        try {
            Session s = sessionCache.getSession(sessID);
            s.destroySession(s);
        } catch (SessionException e) {
            if (debug.messageEnabled()) {
                debug.message("Failed to destroy the next expiring session.", e);
            }
            // in this case
            return true;
        }
    }
    return false;
}
Also used : SessionException(com.iplanet.dpro.session.SessionException) Map(java.util.Map) SessionID(com.iplanet.dpro.session.SessionID) Session(com.iplanet.dpro.session.Session) InternalSession(com.iplanet.dpro.session.service.InternalSession)

Aggregations

InternalSession (com.iplanet.dpro.session.service.InternalSession)42 SessionID (com.iplanet.dpro.session.SessionID)17 Test (org.testng.annotations.Test)16 SSOException (com.iplanet.sso.SSOException)10 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)10 SSOToken (com.iplanet.sso.SSOToken)9 Token (org.forgerock.openam.cts.api.tokens.Token)8 SessionException (com.iplanet.dpro.session.SessionException)6 SSOTokenManager (com.iplanet.sso.SSOTokenManager)5 IOException (java.io.IOException)5 ModelControlException (com.iplanet.jato.model.ModelControlException)4 Map (java.util.Map)4 Session (com.iplanet.dpro.session.Session)3 AuthContextLocal (com.sun.identity.authentication.server.AuthContextLocal)3 AuthD (com.sun.identity.authentication.service.AuthD)3 SessionInfo (com.iplanet.dpro.session.share.SessionInfo)2 AuthException (com.sun.identity.authentication.service.AuthException)2 InvalidPasswordException (com.sun.identity.authentication.spi.InvalidPasswordException)2 ISLocaleContext (com.sun.identity.common.ISLocaleContext)2 SMSException (com.sun.identity.sm.SMSException)2