Search in sources :

Example 71 with AuthLoginException

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

the class PlainMechanismHandler method authenticate.

private SASLResponse authenticate(String data, Message message) {
    int indexNul = data.indexOf('\0');
    if (indexNul == -1) {
        return new SASLResponse(SASLResponse.ABORT);
    }
    int indexNul2 = data.indexOf('\0', indexNul + 1);
    if (indexNul2 == -1) {
        return new SASLResponse(SASLResponse.ABORT);
    }
    String authzID = data.substring(0, indexNul);
    String authnID = data.substring(indexNul + 1, indexNul2);
    String password = data.substring(indexNul2 + 1);
    if (authnID == null) {
        return new SASLResponse(SASLResponse.ABORT);
    }
    if (debug.messageEnabled()) {
        debug.message("PlainMechanismHandler.authenticate: " + "authzID = " + authzID + ", authnID = " + authnID);
    }
    String authModule = AuthnSvcService.getPlainMechanismAuthenticationModule();
    if (debug.messageEnabled()) {
        debug.message("PlainMechanismHandler.authenticate: " + "authModule = " + authModule);
    }
    AuthContext authContext = null;
    try {
        authContext = new AuthContext(SMSEntry.getRootSuffix());
        authContext.login(AuthContext.IndexType.MODULE_INSTANCE, authModule);
    } catch (AuthLoginException le) {
        debug.error("PlainMechanismHandler.authenticate: ", le);
        return new SASLResponse(SASLResponse.ABORT);
    }
    if (authContext.hasMoreRequirements()) {
        Callback[] callbacks = authContext.getRequirements();
        if (callbacks != null) {
            fillInCallbacks(callbacks, authnID, password);
            authContext.submitRequirements(callbacks);
        }
    }
    AuthContext.Status loginStatus = authContext.getStatus();
    if (debug.messageEnabled()) {
        debug.message("PlainMechanismHandler.authenticate: login status = " + loginStatus);
    }
    if (loginStatus != AuthContext.Status.SUCCESS) {
        return new SASLResponse(SASLResponse.ABORT);
    }
    try {
        SSOToken token = authContext.getSSOToken();
        String userDN = token.getPrincipal().getName();
        SASLResponse saslResp = new SASLResponse(SASLResponse.OK);
        try {
            SSOTokenManager.getInstance().destroyToken(token);
        } catch (SSOException ssoex) {
            if (AuthnSvcUtils.debug.warningEnabled()) {
                AuthnSvcUtils.debug.warning("PlainMechanismHandler.authenticate:", ssoex);
            }
        }
        if (!AuthnSvcUtils.setResourceOfferingAndCredentials(saslResp, message, userDN)) {
            return new SASLResponse(SASLResponse.ABORT);
        }
        return saslResp;
    } catch (Exception ex) {
        debug.error("PlainMechanismHandler.authenticate: ", ex);
        return new SASLResponse(SASLResponse.ABORT);
    }
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) SSOToken(com.iplanet.sso.SSOToken) SASLResponse(com.sun.identity.liberty.ws.authnsvc.protocol.SASLResponse) AuthContext(com.sun.identity.authentication.AuthContext) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 72 with AuthLoginException

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

the class SMAuthModule 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 siteminder agent, this will not further
     * validate the SMSESSION by the siteminder 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 (configuredHTTPHeaders != null) {
        request.setAttribute("SM-HTTPHeaders", configuredHTTPHeaders);
    }
    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 SMCookie = null;
    String principal = null;
    boolean cookieFound = false;
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookie.getName().equals("SMSESSION")) {
            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);
            InitDef id = new InitDef(hostName, sharedSecret, true, new ServerDef());
            id.addServerDef(policyServerIP, connectionMin, connectionMin, connectionStep, timeout, authorizationPort, authenticationPort, authorizationPort);
            AgentAPI agentAPI = new AgentAPI();
            int initStat = agentAPI.init(id);
            if (initStat == AgentAPI.SUCCESS) {
                System.out.println("Agent API init succeeded");
            }
            int version = 0;
            boolean thirdParty = false;
            TokenDescriptor td = new TokenDescriptor(version, thirdParty);
            AttributeList al = new AttributeList();
            StringBuffer token = new StringBuffer();
            int status = agentAPI.decodeSSOToken(value, td, al, true, token);
            if (status == AgentAPI.FAILURE) {
                System.out.println("SM session decode failed");
                throw new AuthLoginException("SMSession decode failed");
            } else {
                Enumeration attributes = al.attributes();
                while (attributes.hasMoreElements()) {
                    Attribute attr = (Attribute) attributes.nextElement();
                    int attrId = attr.id;
                    // debugging
                    System.out.println("Attribute Id: " + attrId);
                    String attrValue = XMLUtils.removeNullCharAtEnd(new String(attr.value));
                    System.out.println("Attribute value: " + attrValue);
                    if (attrId == AgentAPI.ATTR_USERDN)
                        userId = attrValue;
                }
            }
        }
    }
    return ISAuthConstants.LOGIN_SUCCEED;
}
Also used : Cookie(javax.servlet.http.Cookie) Enumeration(java.util.Enumeration) Attribute(netegrity.siteminder.javaagent.Attribute) AttributeList(netegrity.siteminder.javaagent.AttributeList) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InitDef(netegrity.siteminder.javaagent.InitDef) ServerDef(netegrity.siteminder.javaagent.ServerDef) HttpServletRequest(javax.servlet.http.HttpServletRequest) TokenDescriptor(netegrity.siteminder.javaagent.TokenDescriptor) AgentAPI(netegrity.siteminder.javaagent.AgentAPI)

