Search in sources :

Example 91 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class SessionCommand method handleRequest.

public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);
    Authenticator auth = Authenticator.getInstance();
    String bindUser = getAdminID();
    AuthContext lc = auth.sessionBasedLogin(getCommandManager(), bindUser, getAdminPassword());
    try {
        boolean isQuiet = isOptionSet(QUIET_PARAM);
        handleRequest(lc.getSSOToken(), isQuiet);
        try {
            lc.logout();
        } catch (AuthLoginException e) {
            throw new CLIException(e, ExitCodes.SESSION_BASED_LOGOUT_FAILED);
        }
    } catch (Exception e) {
        throw new CLIException(e, ExitCodes.SESSION_BASED_LOGIN_FAILED);
    }
}
Also used : AuthContext(com.sun.identity.authentication.AuthContext) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) IOException(java.io.IOException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SessionException(com.iplanet.dpro.session.SessionException)

Example 92 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class OblixAuthModule method process.

/**
     * This method process the login procedure for this authentication
     * module. In this auth module, if the user chooses to just validate
     * the HTTP headers set by the oracle webgent, this will not further
     * validate the OblixSesson by the Oracle AM SDK since the same thing
     * might have already been validated by the agent.
     */
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    HttpServletRequest request = getHttpServletRequest();
    if (checkRemoteUserOnly) {
        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            if (headerName.equals(remoteUserHeader)) {
                userId = request.getHeader(headerName);
            }
        }
        if (userId == null) {
            throw new AuthLoginException("No remote user header found");
        }
        return ISAuthConstants.LOGIN_SUCCEED;
    }
    Cookie[] cookies = request.getCookies();
    String OAMCookie = null;
    String principal = null;
    boolean cookieFound = false;
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookie.getName().equals(oamCookieName)) {
            cookieFound = true;
            String value = cookie.getValue();
            System.out.println("cookie value" + value);
            //value = java.net.URLEncoder.encode(value);
            value = value.replaceAll(" ", "+");
            value = value.replaceAll("%3D", "=");
            System.out.println("cookie value afer replacing: " + value);
            try {
                ObUserSession userSession = new ObUserSession(value);
                if ((userSession != null) && (userSession.getStatus() == ObUserSession.LOGGEDIN)) {
                    userId = userSession.getUserIdentity();
                } else {
                    System.out.println("Oblix session decode failed");
                    throw new AuthLoginException("OblixSession decode failed");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new AuthLoginException("OblixSession decode failed");
            }
        }
    }
    if (!cookieFound) {
        throw new AuthLoginException("Authentication failed. " + "No Oblix cookie found");
    }
    return ISAuthConstants.LOGIN_SUCCEED;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) Enumeration(java.util.Enumeration) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) LoginException(javax.security.auth.login.LoginException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException)

Example 93 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class LogSample method logWriteProcessing.

