Example usage for javax.security.auth.login LoginContext LoginContext

List of usage examples for javax.security.auth.login LoginContext LoginContext

Introduction

In this page you can find the example usage for javax.security.auth.login LoginContext LoginContext.

Prototype

public LoginContext(String name, CallbackHandler callbackHandler) throws LoginException 

Source Link

Document

Instantiate a new LoginContext object with a name and a CallbackHandler object.

Usage

From source file:de.dal33t.powerfolder.clientserver.ServerClient.java

private byte[] prepareKerberosLogin() {
    try {/*from w w  w.  ja v a2s . c om*/
        Path outputFile = Controller.getTempFilesLocation().resolve("login.conf");

        if (Files.notExists(outputFile)) {
            InputStream configFile = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("kerberos/login.conf");
            PathUtils.copyFromStreamToFile(configFile, outputFile);
        }

        System.setProperty("java.security.auth.login.config", outputFile.toAbsolutePath().toString());

        System.setProperty("java.security.krb5.realm",
                ConfigurationEntry.KERBEROS_SSO_REALM.getValue(getController()));
        String kdc = ConfigurationEntry.KERBEROS_SSO_KDC.getValue(getController());
        System.setProperty("java.security.krb5.kdc", kdc);

        LoginContext lc = new LoginContext("SignedOnUserLoginContext", new TextCallbackHandler());
        lc.login();
        Subject clientSubject = lc.getSubject();

        username = clientSubject.getPrincipals().iterator().next().getName();
        return Subject.doAs(clientSubject, new ServiceTicketGenerator());
    } catch (Exception e) {
        logWarning("Unable to login: " + e);
        return null;
    } finally {
        loggingIn.set(false);
    }
}

From source file:nl.nn.adapterframework.util.CredentialFactory.java

/** 
 * return a loginContext, obtained by logging in using the obtained credentials
 *///  w  w  w . j  av  a 2s .c o m
public LoginContext getLoginContext() throws LoginException {
    String loginConfig = "ClientContainer";
    getCredentialsFromAlias();
    log.debug("logging in using context[" + loginConfig + "]");
    LoginContext lc = new LoginContext(loginConfig, new loginCallbackHandler());
    lc.login();
    return lc;
}

From source file:org.acegisecurity.providers.jaas.JaasAuthenticationProvider.java

/**
 * Attempts to login the user given the Authentication objects principal and credential
 *
 * @param auth The Authentication object to be authenticated.
 *
 * @return The authenticated Authentication object, with it's grantedAuthorities set.
 *
 * @throws AuthenticationException This implementation does not handle 'locked' or 'disabled' accounts. This method
 *         only throws a AuthenticationServiceException, with the message of the LoginException that will be
 *         thrown, should the loginContext.login() method fail.
 *//*from  w  w  w  .ja va  2s .  co m*/
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (auth instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;

        try {
            //Create the LoginContext object, and pass our InternallCallbackHandler
            LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth));

            //Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
            loginContext.login();

            //create a set to hold the authorities, and add any that have already been applied.
            Set authorities = new HashSet();

            if (request.getAuthorities() != null) {
                authorities.addAll(Arrays.asList(request.getAuthorities()));
            }

            //get the subject principals and pass them to each of the AuthorityGranters
            Set principals = loginContext.getSubject().getPrincipals();

            for (Iterator iterator = principals.iterator(); iterator.hasNext();) {
                Principal principal = (Principal) iterator.next();

                for (int i = 0; i < authorityGranters.length; i++) {
                    AuthorityGranter granter = authorityGranters[i];
                    Set roles = granter.grant(principal);

                    //If the granter doesn't wish to grant any authorities, it should return null.
                    if ((roles != null) && !roles.isEmpty()) {
                        for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();) {
                            String role = roleIterator.next().toString();
                            authorities.add(new JaasGrantedAuthority(role, principal));
                        }
                    }
                }
            }

            //Convert the authorities set back to an array and apply it to the token.
            JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
                    request.getCredentials(),
                    (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]),
                    loginContext);

            //Publish the success event
            publishSuccessEvent(result);

            //we're done, return the token.
            return result;
        } catch (LoginException loginException) {
            AcegiSecurityException ase = loginExceptionResolver.resolveException(loginException);

            publishFailureEvent(request, ase);
            throw ase;
        }
    }

    return null;
}

From source file:org.alfresco.filesys.auth.cifs.EnterpriseCifsAuthenticator.java

/**
 * Initialize the authenticator (after properties have been set)
 * //from   ww w.ja  va2 s . c o  m
 * @exception InvalidConfigurationException
 */