Example 73 with AuthLoginException

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

the class SAE method process.

/**
     * Validates the authentication credentials.
     *
     * @return ISAuthConstants.LOGIN_SUCCEED on login success
     * @exception AuthLoginException on failure. 
     */
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    debug.message("SAE AuthModule.process...");
    HttpServletRequest req = getHttpServletRequest();
    if (req == null) {
        debug.error("SAE AuthModule.process: httprequest is null.");
        throw new AuthLoginException("HttpServletRequest is null");
    }
    String encodedString = req.getParameter(SecureAttrs.SAE_PARAM_DATA);
    if (debug.messageEnabled()) {
        debug.message("SAE AuthModule.process+encodedStr=" + encodedString);
    }
    String realm = req.getParameter(SAML2Constants.SAE_REALM);
    String idpEntityId = req.getParameter(SAML2Constants.SAE_IDP_ENTITYID);
    String idpAppUrl = req.getParameter(SAML2Constants.SAE_IDPAPP_URL);
    debug.message("SAE AuthModule.SAML2Utils.getSAEAttrs");
    Map saeattrs = SAML2Utils.getSAEAttrs(realm, idpEntityId, SAML2Constants.IDP_ROLE, idpAppUrl);
    if (saeattrs == null) {
        debug.error("SAE AuthModule.process:get SAE Attrs failed:null.");
        throw new AuthLoginException("SAE config Attributes are null");
    }
    String cryptoType = (String) saeattrs.get(SecureAttrs.SAE_CRYPTO_TYPE);
    String encryptAlg = (String) saeattrs.get(SecureAttrs.SAE_CONFIG_DATA_ENCRYPTION_ALG);
    String encryptStrength = (String) saeattrs.get(SecureAttrs.SAE_CONFIG_ENCRYPTION_KEY_STRENGTH);
    String saekey = null;
    String saeprivatekey = null;
    if ("symmetric".equals(cryptoType)) {
        saekey = (String) saeattrs.get(SecureAttrs.SAE_CONFIG_SHARED_SECRET);
        saeprivatekey = saekey;
    } else if ("asymmetric".equals(cryptoType)) {
        saekey = (String) saeattrs.get(SecureAttrs.SAE_CONFIG_PUBLIC_KEY_ALIAS);
        saeprivatekey = (String) saeattrs.get(SecureAttrs.SAE_CONFIG_PRIVATE_KEY_ALIAS);
    }
    if (debug.messageEnabled()) {
        debug.message("SAE AuthModule: realm=" + realm + ", idpEntityID=" + idpEntityId + ", idpAppUrl=" + idpAppUrl + ", cryptoType=" + cryptoType + ", key=" + saekey);
    }
    Map attrs = null;
    try {
        String saInstanceName = cryptoType + "_" + encryptAlg + "_" + encryptStrength;
        SecureAttrs sa = SecureAttrs.getInstance(saInstanceName);
        if (sa == null) {
            // Initialize SecureAttrs here.
            Properties prop = new Properties();
            prop.setProperty(SecureAttrs.SAE_CONFIG_CERT_CLASS, "com.sun.identity.sae.api.FMCerts");
            if (encryptAlg != null) {
                prop.setProperty(SecureAttrs.SAE_CONFIG_DATA_ENCRYPTION_ALG, encryptAlg);
            }
            if (encryptStrength != null) {
                prop.setProperty(SecureAttrs.SAE_CONFIG_ENCRYPTION_KEY_STRENGTH, encryptStrength);
            }
            SecureAttrs.init(saInstanceName, cryptoType, prop);
            sa = SecureAttrs.getInstance(saInstanceName);
        }
        attrs = sa.verifyEncodedString(encodedString, saekey, saeprivatekey);
        if (debug.messageEnabled())
            debug.message("SAE AuthModule.: SAE attrs:" + attrs);
    } catch (Exception ex) {
        debug.error("SAE AuthModule.process: verification failed.", ex);
        throw new AuthLoginException("verify failed");
    }
    if (attrs == null) {
        debug.error("SAE AuthModule.process:verification failed:attrs null.");
        throw new AuthLoginException("Attributes are null");
    }
    userTokenId = (String) attrs.get(SecureAttrs.SAE_PARAM_USERID);
    Iterator iter = attrs.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        if (key.equals(SecureAttrs.SAE_PARAM_USERID)) {
            continue;
        }
        if (debug.messageEnabled()) {
            debug.message("Session Property set: " + key + "= " + value);
        }
        setUserSessionProperty(key, value);
    }
    String authLevel = (String) attrs.get(SecureAttrs.SAE_PARAM_AUTHLEVEL);
    int authLevelInt = DEFAULT_AUTH_LEVEL;
    if (authLevel != null && authLevel.length() != 0) {
        try {
            authLevelInt = Integer.parseInt(authLevel);
        } catch (Exception e) {
            debug.error("Unable to parse auth level " + authLevel + ". Using default.", e);
            authLevelInt = DEFAULT_AUTH_LEVEL;
        }
    }
    if (debug.messageEnabled()) {
        debug.message("SAE AuthModule: auth level = " + authLevelInt);
    }
    setAuthLevel(authLevelInt);
    debug.message("SAE AuthModule:return SUCCESS");
    return ISAuthConstants.LOGIN_SUCCEED;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SecureAttrs(com.sun.identity.sae.api.SecureAttrs) Iterator(java.util.Iterator) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) Properties(java.util.Properties) HashMap(java.util.HashMap) Map(java.util.Map) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException)