private void logWriteProcessing() {
    /*
         *  get:
         *    1. subject userid (subject of the LogRecord)
	 *    2. subject userid's password
         *    3. Log filename to log to
         *    4. LogRecord's "data"
         *    5. LoggedBy userid (who's doing the logging)
         *    6. LoggedBy userid's password
         *    7. Realm (for both subject userid and LoggedBy userid
         *       in this sample)
         */
    String userSID = sampleUtils.getLine("Subject Userid", DEF_USERNAME);
    String userPWD = sampleUtils.getLine("Subject Userid " + userSID + "'s password", DEF_USERPSWD);
    String logName = sampleUtils.getLine("Log file", DEF_LOGNAME);
    String message = sampleUtils.getLine("Log message", DEF_LOGMSG);
    ;
    String loggedBySID = sampleUtils.getLine("LoggedBy Userid", DEF_LOGGEDBY);
    String loggedByPWD = sampleUtils.getLine("LoggedBy Userid's password", DEF_LOGGEDBYPSWD);
    String realmName = sampleUtils.getLine("Realm", DEF_REALM);
    // get AuthContexts for subject userid and loggedby userid
    try {
        userAC = new AuthContext(realmName);
        loggerAC = new AuthContext(realmName);
    } catch (AuthLoginException le) {
        System.err.println("LogSampleUtils: could not get AuthContext for realm " + realmName);
        System.exit(2);
    }
    // do user and loggedby login and get the SSOToken
    try {
        userSSOToken = sampleUtils.realmLogin(userSID, userPWD, userAC);
        loggerSSOToken = sampleUtils.realmLogin(loggedBySID, loggedByPWD, loggerAC);
    } catch (SSOException ssoe) {
        System.err.println("logWriteProcessing: could not get SSOToken: " + ssoe.getMessage());
        System.exit(3);
    } catch (AuthLoginException ale) {
        System.err.println("logWriteProcessing: could not authenticate: " + ale.getMessage());
        System.exit(4);
    } catch (Exception e) {
        System.err.println("logWriteProcessing: exception getting SSOToken: " + e.getMessage());
        System.exit(5);
    }
    try {
        LogRecord logRecord = new LogRecord(java.util.logging.Level.INFO, message, userSSOToken);
        logRecord.addLogInfo("ModuleName", DEF_MODULENAME);
        java.net.InetAddress ipAddr = java.net.InetAddress.getLocalHost();
        logRecord.addLogInfo("IPAddr", ipAddr.getHostAddress());
        Logger logger = (Logger) Logger.getLogger(logName);
        logger.log(logRecord, loggerSSOToken);
        System.out.println("LogSample: Logging Successful !!!");
        userAC.logout();
        loggerAC.logout();
    } catch (AMLogException amex) {
        System.err.println("LogSample: AMLogException: " + amex.getMessage());
        System.err.println("LogSample: Logging Failed; " + "Is user '" + loggedBySID + "' a member of a Role or Group with log writing privileges?");
    } catch (Exception ssoe) {
        System.err.println("LogSample: Exception: " + ssoe.getMessage());
        System.err.println("LogSample: Logging Failed !!!");
    }
}
Also used : LogRecord(com.sun.identity.log.LogRecord) AuthContext(com.sun.identity.authentication.AuthContext) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) AMLogException(com.sun.identity.log.AMLogException) SSOException(com.iplanet.sso.SSOException) Logger(com.sun.identity.log.Logger) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) AMLogException(com.sun.identity.log.AMLogException)

Example 94 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class IdRepoSample method idRepoProcessing.

/*
     *  start of IdRepo processing.  have the starting realm name.
     *  get an SSOToken, and start processing requests.
     */
