Search in sources :

Example 1 with LoginModule

use of javax.security.auth.spi.LoginModule in project OpenAM by OpenRock.

the class LoginContextTest method setUp.

/**
     * This test sets up four mock login modules, each with different control flags. The modules are created with
     * control flags in the following order: required, requisite, sufficient and optional.
     *
     * @throws LoginException
     *         Can be thrown by invocation of the authentication framework.
     */
@BeforeMethod
public void setUp() throws LoginException {
    optionCache = new HashMap<LoginModule, Map<String, Object>>();
    // Create required delegate login module.
    requiredDelegate = mock(LoginModule.class);
    Map<String, Object> requiredOptions = new HashMap<String, Object>();
    requiredOptions.put(DELEGATE_MODULE, requiredDelegate);
    optionCache.put(requiredDelegate, requiredOptions);
    AppConfigurationEntry requiredEntry = new AppConfigurationEntry(LOGIN_MODULE, LoginModuleControlFlag.REQUIRED, requiredOptions);
    // Create requisite delegate login module.
    requisiteDelegate = mock(LoginModule.class);
    Map<String, Object> requisiteOptions = new HashMap<String, Object>();
    requisiteOptions.put(DELEGATE_MODULE, requisiteDelegate);
    optionCache.put(requisiteDelegate, requisiteOptions);
    AppConfigurationEntry requisiteEntry = new AppConfigurationEntry(LOGIN_MODULE, LoginModuleControlFlag.REQUISITE, requisiteOptions);
    // Create sufficient delegate login module.
    sufficientDelegate = mock(LoginModule.class);
    Map<String, Object> sufficientOptions = new HashMap<String, Object>();
    sufficientOptions.put(DELEGATE_MODULE, sufficientDelegate);
    optionCache.put(sufficientDelegate, sufficientOptions);
    AppConfigurationEntry sufficientEntry = new AppConfigurationEntry(LOGIN_MODULE, LoginModuleControlFlag.SUFFICIENT, sufficientOptions);
    // Create optional delegate login module.
    optionalDelegate = mock(LoginModule.class);
    Map<String, Object> optionalOptions = new HashMap<String, Object>();
    optionalOptions.put(DELEGATE_MODULE, optionalDelegate);
    optionCache.put(optionalDelegate, optionalOptions);
    AppConfigurationEntry optionalEntry = new AppConfigurationEntry(LOGIN_MODULE, LoginModuleControlFlag.OPTIONAL, optionalOptions);
    AppConfigurationEntry[] entries = new AppConfigurationEntry[] { requiredEntry, requisiteEntry, sufficientEntry, optionalEntry };
    subject = new Subject();
    handler = mock(CallbackHandler.class);
    // Initialise class under test.
    context = new LoginContext(entries, subject, handler);
}
Also used : AppConfigurationEntry(javax.security.auth.login.AppConfigurationEntry) CallbackHandler(javax.security.auth.callback.CallbackHandler) HashMap(java.util.HashMap) LoginModule(javax.security.auth.spi.LoginModule) HashMap(java.util.HashMap) Matchers.anyMap(org.mockito.Matchers.anyMap) Map(java.util.Map) Subject(javax.security.auth.Subject) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 2 with LoginModule

use of javax.security.auth.spi.LoginModule in project Bytecoder by mirkosertic.

the class LoginContext method invoke.

