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

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

Introduction

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

Prototype

public void login() throws LoginException 

Source Link

Document

Perform the authentication.

Usage

From source file:org.apache.ws.security.validate.KerberosTokenValidator.java

/**
 * Validate the credential argument. It must contain a non-null BinarySecurityToken. 
 * //from  w w  w .  j  a  v  a  2 s  . c  o  m
 * @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.getBinarySecurityToken() == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential");
    }

    BinarySecurity binarySecurity = credential.getBinarySecurityToken();
    if (!(binarySecurity instanceof KerberosSecurity)) {
        return credential;
    }

    if (log.isDebugEnabled()) {
        try {
            String jaasAuth = System.getProperty("java.security.auth.login.config");
            String krbConf = System.getProperty("java.security.krb5.conf");
            log.debug("KerberosTokenValidator - Using JAAS auth login file: " + jaasAuth);
            log.debug("KerberosTokenValidator - Using KRB conf file: " + krbConf);
        } catch (SecurityException ex) {
            log.debug(ex.getMessage(), ex);
        }
    }

    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(getContextName());
        } else {
            loginContext = new LoginContext(getContextName(), callbackHandler);
        }
        loginContext.login();
    } catch (LoginException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { ex.getMessage() }, ex);
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully authenticated to the TGT");
    }

    byte[] token = binarySecurity.getToken();

    // Get the service name to use - fall back on the principal
    Subject subject = loginContext.getSubject();
    String service = serviceName;
    if (service == null) {
        Set<Principal> principals = subject.getPrincipals();
        if (principals.isEmpty()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                    new Object[] { "No Client principals found after login" });
        }
        service = principals.iterator().next().getName();
    }

    // Validate the ticket
    KerberosServiceAction action = new KerberosServiceAction(token, service);
    Principal principal = (Principal) Subject.doAs(subject, action);
    if (principal == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosTicketValidationError");
    }
    credential.setPrincipal(principal);
    credential.setSubject(subject);

    // Try to extract the session key from the token if a KerberosTokenDecoder implementation is
    // available
    if (kerberosTokenDecoder != null) {
        kerberosTokenDecoder.clear();
        kerberosTokenDecoder.setToken(token);
        kerberosTokenDecoder.setSubject(subject);
        byte[] sessionKey = kerberosTokenDecoder.getSessionKey();
        credential.setSecretKey(sessionKey);
    }

    if (log.isDebugEnabled()) {
        log.debug("Successfully validated a ticket");
    }

    return credential;
}

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

public HttpResponse callRestUrl(final String url, final String userId, HTTP operation) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Calling YarnClient %s %s %s", this.principal, this.keytab, url));
    }/*from w w  w.j a va2 s.com*/
    javax.security.auth.login.Configuration config = new javax.security.auth.login.Configuration() {
        @SuppressWarnings("serial")
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(
                    "com.sun.security.auth.module.Krb5LoginModule",
                    AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
                        {
                            put("useTicketCache", "false");
                            put("useKeyTab", "true");
                            put("keyTab", keytab);
                            // Krb5 in GSS API needs to be refreshed so it does not throw the error
                            // Specified version of key is not available
                            put("refreshKrb5Config", "true");
                            put("principal", principal);
                            put("storeKey", "true");
                            put("doNotPrompt", "true");
                            put("isInitiator", "true");
                            if (LOGGER.isDebugEnabled()) {
                                put("debug", "true");
                            }
                        }
                    }) };
        }
    };

    Set<Principal> principals = new HashSet<Principal>(1);
    principals.add(new KerberosPrincipal(userId));
    Subject sub = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    try {
        // Authentication module: Krb5Login
        LoginContext loginContext = new LoginContext("Krb5Login", sub, null, config);
        loginContext.login();
        Subject serviceSubject = loginContext.getSubject();
        return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
            HttpResponse httpResponse = null;

            @Override
            public HttpResponse run() {
                try {
                    HttpUriRequest request = null;
                    switch (operation) {
                    case DELETE:
                        request = new HttpDelete(url);
                        break;
                    case POST:
                        request = new HttpPost(url);
                        break;
                    default:
                        request = new HttpGet(url);
                        break;
                    }

                    HttpClient spengoClient = buildSpengoHttpClient();
                    httpResponse = spengoClient.execute(request);
                    return httpResponse;
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
                return httpResponse;
            }
        });
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}

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 {/*  w  ww  . j  a  v  a  2s. 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.getobjects.appserver.publisher.GoSimpleNamePasswordLogin.java

/**
 * Called by userInContext() of GoHTTPAuthenticator, or by the 'other' login()
 * method which can be triggered by custom login panels.
 * //from w w w  .  j  a  v a2  s  . c  o m
 * @param _login - username
 * @param _pwd   - password
 * @param _realm - realm
 * @return returns a logged-in LoginContext, or null if login failed
 */
public LoginContext loginInJaas(String _login, String _pwd, String _realm) {
    if (_login == null /* not allowed in JAAS */) {
        log.warn("attempt to login with a 'null' login name");
        return null;
    }

    LoginContext lc = null;
    try {
        lc = new LoginContext(_realm != null ? _realm : "Go", null, /* subject (create one if missing) */
                new NamePasswordCallbackHandler(_login, _pwd), this.jaasCfg);
    } catch (LoginException le) {
        log.error("could not create JAAS LoginContext", le);
    }

    if (lc != null) {
        try {
            lc.login();
        } catch (LoginException le) {
            if (log.isInfoEnabled())
                log.info("login failed: " + _login, le);
            lc = null;
        }
    }

    return lc;
}

From source file:org.getobjects.appserver.publisher.JoSimpleNamePasswordLogin.java

/**
 * Called by userInContext() of JoHTTPAuthenticator, or by the 'other' login()
 * method which can be triggered by custom login panels.
 * // ww  w .  j  av a  2s . c o m
 * @param _login - username
 * @param _pwd   - password
 * @param _realm - realm
 * @return returns a logged-in LoginContext, or null if login failed
 */
public LoginContext loginInJaas(String _login, String _pwd, String _realm) {
    if (_login == null /* not allowed in JAAS */) {
        log.warn("attempt to login with a 'null' login name");
        return null;
    }

    LoginContext lc = null;
    try {
        lc = new LoginContext(_realm != null ? _realm : "JOPE", null, /* subject (create one if missing) */
                new NamePasswordCallbackHandler(_login, _pwd), this.jaasCfg);
    } catch (LoginException le) {
        log.error("could not create JAAS LoginContext", le);
    }

    if (lc != null) {
        try {
            lc.login();
        } catch (LoginException le) {
            if (log.isInfoEnabled())
                log.info("login failed: " + _login, le);
            lc = null;
        }
    }

    return lc;
}

From source file:org.jboss.as.test.integration.ejb.container.interceptor.security.api.SwitchIdentityTestCase.java

/**
 * Perform the tests using the ClientLoginModule and LoginContext API to set the desired Principal.
 *//*from  w  w w  .j  ava  2  s  . c  o  m*/
private void callUsingClientLoginModul(String userName, boolean hasRole1, boolean hasRole2) throws Exception {
    LoginContext loginContext = null;
    try {
        loginContext = new LoginContext("foo", new Subject(),
                new UsernamePasswordHandler(userName, new char[0]), CLIENT_LOGIN_CONFIG);
        loginContext.login();

        // register the client side interceptor
        final Registration clientInterceptorHandler = EJBClientContext.requireCurrent()
                .registerInterceptor(112567, new ClientSecurityInterceptor());

        final Manage targetBean = EJBUtil.lookupEJB(TargetBean.class, Manage.class);
        final Manage bridgeBean = EJBUtil.lookupEJB(BridgeBean.class, Manage.class);

        //test direct access
        testMethodAccess(targetBean, ManageMethodEnum.ALLROLES, true);
        testMethodAccess(targetBean, ManageMethodEnum.ROLE1, hasRole1);
        testMethodAccess(targetBean, ManageMethodEnum.ROLE2, hasRole2);

        //test security context propagation
        testMethodAccess(bridgeBean, ManageMethodEnum.ALLROLES, true);
        testMethodAccess(bridgeBean, ManageMethodEnum.ROLE1, hasRole1);
        testMethodAccess(bridgeBean, ManageMethodEnum.ROLE2, hasRole2);

        clientInterceptorHandler.remove();
    } finally {
        if (loginContext != null) {
            loginContext.logout();
        }
    }
}

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  ww w .  j av  a  2  s.co 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.
 * //from  www .ja  va  2  s.c om
 * @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.josso.agent.http.JaasHttpSSOAgent.java

/**
  * Resolves an authentication request using JAAS infrastructure.
  * //from ww  w . ja v a 2  s.c o  m
  * @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
 *///  ww  w  .  j  a  va2  s .com
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;
}