private void idRepoProcessing() {
    /*
         *  get:
         *    1. userid (default "amadmin")
         *    2. userid password (default "openssoxxx")
         *    3. starting realm (default "/")
         */
    String userSID = sampleUtils.getLine("Userid", DEF_USERNAME);
    String userPWD = sampleUtils.getLine("Userid " + userSID + "'s password", DEF_USERPWD);
    String realmName = sampleUtils.getLine("Realm", DEF_REALM);
    try {
        ssoToken = sampleUtils.realmLogin(userSID, userPWD, realmName);
    } catch (SSOException ssoe) {
        System.err.println("idRepoProcessing: could not get SSOToken: " + ssoe.getMessage());
        System.exit(3);
    } catch (AuthLoginException ale) {
        System.err.println("idRepoProcessing: could not authenticate: " + ale.getMessage());
        System.exit(4);
    } catch (Exception e) {
        System.err.println("idRepoProcessing: exception getting SSOToken: " + e.getMessage());
        System.exit(5);
    }
    /*
         *  retrieve some information about the current realm, if
         *  we can as the userid specified.
         */
    currentRealm = realmName;
    doCurrentRealm();
    int i = -1;
    boolean doMore = true;
    String ans = null;
    int ians = -1;
    while (doMore) {
        i = printIdRepoMenu();
        switch(i) {
            case // select (sub)realm
            0:
                IdRepoSampleSubRealm issr = new IdRepoSampleSubRealm(currentRealm);
                String nextSubRealm = issr.selectSubRealm(currentSubRealms);
                if (nextSubRealm != currentRealm) {
                    currentRealm = nextSubRealm;
                    idRepo = new AMIdentityRepository(currentRealm, ssoToken);
                    doCurrentRealm();
                }
                break;
            case // create identity
            1:
                IdRepoSampleCreateId isci = new IdRepoSampleCreateId(idRepo);
                isci.createAMId();
                break;
            case // delete identity
            2:
                IdRepoSampleDeleteId isdi = new IdRepoSampleDeleteId(idRepo);
                isdi.deleteAMId();
                break;
            case // get allowed id operations
            3:
                try {
                    Set types = idRepo.getSupportedIdTypes();
                    IdType itype = null;
                    Set ops = null;
                    for (Iterator it = types.iterator(); it.hasNext(); ) {
                        itype = (IdType) it.next();
                        ops = idRepo.getAllowedIdOperations(itype);
                        sampleUtils.printResults("IdType '" + itype.getName() + "'", ops, "allowed Identity Operations");
                    }
                } catch (IdRepoException ire) {
                    System.err.println("idRepoProcessing:IdRepoException: " + ire.getMessage());
                } catch (SSOException ssoe) {
                    System.err.println("idRepoProcessing:SSOException: " + ssoe.getMessage());
                }
                break;
            case // get supported IdTypes
            4:
                try {
                    Set types = idRepo.getSupportedIdTypes();
                    sampleUtils.printIdTypeResults("This deployment", types, "supported IdTypes");
                } catch (IdRepoException ire) {
                    System.err.println("idRepoProcessing:IdRepoException: " + ire.getMessage());
                } catch (SSOException ssoe) {
                    System.err.println("idRepoProcessing:SSOException: " + ssoe.getMessage());
                }
                break;
            case // search/select Identities
            5:
                IdRepoSampleSearchIds issi = new IdRepoSampleSearchIds(idRepo);
                issi.searchAMIds();
                break;
            case // return to '/' realm
            6:
                currentRealm = DEF_REALM;
                doCurrentRealm();
                break;
            case // exit
            7:
                doMore = false;
                break;
            default:
                System.err.println("Invalid selection; try again.");
        }
    }
    try {
        sampleUtils.logout();
    } catch (AuthLoginException alexc) {
        System.err.println("idRepoProcessing: logout failed for user '" + userSID + "'");
        alexc.printStackTrace();
        System.exit(10);
    }
    System.out.println("idRepoProcessing: user '" + userSID + "' logged out");
}
Also used : Set(java.util.Set) IdRepoException(com.sun.identity.idm.IdRepoException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) Iterator(java.util.Iterator)

Example 95 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class FMSessionProvider method createSession.

/** 
     * Meaningful only for SP side, the implementation of this method
     * will create a local session for the local user identified by
     * the information in the map. The underline mechanism of the
     * session creation and management is application specific.
     * For example, it could be cookie setting or url rewriting, which 
     * is expected to be done by the implementation of this method.
     * Note that only the first input parameter is mandatory. Normally,
     * at least one of the last two parameters should not be null
     * 
     * @param info a Map with keys and values being of type String; The
     *             keys will include "principalName" (returned from
     *             SPAccountMapper), "realm", "authLevel", and may
     *             include "resourceOffering" and/or "idpEntityID";
     *             The implementation of this method could choose to set
     *             some of the information contained in the map into the
     *             newly created Session by calling setProperty(), later
     *             the target application may consume the information. 
     * @param request the HttpServletRequest the user made to initiate
     *                the SSO.
     * @param response the HttpServletResponse that will be sent to the
     *                 user (for example it could be used to set a cookie).
     * @param targetApplication the original resource that was requested
     *                          as the target of the SSO by the end user;
     *                          If needed, this String could be modified,
     *                          e.g., by appending query string(s) or by
     *                          url rewriting, hence this is an in/out
     *                          parameter.
     * @return the newly created local user session.
     * @throws SessionException if an error occurred during session
     * creation.
     */