private void invoke(String methodName) throws LoginException {
    for (int i = moduleIndex; i < moduleStack.length; i++, moduleIndex++) {
        try {
            if (moduleStack[i].module == null) {
                // locate and instantiate the LoginModule
                // 
                String name = moduleStack[i].entry.getLoginModuleName();
                ServiceLoader<LoginModule> sc = AccessController.doPrivileged((PrivilegedAction<ServiceLoader<LoginModule>>) () -> ServiceLoader.load(LoginModule.class, contextClassLoader));
                for (LoginModule m : sc) {
                    if (m.getClass().getName().equals(name)) {
                        moduleStack[i].module = m;
                        if (debug != null) {
                            debug.println(name + " loaded as a service");
                        }
                        break;
                    }
                }
                if (moduleStack[i].module == null) {
                    try {
                        @SuppressWarnings("deprecation") Object tmp = Class.forName(name, false, contextClassLoader).newInstance();
                        moduleStack[i].module = (LoginModule) tmp;
                        if (debug != null) {
                            debug.println(name + " loaded via reflection");
                        }
                    } catch (ClassNotFoundException e) {
                        throw new LoginException("No LoginModule found for " + name);
                    }
                }
                // invoke the LoginModule initialize method
                moduleStack[i].module.initialize(subject, callbackHandler, state, moduleStack[i].entry.getOptions());
            }
            // find the requested method in the LoginModule
            boolean status;
            switch(methodName) {
                case LOGIN_METHOD:
                    status = moduleStack[i].module.login();
                    break;
                case COMMIT_METHOD:
                    status = moduleStack[i].module.commit();
                    break;
                case LOGOUT_METHOD:
                    status = moduleStack[i].module.logout();
                    break;
                case ABORT_METHOD:
                    status = moduleStack[i].module.abort();
                    break;
                default:
                    throw new AssertionError("Unknown method " + methodName);
            }
            if (status == true) {
                // if SUFFICIENT, return if no prior REQUIRED errors
                if (!methodName.equals(ABORT_METHOD) && !methodName.equals(LOGOUT_METHOD) && moduleStack[i].entry.getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT && firstRequiredError == null) {
                    // clear state
                    clearState();
                    if (debug != null)
                        debug.println(methodName + " SUFFICIENT success");
                    return;
                }
                if (debug != null)
                    debug.println(methodName + " success");
                success = true;
            } else {
                if (debug != null)
                    debug.println(methodName + " ignored");
            }
        } catch (Exception ite) {
            // failure cases
            LoginException le;
            if (ite instanceof PendingException && methodName.equals(LOGIN_METHOD)) {
                throw (PendingException) ite;
            } else if (ite instanceof LoginException) {
                le = (LoginException) ite;
            } else if (ite instanceof SecurityException) {
                // do not want privacy leak
                // (e.g., sensitive file path in exception msg)
                le = new LoginException("Security Exception");
                le.initCause(new SecurityException());
                if (debug != null) {
                    debug.println("original security exception with detail msg " + "replaced by new exception with empty detail msg");
                    debug.println("original security exception: " + ite.toString());
                }
            } else {
                // capture an unexpected LoginModule exception
                java.io.StringWriter sw = new java.io.StringWriter();
                ite.printStackTrace(new java.io.PrintWriter(sw));
                sw.flush();
                le = new LoginException(sw.toString());
            }
            if (moduleStack[i].entry.getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUISITE) {
                if (debug != null)
                    debug.println(methodName + " REQUISITE failure");
                // if REQUISITE, then immediately throw an exception
                if (methodName.equals(ABORT_METHOD) || methodName.equals(LOGOUT_METHOD)) {
                    if (firstRequiredError == null)
                        firstRequiredError = le;
                } else {
                    throwException(firstRequiredError, le);
                }
            } else if (moduleStack[i].entry.getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUIRED) {
                if (debug != null)
                    debug.println(methodName + " REQUIRED failure");
                // mark down that a REQUIRED module failed
                if (firstRequiredError == null)
                    firstRequiredError = le;
            } else {
                if (debug != null)
                    debug.println(methodName + " OPTIONAL failure");
                // mark down that an OPTIONAL module failed
                if (firstError == null)
                    firstError = le;
            }
        }
    }
    // we went thru all the LoginModules.
    if (firstRequiredError != null) {
        // a REQUIRED module failed -- return the error
        throwException(firstRequiredError, null);
    } else if (success == false && firstError != null) {
        // no module succeeded -- return the first error
        throwException(firstError, null);
    } else if (success == false) {
        // no module succeeded -- all modules were IGNORED
        throwException(new LoginException(ResourcesMgr.getString("Login.Failure.all.modules.ignored")), null);
    } else {
        // success
        clearState();
        return;
    }
}
Also used : PendingException(sun.security.util.PendingException) LoginModule(javax.security.auth.spi.LoginModule) PendingException(sun.security.util.PendingException) ServiceLoader(java.util.ServiceLoader)

Example 3 with LoginModule

use of javax.security.auth.spi.LoginModule in project jackrabbit-oak by apache.

the class ExternalLoginModuleFactoryTest method setUpJaasFactoryWithInjection.

/**
 * Prepares the OSGi part with required services injected and configures
 * the factory in JAAS options which then delegates to ExternalLoginModuleFactory
 */
private void setUpJaasFactoryWithInjection() throws Exception {
    context.registerService(Repository.class, EasyMock.createMock(Repository.class));
    context.registerService(SyncManager.class, new SyncManagerImpl(whiteboard));
    context.registerService(ExternalIdentityProviderManager.class, new ExternalIDPManagerImpl(whiteboard));
    final LoginModuleFactory lmf = context.registerInjectActivateService(new ExternalLoginModuleFactory());
    options.put(ProxyLoginModule.PROP_LOGIN_MODULE_FACTORY, new ProxyLoginModule.BootLoginModuleFactory() {

        @Override
        public LoginModule createLoginModule() {
            return lmf.createLoginModule();
        }
    });
}
Also used : ProxyLoginModule(org.apache.felix.jaas.boot.ProxyLoginModule) Repository(javax.jcr.Repository) LoginModuleFactory(org.apache.felix.jaas.LoginModuleFactory) LoginModule(javax.security.auth.spi.LoginModule) ProxyLoginModule(org.apache.felix.jaas.boot.ProxyLoginModule)

Example 4 with LoginModule

use of javax.security.auth.spi.LoginModule in project jspwiki by apache.

the class AuthenticationManager method doJAASLogin.

