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:org.apache.ws.security.validate.JAASUsernameTokenValidator.java

/**
 * Validate the credential argument. It must contain a non-null UsernameToken. A 
 * CallbackHandler implementation is also required to be set.
 * Validator// w  ww  .  j a  v  a 2 s  .c o m
 * If the password type is either digest or plaintext, it extracts a password from the 
 * CallbackHandler and then compares the passwords appropriately.
 * 
 * If the password is null it queries a hook to allow the user to validate UsernameTokens
 * of this type. 
 * 
 * @param credential the Credential to be validated
 * @param data the RequestData associated with the request
 * @throws WSSecurityException on a failed validation
 */
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential");
    }

    String user = null;
    String password = null;

    UsernameToken usernameToken = credential.getUsernametoken();

    user = usernameToken.getName();
    String pwType = usernameToken.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + usernameToken.getName());
        log.debug("UsernameToken password type " + pwType);
    }

    if (usernameToken.isHashed()) {
        log.warn("Authentication failed as hashed username token not supported");
        throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
    }

    password = usernameToken.getPassword();

    if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
        log.warn("Password type " + pwType + " not supported");
        throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
    }

    if (!(user != null && user.length() > 0 && password != null && password.length() > 0)) {
        log.warn("User or password empty");
        throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
    }

    try {
        CallbackHandler handler = getCallbackHandler(user, password);
        LoginContext ctx = new LoginContext(getContextName(), handler);
        ctx.login();
        Subject subject = ctx.getSubject();
        credential.setSubject(subject);

    } catch (LoginException ex) {
        log.info("Authentication failed", ex);
        throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, ex);
    }

    return credential;

}

From source file:org.apereo.portal.security.provider.JAASSecurityContext.java

public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;

    if (this.myPrincipal.UID != null && this.myOpaqueCredentials.credentialstring != null) {

        try {//from w  ww .  j av a2  s.  c o m
            // JAAS Stuff

            LoginContext lc = null;

            lc = new LoginContext("uPortal", new JAASInlineCallbackHandler(this.myPrincipal.UID,
                    (new String(this.myOpaqueCredentials.credentialstring)).toCharArray())); // could not come up w/ a better way to do this

            lc.login();
            additionalDescriptor = new JAASSubject(lc.getSubject());

            // the above will throw an exception if authentication does not succeed

            if (log.isInfoEnabled())
                log.info("User " + this.myPrincipal.UID + " is authenticated");
            this.isauth = true;

        } catch (LoginException e) {
            if (log.isInfoEnabled())
                log.info("User " + this.myPrincipal.UID + ": invalid password");
            if (log.isDebugEnabled())
                log.debug("LoginException", e);
        }
    } else {
        log.error("Principal or OpaqueCredentials not initialized prior to authenticate");
    }

    // authenticate all subcontexts.
    super.authenticate();

    return;
}

From source file:org.hyperic.hq.plugin.weblogic.WeblogicAuth.java

