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:it.cnr.icar.eric.client.xml.registry.ConnectionImpl.java

/**
 * Forces authentication to occur./*from w ww. j a  v  a 2 s .  c o  m*/
 ** Add to JAXR 2.0??
 *
 * @throws JAXRException DOCUMENT ME!
 */
public void authenticate() throws JAXRException {
    // Obtain a LoginContext, needed for authentication. Tell it 
    // to use the LoginModule implementation specified by the 
    // entry named "Sample" in the JAAS login configuration 
    // file and to also use the specified CallbackHandler.
    LoginContext lc = null;

    try {
        loginModuleMgr.createLoginConfigFile();

        String applicationName = loginModuleMgr.getApplicationName();
        handler = loginModuleMgr.getCallbackHandler();

        lc = new LoginContext(applicationName, handler);

        // attempt authentication
        lc.login();

        //Get the authenticated Subject.
        Subject subject = lc.getSubject();
        Set<Object> privateCredentials = subject.getPrivateCredentials();

        //Set credentials on JAXR Connections
        setCredentials(privateCredentials);

        log.info(JAXRResourceBundle.getInstance().getString("message.SetCredentialsOnConnection"));
    } catch (LoginException le) {
        String msg = le.getMessage();

        if ((msg != null) && (!(msg.equalsIgnoreCase("Login cancelled")))) {
            throw new JAXRException(le);
        }
    } catch (SecurityException se) {
        throw new JAXRException(se);
    }
}

From source file:com.example.ManualSpnegoNegotiateServlet.java

/**
 * Use of Kerberos is wrapped in an HTTP auth-scheme of "Negotiate" [RFC 4559].
 *
 * The auth-params exchanged use data formats defined for use with the GSS-API [RFC 2743]. In particular, they follow the formats set for the SPNEGO [RFC 4178] and
 * Kerberos [RFC 4121] mechanisms for GSSAPI. The "Negotiate" auth-scheme calls for the use of SPNEGO GSSAPI tokens that the specific mechanism type specifies.
 *
 * The current implementation of this protocol is limited to the use of SPNEGO with the Kerberos protocol.
 *
 * @param request//from www.j a  v  a 2 s  .c  o  m
 * @param response
 * @throws ServletException
 *
 * @return true upon successful authentication, false otherwise
 */
