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

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

Introduction

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

Prototype

public Subject getSubject() 

Source Link

Document

Return the authenticated Subject.

Usage

From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithKerberos.java

@Test
public void testPingWithUnauthorizedUser() throws Exception {
    // create an unauthorized User with Kerberos
    String userPrinciple = "user/" + SERVER_HOST;
    String userKerberosName = userPrinciple + "@" + REALM;
    Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)),
            new HashSet<Object>(), new HashSet<Object>());
    File userKeytab = new File(kdcWorkDir, "user.keytab");
    kdc.createPrincipal(userKeytab, userPrinciple);
    LoginContext userLoginContext = new LoginContext("", userSubject, null,
            KerberosConfiguration.createClientConfig(userKerberosName, userKeytab));
    userLoginContext.login();/*from w w w.j  av  a2 s  .  com*/
    Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/ping");
            try {
                new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url,
                        new AuthenticatedURL.Token());
                fail("Here should fail.");
            } catch (AuthenticationException e) {
                String expectedError = "status code: 403";
                if (!e.getMessage().contains(expectedError)) {
                    LOG.error("UnexpectedError: " + e.getMessage(), e);
                    fail("UnexpectedError: " + e.getMessage());
                }
            }
            return null;
        }
    });
}

From source file:org.apache.ws.security.message.token.KerberosSecurity.java

/**
 * Retrieve a service ticket from a KDC using the Kerberos JAAS module, and set it in this
 * BinarySecurityToken./*  w w w. jav a  2s  .  c  om*/
 * @param jaasLoginModuleName the JAAS Login Module name to use
 * @param callbackHandler a CallbackHandler instance to retrieve a password (optional)
 * @param serviceName the desired Kerberized service
 * @throws WSSecurityException
 */
public void retrieveServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler,
        String serviceName) throws WSSecurityException {
    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(jaasLoginModuleName);
        } else {
            loginContext = new LoginContext(jaasLoginModuleName, 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");
    }

    Subject clientSubject = loginContext.getSubject();
    Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    if (clientPrincipals.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { "No Client principals found after login" });
    }
    // Store the TGT
    KerberosTicket tgt = getKerberosTicket(clientSubject, null);

    // Get the service ticket
    KerberosClientAction action = new KerberosClientAction(clientPrincipals.iterator().next(), serviceName);
    byte[] ticket = (byte[]) Subject.doAs(clientSubject, action);
    if (ticket == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosServiceTicketError");
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully retrieved a service ticket");
    }

    // Get the Service Ticket (private credential)
    KerberosTicket serviceTicket = getKerberosTicket(clientSubject, tgt);
    if (serviceTicket != null) {
        secretKey = serviceTicket.getSessionKey();
    }

    setToken(ticket);

    if ("".equals(getValueType())) {
        setValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
    }
}

From source file:org.apache.ws.security.spnego.SpnegoTokenContext.java

/**
 * Retrieve a service ticket from a KDC using the Kerberos JAAS module, and set it in this
 * BinarySecurityToken.//from  ww  w  .j ava 2s. co  m
 * @param jaasLoginModuleName the JAAS Login Module name to use
 * @param callbackHandler a CallbackHandler instance to retrieve a password (optional)
 * @param serviceName the desired Kerberized service
 * @throws WSSecurityException
 */
public void retrieveServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler,
        String serviceName) throws WSSecurityException {
    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(jaasLoginModuleName);
        } else {
            loginContext = new LoginContext(jaasLoginModuleName, 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");
    }

    Subject clientSubject = loginContext.getSubject();
    Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    if (clientPrincipals.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { "No Client principals found after login" });
    }

    // Get the service ticket
    clientAction.setServiceName(serviceName);
    clientAction.setMutualAuth(mutualAuth);
    token = (byte[]) Subject.doAs(clientSubject, clientAction);
    if (token == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosServiceTicketError");
    }

    secContext = clientAction.getContext();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Successfully retrieved a service ticket");
    }

}

From source file:org.apache.ws.security.spnego.SpnegoTokenContext.java

/**
 * Validate a service ticket.//ww w  .  ja v  a2 s  .c om
 * @param jaasLoginModuleName
 * @param callbackHandler
 * @param serviceName
 * @param ticket
 * @throws WSSecurityException
 */