public Subject getSubject() throws SecurityException {

    if (this.subject != null) {
        return this.subject;
    }// w  w w.ja v  a 2 s . c  o m

    StopWatch timer = null;

    if (this.loginContext == null) {
        if (log.isDebugEnabled()) {
            timer = new StopWatch();
        }

        try {
            this.loginContext = new LoginContext(LOGIN_MODULE, this);
            this.loginContext.login();
        } catch (LoginException e) {
            //e.printStackTrace();
            this.loginContext = null;
            throw new SecurityException(e.getMessage());
        }
    }

    this.subject = this.loginContext.getSubject();

    if (timer != null) {
        log.debug(this.url + " login took: " + timer);
    }

    if (this.subject == null) {
        throw new SecurityException("Authentication failed: reason unknown.");
    }

    return this.subject;
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Creates login context for given {@link Krb5LoginConfiguration} and credentials and calls the {@link LoginContext#login()}
 * method on it. This method contains workaround for IBM JDK issue described in bugzilla <a
 * href="https://bugzilla.redhat.com/show_bug.cgi?id=1206177">https://bugzilla.redhat.com/show_bug.cgi?id=1206177</a>.
 *
 * @param krb5Configuration//from   w  w w . j  a  v  a  2  s .c o  m
 * @param user
 * @param pass
 * @return
 * @throws LoginException
 */
public static LoginContext loginWithKerberos(final Krb5LoginConfiguration krb5Configuration, final String user,
        final String pass) throws LoginException {
    LoginContext lc = new LoginContext(krb5Configuration.getName(), new UsernamePasswordHandler(user, pass));
    if (IBM_JDK) {
        // workaround for IBM JDK on RHEL5 issue described in https://bugzilla.redhat.com/show_bug.cgi?id=1206177
        // The first negotiation always fail, so let's do a dummy login/logout round.
        lc.login();
        lc.logout();
        lc = new LoginContext(krb5Configuration.getName(), new UsernamePasswordHandler(user, pass));
    }
    lc.login();
    return lc;
}

From source file:org.jboss.test.kerberos.gss.GSSTestServer.java

/**
 * Authenticates this server in Kerberos KDC.
 * /* w  ww.  j av  a2s. c  o m*/
 * @throws LoginException
 * @throws PrivilegedActionException
 */
private void start() throws LoginException, PrivilegedActionException {
    System.out.println("Starting GSSTestServer - login");
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            final Map<String, Object> options = new HashMap<String, Object>();
            options.put("refreshKrb5Config", "true");
            options.put("storeKey", "true");
            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    });
    // 1. Authenticate to Kerberos.
    final LoginContext lc = new LoginContext("foo",
            new UsernamePasswordHandler(PRINCIPAL, PASSWORD != null ? PASSWORD.toCharArray() : null));
    lc.login();
    System.out.println("Authentication succeed");
    // 2. Perform the work as authenticated Subject.
    final String finishMsg = Subject.doAs(lc.getSubject(), new ServerAction());
    System.out.println("Server stopped with result: " + (finishMsg == null ? "OK" : finishMsg));
    lc.logout();

}

From source file:org.jboss.test.security.test.CustomPrincipalPropagationUnitTestCase.java

private void login(String username, char[] password) throws Exception {
    if (loggedIn)
        return;/*from   w ww. j a va  2 s  .  c o  m*/

    lc = null;
    String confName = System.getProperty("conf.name", "jaas-test");
    AppCallbackHandler handler = new AppCallbackHandler(username, password);
    log.debug("Creating LoginContext(" + confName + ")");
    lc = new LoginContext(confName, handler);
    lc.login();
    log.debug("Created LoginContext, subject=" + lc.getSubject());
    loggedIn = true;
}

From source file:org.josso.agent.http.JaasHttpSSOAgent.java

/**
  * Resolves an authentication request using JAAS infrastructure.
  * /*w  w  w. j av a  2  s.c om*/
  * @param request containing the SSO Session id.
  * @return null if no principal can be authenticated using the received SSO Session Id
  */
protected Principal authenticate(SSOAgentRequest request) {

    String ssoSessionId = request.getSessionId();
    if (log.isDebugEnabled()) {
        log.debug("Attempting SSO Session authentication by " + request.getRequester() + ":" + ssoSessionId);
    }

    try {

        // Look up for JAAS security context configured for JOSSO.
        if (log.isDebugEnabled())
            log.debug("Creating callback handler for " + request.getRequester() + "/" + ssoSessionId);

        CallbackHandler ch = new SSOGatewayHandler(request.getRequester(), ssoSessionId, request.getNodeId());
        LoginContext lc = new LoginContext("josso", ch);

        // Perform login
        lc.login();

        if (log.isDebugEnabled()) {
            log.debug("SSO Session authenticated " + ssoSessionId);
        }

        // Lookup for specific principal
        if (log.isDebugEnabled()) {
            log.debug("Creating new JOSSO Security Context instance");
        }

        Subject s = lc.getSubject();

        JOSSOSecurityContext ctx = new JOSSOSecurityContext(s);
        return ctx.getCurrentPrincipal();

    } catch (LoginException e) {
        log.error(e.getMessage());
    }

    return null;
}

From source file:org.josso.servlet.agent.GenericServletSSOAgent.java

/**
 * Resolves an authentication request using JAAS infrastructure.
 * @param request containing the SSO Session id.
 * @return null if no principal can be authenticated using the received SSO Session Id
 *//*  w w  w  . j av  a2 s  . c o m*/