@Override
public void initialize() throws InvalidConfigurationException {
    super.initialize();

    // Check if Java API Kerberos debug output should be enabled

    if (this.kerberosDebug) {
        // Enable Kerberos API debug output

        System.setProperty("sun.security.jgss.debug", "true");
        System.setProperty("sun.security.krb5.debug", "true");
    }

    // Check if Kerberos is enabled
    if (m_krbRealm != null && m_krbRealm.length() > 0) {

        // Get the CIFS service account password
        if (m_password == null || m_password.length() == 0) {
            throw new InvalidConfigurationException("CIFS service account password not specified");
        }

        // Get the login configuration entry name
        if (m_loginEntryName == null || m_loginEntryName.length() == 0) {
            throw new InvalidConfigurationException("Invalid login entry specified");
        }

        // Create a login context for the CIFS server service

        try {
            // Login the CIFS server service

            m_loginContext = new LoginContext(m_loginEntryName, this);
            m_loginContext.login();
        } catch (LoginException ex) {
            // Debug

            if (logger.isErrorEnabled()) {
                logger.error("CIFS Kerberos authenticator error", ex);
            }

            throw new InvalidConfigurationException("Failed to login CIFS server service");
        }

        // Get the CIFS service account name from the subject

        Subject subj = m_loginContext.getSubject();
        Principal princ = subj.getPrincipals().iterator().next();

        m_accountName = princ.getName();

        if (logger.isDebugEnabled()) {
            logger.debug("Logged on using principal " + m_accountName);
        }

        // Create the Oid list for the SPNEGO NegTokenInit, include NTLMSSP for fallback

        m_mechTypes = new Vector<Oid>();

        // DEBUG

        if (logger.isDebugEnabled()) {
            logger.debug("Enabling mechTypes :-Kerberos5 MS-Kerberos5");
        }

        // Always enable Kerberos

        m_mechTypes.add(OID.KERBEROS5);
        m_mechTypes.add(OID.MSKERBEROS5);

        if (!disableNTLM) {
            m_mechTypes.add(OID.NTLMSSP);

            // DEBUG

            if (logger.isDebugEnabled()) {
                logger.debug(" Enabling NTLMSSP");
            }
        }

        // Indicate that SPNEGO security blobs are being used

        m_useRawNTLMSSP = false;
    }
    // Check if raw NTLMSSP or SPNEGO/NTLMSSP should be used
    else if (!m_useRawNTLMSSP) {
        // SPNEGO security blobs are being used

        // Create the Oid list for the SPNEGO NegTokenInit

        m_mechTypes = new Vector<Oid>();

        m_mechTypes.add(OID.NTLMSSP);

    } else {
        // Use raw NTLMSSP security blobs
    }

    // Make sure that either Kerberos support is enabled and/or the authentication component
    // supports MD4 hashed passwords

    if (!isKerberosEnabled() && (!(getAuthenticationComponent() instanceof NLTMAuthenticator)
            || getNTLMAuthenticator().getNTLMMode() != NTLMMode.MD4_PROVIDER)) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "No valid CIFS authentication combination available, Either enable Kerberos support or use an SSO-enabled authentication component that supports MD4 hashed passwords");
        }
        // Throw an exception to stop the CIFS server startup

        throw new AlfrescoRuntimeException(
                "No valid CIFS authentication combination available, Either enable Kerberos support or use an SSO-enabled authentication component that supports MD4 hashed passwords");
    }
}

From source file:org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter.java