protected boolean attemptNegotiation(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, UnsupportedEncodingException, IOException {
    log.debug("Attempting negotiation.");

    String header = request.getHeader("Authorization");

    /**
     * Guard clause to check for Negotiate header.
     *
     * If the server receives a request for an access-protected object, and if an acceptable Authorization header has not been sent, the server responds with a "401
     * Unauthorized" status code, and a "WWW-Authenticate:" header as per the framework described in [RFC 2616]. The initial WWW-Authenticate header will not carry
     * any gssapi-data.
     */
    if (header == null || header.length() < 10 || !header.startsWith("Negotiate ")) {
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        log.debug("Proper authorization header not found, returning challenge.");
        return false;
    }

    /**
     * A client may initiate a connection to the server with an "Authorization" header containing the initial token for the server. This form will bypass the initial
     * 401 error from the server when the client knows that the server will accept the Negotiate HTTP authentication type.
     */
    log.debug("Authorization header found, continuing negotiation.");

    /**
     * The data following the word Negotiate is the GSS-API data to process.
     */
    byte gssapiData[] = Base64.decode(header.substring(10));

    log.debug("GSS API data: " + Arrays.toString(gssapiData));

    /**
     * Guard clause to check for the unsupported NTLM authentication mechanism.
     */
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return false;
    }

    /**
     * The server attempts to establish a security context. Establishment may result in tokens that the server must return to the client. Tokens are BASE-64 encoded
     * GSS-API data.
     */
    GSSContext gssContext = null;
    LoginContext loginContext = null;
    String outToken = null;

    try {
        final String domainUsername = "Zeus";
        final String domainUserPassword = "Z3usP@55";
        final CallbackHandler handler = SpnegoProvider.getUsernamePasswordHandler(domainUsername,
                domainUserPassword);

        loginContext = new LoginContext("spnego-server", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); // for spnego answers
        Oid kerbv5Oid = new Oid("1.2.840.113554.1.2.2"); // for chromium (they send a kerbv5 token instead of spnego)
        final Oid[] oids = new Oid[] { spnegoOid, kerbv5Oid };

        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, oids,
                        GSSCredential.ACCEPT_ONLY);
            }
        };

        GSSCredential serverCreds = Subject.doAs(subject, action);

        log.debug("Mechs: " + Arrays.toString(serverCreds.getMechs()));

        gssContext = manager.createContext(serverCreds);

        log.debug("Context created. " + gssContext);

        byte tokenBytes[] = gssContext.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = Base64.encode(tokenBytes);
    } catch (PrivilegedActionException ex) {
        log.error("", ex);
    } catch (LoginException ex) {
        log.error("", ex);
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the "context initiator." In the case of the Kerberos mechanism, the context initiator is
     * the Kerberos principal of the client. Additionally, the client may be delegating credentials.
     */
    if (gssContext != null && gssContext.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = gssContext.getSrcName();
            KerberosPrincipal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);
            response.getWriter().println("Hello, " + clientPrincipal);

            /**
             * Retrieve LogonInfo (for example, GroupSIDs) from the PAC Authorization Data
             * from a Kerberos Ticket that was issued by Active Directory.
             */
            byte[] kerberosTokenData = gssapiData;
            try {
                SpnegoToken token = SpnegoToken.parse(gssapiData);
                kerberosTokenData = token.getMechanismToken();
            } catch (DecodingException dex) {
                // Chromium bug: sends a Kerberos response instead of an spnego response with a Kerberos mechanism
            } catch (Exception ex) {
                log.error("", ex);
            }

            try {
                Object[] keyObjs = IteratorUtils
                        .toArray(loginContext.getSubject().getPrivateCredentials(KerberosKey.class).iterator());
                KerberosKey[] keys = new KerberosKey[keyObjs.length];
                System.arraycopy(keyObjs, 0, keys, 0, keyObjs.length);

                KerberosToken token = new KerberosToken(kerberosTokenData, keys);
                log.info("Authorizations: ");
                for (KerberosAuthData authData : token.getTicket().getEncData().getUserAuthorizations()) {
                    if (authData instanceof KerberosPacAuthData) {
                        PacSid[] groupSIDs = ((KerberosPacAuthData) authData).getPac().getLogonInfo()
                                .getGroupSids();
                        log.info("GroupSids: " + Arrays.toString(groupSIDs));
                        response.getWriter().println("Found group SIDs: " + Arrays.toString(groupSIDs));
                    } else {
                        log.info("AuthData without PAC: " + authData.toString());
                    }
                }
            } catch (Exception ex) {
                log.error("", ex);
            }

            if (gssContext.getCredDelegState()) {
                GSSCredential delegateCredential = gssContext.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            /**
             * A status code 200 status response can also carry a "WWW-Authenticate" response header containing the final leg of an authentication. In this case, the
             * gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                response.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                log.debug("Negotiation completed.");
                return true;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            response.addHeader("Client-Warning", gsse.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an authentication error. If a 401 containing a "WWW-Authenticate" header with "Negotiate" and
         * gssapi-data is returned from the server, it is a continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return false;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");

    return true;
}

From source file:org.apache.brooklyn.security.StockSecurityProviderTest.java

private LoginContext doLogin(final String username, final String password) throws LoginException {
    assertRealmRegisteredEventually(WEBCONSOLE_REALM);
    LoginContext lc = new LoginContext(WEBCONSOLE_REALM, new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                Callback callback = callbacks[i];
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(password.toCharArray());
                } else if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(username);
                }/*from w  w  w  .  j av a2 s . c om*/
            }
        }
    });
    lc.login();
    return lc;
}

From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java

public Subject doAuthenticate(final String username, final String password) {
    try {/*from w  w w.j  ava 2s .com*/
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof NameCallback) {
                        ((NameCallback) callbacks[i]).setName(username);
                    } else if (callbacks[i] instanceof PasswordCallback) {
                        ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        loginContext.login();
        if (role != null && role.length() > 0) {
            String clazz = "org.apache.karaf.jaas.boot.principal.RolePrincipal";
            String name = role;
            int idx = role.indexOf(':');
            if (idx > 0) {
                clazz = role.substring(0, idx);
                name = role.substring(idx + 1);
            }
            boolean found = false;
            for (Principal p : subject.getPrincipals()) {
                if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new FailedLoginException("User does not have the required role " + role);
            }
        }
        return subject;
    } catch (AccountException e) {
        LOGGER.warn("Account failure", e);
        return null;
    } catch (LoginException e) {
        LOGGER.debug("Login failed", e);
        return null;
    } catch (GeneralSecurityException e) {
        LOGGER.error("General Security Exception", e);
        return null;
    }
}

From source file:org.wso2.carbon.mediator.kerberos.KerberosMediator.java