/**
 * Instantiates and executes a single JAAS
 * {@link javax.security.auth.spi.LoginModule}, and returns a Set of
 * Principals that results from a successful login. The LoginModule is instantiated,
 * then its {@link javax.security.auth.spi.LoginModule#initialize(Subject, CallbackHandler, Map, Map)}
 * method is called. The parameters passed to <code>initialize</code> is a
 * dummy Subject, an empty shared-state Map, and an options Map the caller supplies.
 *
 * @param clazz
 *            the LoginModule class to instantiate
 * @param handler
 *            the callback handler to supply to the LoginModule
 * @param options
 *            a Map of key/value strings for initializing the LoginModule
 * @return the set of Principals returned by the JAAS method {@link Subject#getPrincipals()}
 * @throws WikiSecurityException
 *             if the LoginModule could not be instantiated for any reason
 */
protected Set<Principal> doJAASLogin(Class<? extends LoginModule> clazz, CallbackHandler handler, Map<String, String> options) throws WikiSecurityException {
    // Instantiate the login module
    LoginModule loginModule = null;
    try {
        loginModule = clazz.newInstance();
    } catch (InstantiationException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    }
    // Initialize the LoginModule
    Subject subject = new Subject();
    loginModule.initialize(subject, handler, EMPTY_MAP, options);
    // Try to log in:
    boolean loginSucceeded = false;
    boolean commitSucceeded = false;
    try {
        loginSucceeded = loginModule.login();
        if (loginSucceeded) {
            commitSucceeded = loginModule.commit();
        }
    } catch (LoginException e) {
    // Login or commit failed! No principal for you!
    }
    // If we successfully logged in & committed, return all the principals
    if (loginSucceeded && commitSucceeded) {
        return subject.getPrincipals();
    }
    return NO_PRINCIPALS;
}
Also used : LoginException(javax.security.auth.login.LoginException) AnonymousLoginModule(org.apache.wiki.auth.login.AnonymousLoginModule) LoginModule(javax.security.auth.spi.LoginModule) CookieAuthenticationLoginModule(org.apache.wiki.auth.login.CookieAuthenticationLoginModule) WebContainerLoginModule(org.apache.wiki.auth.login.WebContainerLoginModule) CookieAssertionLoginModule(org.apache.wiki.auth.login.CookieAssertionLoginModule) UserDatabaseLoginModule(org.apache.wiki.auth.login.UserDatabaseLoginModule) Subject(javax.security.auth.Subject)

Example 5 with LoginModule

use of javax.security.auth.spi.LoginModule in project jspwiki by apache.

the class CookieAssertionLoginModuleTest method testLogout.

public final void testLogout() {
    MockHttpServletRequest request = m_engine.newHttpRequest();
    Cookie cookie = new Cookie(CookieAssertionLoginModule.PREFS_COOKIE_NAME, "Bullwinkle");
    request.setCookies(new Cookie[] { cookie });
    try {
        CallbackHandler handler = new WebContainerCallbackHandler(m_engine, request);
        LoginModule module = new CookieAssertionLoginModule();
        module.initialize(m_subject, handler, new HashMap<String, Object>(), new HashMap<String, Object>());
        module.login();
        module.commit();
        Set<Principal> principals = m_subject.getPrincipals();
        Assert.assertEquals(1, principals.size());
        Assert.assertTrue(principals.contains(new WikiPrincipal("Bullwinkle")));
        Assert.assertFalse(principals.contains(Role.ANONYMOUS));
        Assert.assertFalse(principals.contains(Role.ALL));
        module.logout();
        Assert.assertEquals(0, principals.size());
    } catch (LoginException e) {
        System.err.println(e.getMessage());
        Assert.assertTrue(false);
    }
}
Also used : Cookie(javax.servlet.http.Cookie) CallbackHandler(javax.security.auth.callback.CallbackHandler) MockHttpServletRequest(net.sourceforge.stripes.mock.MockHttpServletRequest) LoginModule(javax.security.auth.spi.LoginModule) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) LoginException(javax.security.auth.login.LoginException) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) Principal(java.security.Principal)

Aggregations

LoginModule (javax.security.auth.spi.LoginModule)19 LoginException (javax.security.auth.login.LoginException)12 CallbackHandler (javax.security.auth.callback.CallbackHandler)10 Principal (java.security.Principal)8 Subject (javax.security.auth.Subject)8 WikiPrincipal (org.apache.wiki.auth.WikiPrincipal)8 MockHttpServletRequest (net.sourceforge.stripes.mock.MockHttpServletRequest)4 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Cookie (javax.servlet.http.Cookie)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 ExtensionLoginModule (org.eclipse.equinox.security.auth.module.ExtensionLoginModule)2 SecurityLoggerInfo (com.sun.enterprise.security.SecurityLoggerInfo)1 CERT_REALMNAME (com.sun.enterprise.security.auth.login.LoginContextDriver.CERT_REALMNAME)1 X509CertificateCredential (com.sun.enterprise.security.auth.login.common.X509CertificateCredential)1 OID (com.sun.enterprise.security.auth.realm.certificate.OID)1 AppClientSSL (com.sun.enterprise.security.integration.AppClientSSL)1 SSLUtils (com.sun.enterprise.security.ssl.SSLUtils)1 LocalStringManagerImpl (com.sun.enterprise.util.LocalStringManagerImpl)1 KeyStore (java.security.KeyStore)1