Example 74 with AuthLoginException

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

the class ClientAuthenticatorImpl method authenticate.

/**
     * Perform the authentication of the client using the specified client credentials.
     *
     * @param clientId The client's id.
     * @param clientSecret The client's secret.
     * @param realm The realm the client exists in.
     * @return {@code true} if the client was authenticated successfully.
     * @throws InvalidClientException If the authentication configured for the client is not completed by the
     *          specified client credentials.
     */
private boolean authenticate(OAuth2Request request, String clientId, char[] clientSecret, String realm) throws InvalidClientException {
    try {
        AuthContext lc = new AuthContext(realm);
        lc.login(AuthContext.IndexType.MODULE_INSTANCE, "Application");
        while (lc.hasMoreRequirements()) {
            Callback[] callbacks = lc.getRequirements();
            List<Callback> missing = new ArrayList<Callback>();
            // loop through the requires setting the needs..
            for (final Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    NameCallback nc = (NameCallback) callback;
                    nc.setName(clientId);
                } else if (callback instanceof PasswordCallback) {
                    PasswordCallback pc = (PasswordCallback) callback;
                    pc.setPassword(clientSecret);
                } else {
                    missing.add(callback);
                }
            }
            // there's missing requirements not filled by this
            if (missing.size() > 0) {
                lc.logout();
                throw failureFactory.getException(request, "Missing requirements");
            }
            lc.submitRequirements(callbacks);
        }
        // validate the password..
        if (lc.getStatus() == AuthContext.Status.SUCCESS) {
            lc.logout();
            return true;
        } else {
            throw failureFactory.getException(request, "Client authentication failed");
        }
    } catch (AuthLoginException le) {
        logger.error("ClientVerifierImpl::authContext AuthException", le);
        throw failureFactory.getException(request, "Client authentication failed");
    }
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ArrayList(java.util.ArrayList) AuthContext(com.sun.identity.authentication.AuthContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException)

Example 75 with AuthLoginException

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

the class OpenAMResourceOwnerAuthenticator method authenticate.

private ResourceOwner authenticate(String username, char[] password, String realm, String service) {
    ResourceOwner ret = null;
    AuthContext lc = null;
    try {
        lc = new AuthContext(realm);
        if (service != null) {
            lc.login(AuthContext.IndexType.SERVICE, service, null, ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
        } else {
            lc.login(ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
        }
        while (lc.hasMoreRequirements()) {
            Callback[] callbacks = lc.getRequirements();
            ArrayList missing = new ArrayList();
            // loop through the requires setting the needs..
            for (int i = 0; i < callbacks.length; i++) {
                if (callbacks[i] instanceof NameCallback) {
                    NameCallback nc = (NameCallback) callbacks[i];
                    nc.setName(username);
                } else if (callbacks[i] instanceof PasswordCallback) {
                    PasswordCallback pc = (PasswordCallback) callbacks[i];
                    pc.setPassword(password);
                } else {
                    missing.add(callbacks[i]);
                }
            }
            // there's missing requirements not filled by this
            if (missing.size() > 0) {
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Missing requirements");
            }
            lc.submitRequirements(callbacks);
        }
        // validate the password..
        if (lc.getStatus() == AuthContext.Status.SUCCESS) {
            try {
                // package up the token for transport..
                ret = createResourceOwner(lc);
            } catch (Exception e) {
                logger.error("Unable to get SSOToken", e);
                // because the system is likely down..
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
            }
        }
    } catch (AuthLoginException le) {
        logger.error("AuthException", le);
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, le);
    } finally {
        if (lc != null && AuthContext.Status.SUCCESS.equals(lc.getStatus())) {
            try {
                lc.logout();
                logger.message("Logged user out.");
            } catch (AuthLoginException e) {
                logger.error("Exception caught logging out of AuthContext after successful login", e);
            }
        }
    }
    return ret;
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) ArrayList(java.util.ArrayList) AuthContext(com.sun.identity.authentication.AuthContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ResourceException(org.restlet.resource.ResourceException) IdRepoException(com.sun.identity.idm.IdRepoException) ResourceException(org.restlet.resource.ResourceException) ParseException(java.text.ParseException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

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