/**
 * Create GSSCredential for the user.//  w w w.jav a 2 s  . c  o m
 *
 * @param callbackHandler callback handler.
 * @param mechanismOId    Oid for the mechanism.
 * @return GSSCredential.
 * @throws LoginException
 * @throws PrivilegedActionException
 * @throws GSSException
 */
private GSSCredential createClientCredentials(CallbackHandler callbackHandler, final Oid mechanismOId)
        throws LoginException, PrivilegedActionException, GSSException {

    LoginContext loginContext;
    String loginName;
    if (StringUtils.isNotEmpty(getLoginContextName())) {
        loginName = getLoginContextName();
    } else {
        loginName = "com.sun.security.auth.module.Krb5LoginModule";
    }
    if (callbackHandler != null) {
        loginContext = new LoginContext(loginName, callbackHandler);
    } else {
        loginContext = new LoginContext(loginName);
    }
    loginContext.login();
    if (log.isDebugEnabled()) {
        log.debug("Pre-authentication successful for with Kerberos Server.");
    }

    // Create client credentials from pre authentication with the AD
    final GSSName clientName = gssManager.createName(clientPrincipalValue, GSSName.NT_USER_NAME);
    final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
        public GSSCredential run() throws GSSException {

            return gssManager.createCredential(clientName.canonicalize(mechanismOId),
                    GSSCredential.DEFAULT_LIFETIME, mechanismOId, GSSCredential.INITIATE_ONLY);
        }
    };

    if (log.isDebugEnabled()) {
        Set<Principal> principals = loginContext.getSubject().getPrincipals();
        String principalName = null;
        if (principals != null) {
            principalName = principals.toString();
        }
        log.debug("Creating gss credentials as principal : " + principalName);
    }
    return Subject.doAs(loginContext.getSubject(), action);
}

From source file:com.salesmanager.core.module.impl.application.logon.CustomerJAASLogonImpl.java

private boolean isValidLogin(HttpServletRequest req, String username, String password, int merchantId) {
    LoginContext context = null;
    try {//w  ww .j av a2 s. co m

        // 1) using jaas.conf
        // context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME,new
        // CustomerLoginCallBackHandler(username,password));

        // 2) programaticaly created jaas.conf equivalent
        SalesManagerJAASConfiguration jaasc = new SalesManagerJAASConfiguration(
                "com.salesmanager.core.module.impl.application.logon.JAASSecurityCustomerLoginModule");
        context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME, null,
                new CustomerLoginCallBackHandler(username, password, merchantId), jaasc);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to Create Login Context, configuration file may be missing", e);
        /**
         * needs a jaas.conf file in the startup script Logon {
         * com.salesmanager.core.module.impl.application.logon.
         * JAASSecurityCustomerLoginModule required; }; and this parameter
         * -Djava.security.auth.login.config=jaas.conf
         */
    }
    if (context != null) {
        try {
            context.login();

            Subject s = context.getSubject();

            if (s != null) {
                Set principals = s.getPrincipals();
            }

            // Create a principal
            UserPrincipal principal = new UserPrincipal(username);

            HttpSession session = req.getSession();
            session.setAttribute("PRINCIPAL", principal);
            session.setAttribute("LOGINCONTEXT", context);

            return true;
        } catch (LoginException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

private Subject fetchSubjectFromLoginModule(String jaasContextName, Subject subject,
        Krb5LoginConfig loginConfig) throws LoginException {
    debug("Try to create a context LM for jassname={0}, subject={1}, config={2}", jaasContextName, subject,
            loginConfig);//from w w w. j  a  v a  2  s .  c om
    final LoginContext lc = new LoginContext(jaasContextName, subject, null, loginConfig);
    lc.login();
    return lc.getSubject();
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.KerberosTokenGenerator.java

private void login(final NTUser userName, final String password) throws LoginException {
    this.subject = new Subject();
    LoginContext login;
    login = new LoginContext("", subject, new CallbackHandler() {

        @Override//ww  w. j av a 2 s.co  m
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    //We may need some more complete mapping between AD user domain and Kerberos realms  
                    String kerbUserSPN = userName.getUserName();
                    if (StringUtils.isNotBlank(userName.getDomain())) {
                        kerbUserSPN += "@" + userName.getDomain().toUpperCase();
                    }

                    log.debug("Kerberos login name: " + kerbUserSPN);
                    ((NameCallback) callback).setName(kerbUserSPN);
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword(password.toCharArray());
                }
            }
        }
    }, new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> config = new HashMap<String, String>();
            config.put("useTicketCache", "false");

            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, config) };
        }
    });
    login.login();

}

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

private byte[] prepareKerberosLogin() {
    try {//from  w w w  .j  a va  2s. c  o m
        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);
    }
}