protected Principal authenticate(SSOAgentRequest request) {

    String ssoSessionId = request.getSessionId();
    if (log.isDebugEnabled())
        log.debug("Attempting SSO Session authentication : " + ssoSessionId);

    try {

        // Look up for JAAS security context configured for JOSSO.
        CallbackHandler ch = new SSOGatewayHandler(request.getRequester(), ssoSessionId);
        LoginContext lc = new LoginContext("josso", ch);

        // Perform login
        lc.login();

        if (log.isDebugEnabled())
            log.debug("SSO Session authenticated " + ssoSessionId);

        // Lookup for specific principal

        if (log.isDebugEnabled())
            log.debug("Creating new JOSSO Security Context instance");

        Subject s = lc.getSubject();

        GenericServletSSOAgentRequest r = (GenericServletSSOAgentRequest) request;
        JOSSOSecurityContext ctx = new JOSSOSecurityContext(s);
        r.setSecurityContext(ctx);

        return ctx.getCurrentPrincipal();

    } catch (LoginException e) {
        log.error(e.getMessage());
    }

    return null;
}

From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java

/**
 * Perform JAAS login.// www .  ja v a  2  s . c  om
 *
 * @return the logged-in subject or null if login failed.
 */
protected Subject performJAASLogin() {
    CallbackHandler lch = getLoginCallbackHandler();
    try {
        LoginContext lc;
        try {
            lc = new LoginContext(getLoginContextName(), lch);
        } catch (LoginException le) {
            LOG.error("Cannot create LoginContext.", le);
            return null;
        } catch (SecurityException se) {
            LOG.error("Cannot create LoginContext.", se);
            return null;
        }
        lc.login();
        return lc.getSubject();
    } catch (LoginException le) {
        // le.getCause() is always null, so cannot rely on it.
        // see bug #1019
        if (!(le instanceof FailedLoginException)) {
            String message = le.getMessage();
            if (message.indexOf(':') > 0) {
                String exceptionClassName = message.substring(0, message.indexOf(':'));
                try {
                    if (Throwable.class.isAssignableFrom(Class.forName(exceptionClassName))) {
                        LOG.error("A technical exception occurred on login module.", le);
                    }
                } catch (ClassNotFoundException ignored) {
                    // ignored.
                }
            }
        }
        return null;
    }
}

From source file:org.kalypso.test.bsu.wfs.SingleSignonTest.java

public void testSigngleSignon() throws Exception {
    try {/*w  ww  .j a  v a 2 s.c om*/
        copy(new File("D:/eclipse3.1/tmp/web_FlowsAStestLogin.html"));
        LoginContext loginContext = null;
        System.setProperty("java.security.auth.login.config", "D:/eclipse3.1/tmp/jaasConf.txt");
        // Login-Kontext fr die Konfiguration "Demo" erzeugen
        // loginContext = new LoginContext( "Demo" );
        loginContext = new LoginContext("Demo", new CallbackHandler() {

            public void handle(Callback[] callbacks) {
                for (int i = 0; i < callbacks.length; i++) {
                    Callback callback = callbacks[i];
                    if (callback instanceof NameCallback) {
                        final NameCallback nCall = (NameCallback) callback;
                        System.out.println(nCall.getPrompt());
                        nCall.setName("Flowsad");
                    } else if (callback instanceof PasswordCallback) {
                        final PasswordCallback call = (PasswordCallback) callback;
                        System.out.println(call.getPrompt());
                        call.setPassword(new char[] { ' ', ' ', });
                    } else
                        System.out.println("unknown Callback: " + callback.getClass().getName());
                }
            }

        });
        // Durchfhrung des Logins
        loginContext.login();
        System.out.println("authentication succeeded");

        // Die Principals ermitteln...
        Set principals = loginContext.getSubject().getPrincipals();
        // ...und in einer Iteration ausgeben
        Iterator it = principals.iterator();
        Principal p;
        while (it.hasNext()) {
            p = (Principal) it.next();
            System.out.println(p);
        }
        System.out.println("logging out...");
        copy(new File("D:/eclipse3.1/tmp/web_FlowsAdmitLogin.html"));

        loginContext.logout();
    } catch (Exception e) {
        System.out.println("authentication failed");
        throw e;
    }
}