@Override
protected void init() throws ServletException {
    super.init();

    if (m_krbRealm == null) {
        throw new ServletException("Kerberos realm not specified");
    }//from  w w  w  .  ja v a  2s .c o  m

    if (m_password == null) {
        throw new ServletException("HTTP service account password not specified");
    }

    if (m_loginEntryName == null) {
        throw new ServletException("Invalid login entry specified");
    }

    // Get the local host name        
    String localName = null;

    try {
        localName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException ex) {
        throw new ServletException("Failed to get local host name");
    }

    // Create a login context for the HTTP server service

    try {
        // Login the HTTP server service

        m_loginContext = new LoginContext(m_loginEntryName, this);
        m_loginContext.login();

        // DEBUG

        if (getLogger().isDebugEnabled())
            getLogger().debug("HTTP Kerberos login successful");
    } catch (LoginException ex) {
        // Debug

        if (getLogger().isErrorEnabled())
            getLogger().error("HTTP Kerberos web filter error", ex);

        throw new ServletException("Failed to login HTTP server service");
    }

    // Get the HTTP service account name from the subject

    Subject subj = m_loginContext.getSubject();
    Principal princ = subj.getPrincipals().iterator().next();

    m_accountName = princ.getName();

    // DEBUG

    if (getLogger().isDebugEnabled())
        getLogger().debug("Logged on using principal " + m_accountName);

    // Create the Oid list for the SPNEGO NegTokenInit, include NTLMSSP for fallback

    Vector<Oid> mechTypes = new Vector<Oid>();

    mechTypes.add(OID.KERBEROS5);
    mechTypes.add(OID.MSKERBEROS5);

    // Build the SPNEGO NegTokenInit blob

    try {
        // Build the mechListMIC principle
        //
        // Note: This field is not as specified

        String mecListMIC = null;

        StringBuilder mic = new StringBuilder();
        mic.append(localName);
        mic.append("$@");
        mic.append(m_krbRealm);

        mecListMIC = mic.toString();

        // Build the SPNEGO NegTokenInit that contains the authentication types that the HTTP server accepts

        NegTokenInit negTokenInit = new NegTokenInit(mechTypes, mecListMIC);

        // Encode the NegTokenInit blob
        negTokenInit.encode();
    } catch (IOException ex) {
        // Debug

        if (getLogger().isErrorEnabled())
            getLogger().error("Error creating SPNEGO NegTokenInit blob", ex);

        throw new ServletException("Failed to create SPNEGO NegTokenInit blob");
    }
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Initialize the filter/*from   w ww  .j  a v a2 s.  com*/
 */
public void init(FilterConfig args) throws ServletException {
    if (logger.isDebugEnabled())
        logger.debug("Initializing the SSOAuthenticationFilter.");

    // get reference to our ServletContext
    this.servletContext = args.getServletContext();

    ApplicationContext context = getApplicationContext();

    this.loginController = (SlingshotLoginController) context.getBean("loginController");

    // retrieve the connector service
    this.connectorService = (ConnectorService) context.getBean("connector.service");

    ConfigService configService = (ConfigService) context.getBean("web.config");

    // Retrieve the remote configuration
    RemoteConfigElement remoteConfig = (RemoteConfigElement) configService.getConfig("Remote")
            .getConfigElement("remote");
    if (remoteConfig == null) {
        logger.error(
                "There is no Remote configuration element. This is required to use SSOAuthenticationFilter.");
        return;
    }

    // get the endpoint id to use
    String endpoint = args.getInitParameter("endpoint");
    if (endpoint == null) {
        logger.error(
                "There is no 'endpoint' id in the SSOAuthenticationFilter init parameters. Cannot initialise filter.");
        return;
    }

    // Get the endpoint descriptor and check if external auth is enabled
    EndpointDescriptor endpointDescriptor = remoteConfig.getEndpointDescriptor(endpoint);
    if (endpointDescriptor == null || !endpointDescriptor.getExternalAuth()) {
        if (logger.isDebugEnabled())
            logger.debug("No External Auth endpoint configured for " + endpoint);
        return;
    }

    try {
        Connector conn = this.connectorService.getConnector(endpoint);

        // Save the endpoint, activating the filter
        this.endpoint = endpoint;
        if (logger.isDebugEnabled())
            logger.debug("Endpoint is " + endpoint);

        // Obtain the userHeader (if configured) from the alfresco connector
        this.userHeader = conn.getConnectorSession()
                .getParameter(SlingshotAlfrescoConnector.CS_PARAM_USER_HEADER);
        String userIdPattern = conn.getConnectorSession()
                .getParameter(SlingshotAlfrescoConnector.CS_PARAM_USER_ID_PATTERN);
        if (userIdPattern != null) {
            this.userIdPattern = Pattern.compile(userIdPattern);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("userHeader is " + userHeader);
            logger.debug("userIdPattern is " + userIdPattern);
        }
    } catch (ConnectorServiceException e) {
        logger.error("Unable to find connector " + endpointDescriptor.getConnectorId() + " for the endpoint "
                + endpoint, e);
    }

    // retrieve the optional kerberos configuration
    KerberosConfigElement krbConfig = (KerberosConfigElement) configService.getConfig("Kerberos")
            .getConfigElement("kerberos");
    if (krbConfig != null) {
        if (logger.isDebugEnabled())
            logger.debug("Found configuration for Kerberos authentication.");
        // Get the Kerberos realm

        String krbRealm = krbConfig.getRealm();
        if (krbRealm != null && krbRealm.length() > 0) {
            if (logger.isDebugEnabled())
                logger.debug("Found Kerberos realm: " + krbRealm);
            // Set the Kerberos realm

            this.krbRealm = krbRealm;
        } else
            throw new ServletException("Kerberos realm not specified");

        // Get the HTTP service account password

        String srvPassword = krbConfig.getPassword();
        if (srvPassword != null && srvPassword.length() > 0) {
            // Set the HTTP service account password

            this.krbPassword = srvPassword;
        } else
            throw new ServletException("HTTP service account password not specified");

        String krbEndpointSPN = krbConfig.getEndpointSPN();
        if (krbEndpointSPN != null && krbEndpointSPN.length() > 0) {
            // Set the Service Principal Name to use on the endpoint
            if (logger.isDebugEnabled())
                logger.debug("The Service Principal Name to use on the endpoint: " + krbEndpointSPN);
            this.krbEndpointSPN = krbEndpointSPN;
        } else
            throw new ServletException("endpoint service principal name not specified");

        // Get the login configuration entry name

        String loginEntry = krbConfig.getLoginEntryName();

        if (loginEntry != null) {
            if (loginEntry.length() > 0) {
                // Set the login configuration entry name to use
                if (logger.isDebugEnabled())
                    logger.debug("The login configuration entry name to use: " + loginEntry);
                jaasLoginEntryName = loginEntry;
            } else
                throw new ServletException("Invalid login entry specified");
        }

        // Get the login stripUserNameSuffix property

        boolean stripUserNameSuffix = krbConfig.getStripUserNameSuffix();

        // Set the login configuration entry name to use
        if (logger.isDebugEnabled())
            logger.debug("The stripUserNameSuffix property is set to: " + stripUserNameSuffix);
        this.stripUserNameSuffix = stripUserNameSuffix;

        // Create a login context for the HTTP server service

        try {
            // Login the HTTP server service

            jaasLoginContext = new LoginContext(jaasLoginEntryName, this);
            jaasLoginContext.login();

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("HTTP Kerberos login successful");
        } catch (LoginException ex) {
            // Debug

            if (logger.isErrorEnabled())
                logger.error("HTTP Kerberos web filter error", ex);

            throw new ServletException("Failed to login HTTP server service");
        }

        // Get the HTTP service account name from the subject

        Subject subj = jaasLoginContext.getSubject();
        Principal princ = subj.getPrincipals().iterator().next();

        krbAccountName = princ.getName();

        // DEBUG

        if (logger.isDebugEnabled())
            logger.debug("Logged on using principal " + krbAccountName);
    }

    if (logger.isInfoEnabled())
        logger.info("SSOAuthenticationFilter initialised.");
}

From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java

@Test
public void testLogin() throws LoginException {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "secret"));

    context.login();//  w  w w .  j  a  va2  s .  c  o m

    Subject subject = context.getSubject();

    assertEquals("Should have three principals", 3, subject.getPrincipals().size());
    assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size());
    assertEquals("Should have two group principals", 2, subject.getPrincipals(RolePrincipal.class).size());

    context.logout();

    assertEquals("Should have zero principals", 0, subject.getPrincipals().size());
}