public void validateServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler,
        String serviceName, byte[] ticket) throws WSSecurityException {
    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(jaasLoginModuleName);
        } else {
            loginContext = new LoginContext(jaasLoginModuleName, 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");
    }

    // 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
    serviceAction.setTicket(ticket);
    serviceAction.setServiceName(service);
    token = (byte[]) Subject.doAs(subject, serviceAction);

    secContext = serviceAction.getContext();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Successfully validated a service ticket");
    }

}

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//from   ww  w .  j  a v a 2 s.c om
 * 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.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));
    }// ww  w. jav  a  2  s  . c  om
    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  w  w .j av a 2 s.  co  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.GoHTTPAuthenticator.java

/**
 * Returns a user object for the given HTTP credentials (creds[0] is the
 * login, creds[1] is the password and creds[2] is the optional domain).
 * <p>/*from  w  w  w.j ava  2s  . c  o m*/
 * This method uses JAAS to authenticate the user and stores the JAAS subject
 * in the GoUser object.
 * 
 * @param _ctx   - the context in which the current transaction takes place
 * @param _creds - the credentials extracted from the HTTP request
 * @return an IGoUser object, or null if authentication failed
 */
public IGoUser userInContext(final IGoContext _ctx, final String[] _creds) {
    String lRealm = null;
    if (_creds.length > 2)
        lRealm = _creds[2];
    if (lRealm == null) {
        lRealm = this.realmForSecurityExceptionInContext(null,
                _ctx instanceof WOContext ? (WOContext) _ctx : null);
    }
    if (lRealm == null)
        lRealm = defaultRealm;

    final String cacheKey = _creds[0] + "\n" + _creds[1] + "\n" + lRealm;

    LoginContext lc = null;
    if ((lc = this.basicAuthContextCache.get(cacheKey)) == null) {
        /* setup context */

        if (this.login != null)
            lc = this.login.loginInJaas(_creds[0], _creds[1], lRealm);
    }

    /* check whether login failed and return anonymous */

    if (lc == null || lc.getSubject() == null) {
        /* Note: We do not distinguish between anonymous and failed logins. The
         *       application needs *some* user object.
         *       The other option would be to create some "failed" login user
         *       which has the anonymous but not the authenticated role.
         */
        if (log.isInfoEnabled())
            log.info("did not authenticate user: " + _creds[0]);
        return this.anonymousUserInContext(_ctx);
    }

    /* cache valid context */
    this.basicAuthContextCache.put(cacheKey, lc);

    return this.userObjectForValidatedCredentials(_creds[0], _creds, lc, _ctx);
}

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

/**
 * Returns a user object for the given HTTP credentials (creds[0] is the
 * login, creds[1] is the password and creds[2] is the optional domain).
 * <p>/*from   w w  w .  ja  v  a 2  s .c o  m*/
 * This method uses JAAS to authenticate the user and stores the JAAS subject
 * in the JoUser object.
 * 
 * @param _ctx   - the context in which the current transaction takes place
 * @param _creds - the credentials extracted from the HTTP request
 * @return an IJoUser object, or null if authentication failed
 */
public IJoUser userInContext(final IJoContext _context, final String[] creds) {
    String lRealm = null;
    if (creds.length > 2)
        lRealm = creds[2];
    if (lRealm == null) {
        lRealm = this.realmForSecurityExceptionInContext(null,
                _context instanceof WOContext ? (WOContext) _context : null);
    }
    if (lRealm == null)
        lRealm = defaultRealm;

    String cacheKey = creds[0] + "\n" + creds[1] + "\n" + lRealm;

    LoginContext lc = null;
    if ((lc = this.basicAuthContextCache.get(cacheKey)) == null) {
        /* setup context */

        if (this.login != null)
            lc = this.login.loginInJaas(creds[0], creds[1], lRealm);
    }

    /* check whether login failed and return anonymous */

    if (lc == null || lc.getSubject() == null) {
        /* Note: We do not distinguish between anonymous and failed logins. The
         *       application needs *some* user object.
         *       The other option would be to create some "failed" login user
         *       which has the anonymous but not the authenticated role.
         */
        if (log.isInfoEnabled())
            log.info("did not authenticate user: " + creds[0]);
        return this.anonymousUserInContext(_context);
    }

    /* cache valid context */
    this.basicAuthContextCache.put(cacheKey, lc);

    return this.userObjectForValidatedCredentials(creds[0], creds, lc, _context);
}