public Object createSession(// in
Map info, // in
HttpServletRequest request, // in/out
HttpServletResponse response, // in/out
StringBuffer targetApplication) throws SessionException {
    String realm = (String) info.get(REALM);
    if (realm == null || realm.length() == 0) {
        throw new SessionException(bundle.getString("nullRealm"));
    }
    String principalName = (String) info.get(PRINCIPAL_NAME);
    if (principalName == null || principalName.length() == 0) {
        throw new SessionException(bundle.getString("nullPrincipal"));
    }
    String authLevel = (String) info.get(AUTH_LEVEL);
    Object oldSession = null;
    if (request != null) {
        try {
            oldSession = getSession(request);
            String oldPrincipal = getPrincipalName(oldSession);
            oldPrincipal = oldPrincipal.toLowerCase();
            if ((!oldPrincipal.equals(principalName.toLowerCase())) && (!oldPrincipal.startsWith("id=" + principalName.toLowerCase() + ","))) {
                invalidateSession(oldSession, request, response);
                oldSession = null;
            }
        } catch (SessionException se) {
            oldSession = null;
        }
    }
    // Call auth module "Federation"
    AuthContext ac = null;
    try {
        if (oldSession != null) {
            ac = new AuthContext((SSOToken) oldSession, true);
        } else {
            ac = new AuthContext(realm);
        }
        ac.login(AuthContext.IndexType.MODULE_INSTANCE, "Federation", null, null, request, response);
    } catch (AuthLoginException ale) {
        throw new SessionException(ale);
    }
    Callback[] callbacks = null;
    while (ac.hasMoreRequirements()) {
        callbacks = ac.getRequirements();
        if (callbacks == null || callbacks.length == 0) {
            continue;
        }
        for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
                NameCallback nc = (NameCallback) callbacks[i];
                if (nc.getPrompt().equals(PRINCIPAL_NAME)) {
                    nc.setName(principalName);
                } else if (nc.getPrompt().equals(RANDOM_SECRET)) {
                    String randomString = generateSecret();
                    while (secretSet.contains(randomString)) {
                        randomString = generateSecret();
                    }
                    secretSet.add(randomString);
                    nc.setName(randomString);
                } else if (nc.getPrompt().equals(AUTH_LEVEL)) {
                    nc.setName(authLevel);
                }
            }
        }
        break;
    }
    ac.submitRequirements(callbacks);
    SSOToken ssoToken = null;
    if (ac.getStatus() == AuthContext.Status.SUCCESS) {
        try {
            ssoToken = ac.getSSOToken();
        } catch (Exception e) {
            throw new SessionException(e.getMessage());
        }
    } else if (ac.getStatus() == AuthContext.Status.FAILED) {
        // TODO: test again when auth changes are done so the error code
        // is set and passed over
        int failureCode = SessionException.AUTH_ERROR_NOT_DEFINED;
        AuthLoginException ale = ac.getLoginException();
        String authError = null;
        if (ale != null) {
            authError = ale.getErrorCode();
        }
        if (authError == null) {
            failureCode = SessionException.AUTH_ERROR_NOT_DEFINED;
        } else if (authError.equals(AMAuthErrorCode.AUTH_USER_INACTIVE)) {
            failureCode = SessionException.AUTH_USER_INACTIVE;
        } else if (authError.equals(AMAuthErrorCode.AUTH_USER_LOCKED)) {
            failureCode = SessionException.AUTH_USER_LOCKED;
        } else if (authError.equals(AMAuthErrorCode.AUTH_ACCOUNT_EXPIRED)) {
            failureCode = SessionException.AUTH_ACCOUNT_EXPIRED;
        }
        SessionException se = null;
        if (ale != null) {
            se = new SessionException(ale);
        } else {
            se = new SessionException(bundle.getString("loginFailed"));
        }
        se.setErrCode(failureCode);
        throw se;
    } else {
        throw new SessionException(bundle.getString("loginFailed"));
    }
    if (response != null) {
        ServiceSchemaManager scm = null;
        try {
            scm = new ServiceSchemaManager("iPlanetAMPlatformService", ssoToken);
        } catch (Exception e) {
            throw new SessionException(e);
        }
        ServiceSchema platformSchema = null;
        try {
            platformSchema = scm.getGlobalSchema();
        } catch (SMSException se) {
            throw new SessionException(se);
        }
        setLoadBalancerCookie(request, response);
        Set cookieDomains = (Set) platformSchema.getAttributeDefaults().get("iplanet-am-platform-cookie-domains");
        String value = ssoToken.getTokenID().toString();
        if (cookieDomains.size() == 0) {
            Cookie cookie = CookieUtils.newCookie(cookieName, value, "/");
            CookieUtils.addCookieToResponse(response, cookie);
        } else {
            Iterator it = cookieDomains.iterator();
            Cookie cookie = null;
            String cookieDomain = null;
            while (it.hasNext()) {
                cookieDomain = (String) it.next();
                if (debug.messageEnabled()) {
                    debug.message("cookieName=" + cookieName);
                    debug.message("value=" + value);
                    debug.message("cookieDomain=" + cookieDomain);
                }
                cookie = CookieUtils.newCookie(cookieName, value, "/", cookieDomain);
                CookieUtils.addCookieToResponse(response, cookie);
            }
        }
        if (urlRewriteEnabled && targetApplication != null) {
            int n = targetApplication.length();
            if (n > 0) {
                String rewrittenURL = rewriteURL(ssoToken, targetApplication.toString());
                targetApplication.delete(0, n);
                targetApplication.append(rewrittenURL);
            }
        }
    }
    // set all properties in the info map to sso token
    try {
        Iterator it = info.keySet().iterator();
        while (it.hasNext()) {
            String keyName = (String) it.next();
            if (keyName.equals(AUTH_LEVEL)) {
                continue;
            }
            String keyVal = (String) info.get(keyName);
            ssoToken.setProperty(keyName, StringUtils.getEscapedValue(keyVal));
        }
    } catch (SSOException se) {
        throw new SessionException(se);
    }
    return ssoToken;
}
Also used : Cookie(javax.servlet.http.Cookie) SSOToken(com.iplanet.sso.SSOToken) HashSet(java.util.HashSet) Set(java.util.Set) SMSException(com.sun.identity.sm.SMSException) SessionException(com.sun.identity.plugin.session.SessionException) AuthContext(com.sun.identity.authentication.AuthContext) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) SessionException(com.sun.identity.plugin.session.SessionException) SMSException(com.sun.identity.sm.SMSException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) ServiceSchema(com.sun.identity.sm.ServiceSchema) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) Iterator(java.util.Iterator) ServiceSchemaManager(com.sun.identity.sm.ServiceSchemaManager)

Aggregations

AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)118 SSOException (com.iplanet.sso.SSOException)39 Callback (javax.security.auth.callback.Callback)29 IdRepoException (com.sun.identity.idm.IdRepoException)27 InvalidPasswordException (com.sun.identity.authentication.spi.InvalidPasswordException)25 NameCallback (javax.security.auth.callback.NameCallback)24 PasswordCallback (javax.security.auth.callback.PasswordCallback)23 IOException (java.io.IOException)20 Set (java.util.Set)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 SSOToken (com.iplanet.sso.SSOToken)14 HashMap (java.util.HashMap)14 AuthContext (com.sun.identity.authentication.AuthContext)13 Map (java.util.Map)12 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)12 Test (org.testng.annotations.Test)12 HashSet (java.util.HashSet)9 LoginException (javax.security.auth.login.LoginException)8 SSOTokenManager (com.iplanet.sso.SSOTokenManager)7 AuthException (com.sun.identity.authentication.service.AuthException)7