From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java

@Test
public void testLoginReload() throws Exception {
    File targetPropDir = new File("target/loginReloadTest");
    File usersFile = new File(targetPropDir, "users.properties");
    File rolesFile = new File(targetPropDir, "roles.properties");

    //Set up initial properties
    FileUtils.copyFile(new File(getClass().getResource("/users.properties").toURI()), usersFile);
    FileUtils.copyFile(new File(getClass().getResource("/roles.properties").toURI()), rolesFile);

    LoginContext context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secret"));
    context.login();/*from   ww w  .ja  v a2 s  . com*/
    Subject subject = context.getSubject();

    //test initial principals
    assertEquals("Should have three principals", 3, subject.getPrincipals().size());
    assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size());
    assertEquals("Should have two group principals", 2, subject.getPrincipals(RolePrincipal.class).size());

    context.logout();

    assertEquals("Should have zero principals", 0, subject.getPrincipals().size());

    //Modify the file and test that the properties are reloaded
    Thread.sleep(1000);
    FileUtils.copyFile(new File(getClass().getResource("/usersReload.properties").toURI()), usersFile);
    FileUtils.copyFile(new File(getClass().getResource("/rolesReload.properties").toURI()), rolesFile);
    FileUtils.touch(usersFile);
    FileUtils.touch(rolesFile);

    //Use new password to verify  users file was reloaded
    context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secrets"));
    context.login();
    subject = context.getSubject();

    //Check that the principals changed
    assertEquals("Should have three principals", 2, subject.getPrincipals().size());
    assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size());
    assertEquals("Should have one group principals", 1, subject.getPrincipals(RolePrincipal.class).size());

    context.logout();

    assertEquals("Should have zero principals", 0, subject.getPrincipals().size());
}

From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java

@Test
public void testBadUseridLogin() throws Exception {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("BAD", "secret"));

    try {// ww  w  . j ava2 s .  co  m
        context.login();
        fail("Should have thrown a FailedLoginException");
    } catch (FailedLoginException doNothing) {
    }

}

From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java

@Test
public void testBadPWLogin() throws Exception {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "BAD"));

    try {/*from  w w w  .j  a  v a  2  s  .c o m*/
        context.login();
        fail("Should have thrown a FailedLoginException");
    } catch (FailedLoginException doNothing) {
    }

}