List of usage examples for javax.security.auth.login LoginContext login
public void login() throws LoginException
From source file:org.apache.ranger.services.storm.client.StormClient.java
public static <T> T executeUnderKerberos(String userName, String password, String lookupPrincipal, String lookupKeytab, String nameRules, PrivilegedAction<T> action) throws IOException { final String errMsg = errMessage; class MySecureClientLoginConfiguration extends javax.security.auth.login.Configuration { private String userName; private String password; MySecureClientLoginConfiguration(String aUserName, String password) { this.userName = aUserName; this.password = password; }//from w ww . jav a2s. c o m @Override public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { Map<String, String> kerberosOptions = new HashMap<String, String>(); kerberosOptions.put("principal", this.userName); kerberosOptions.put("debug", "true"); kerberosOptions.put("useKeyTab", "false"); kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName); kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password); kerberosOptions.put("doNotPrompt", "false"); kerberosOptions.put("useFirstPass", "true"); kerberosOptions.put("tryFirstPass", "false"); kerberosOptions.put("storeKey", "true"); kerberosOptions.put("refreshKrb5Config", "true"); AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null; AppConfigurationEntry KERBEROS_PWD_SAVER = null; try { KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, kerberosOptions); KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions); } catch (IllegalArgumentException e) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, e); LOG.error(msgDesc, e); hdpException.generateResponseDataMap(false, BaseClient.getMessage(e), msgDesc + errMsg, null, null); throw hdpException; } LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal")); return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN }; } } ; T ret = null; Subject subject = null; LoginContext loginContext = null; try { Subject loginSubj = null; if (!StringUtils.isEmpty(lookupPrincipal) && !StringUtils.isEmpty(lookupKeytab)) { LOG.info("Init Lookup Login: security enabled, using lookupPrincipal/lookupKeytab"); if (StringUtils.isEmpty(nameRules)) { nameRules = "DEFAULT"; } loginSubj = SecureClientLogin.loginUserFromKeytab(lookupPrincipal, lookupKeytab, nameRules); } else { subject = new Subject(); LOG.debug("executeUnderKerberos():user=" + userName + ",pass="); LOG.debug("executeUnderKerberos():Creating config.."); MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(userName, password); LOG.debug("executeUnderKerberos():Creating Context.."); loginContext = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf); LOG.debug("executeUnderKerberos():Logging in.."); loginContext.login(); LOG.info("Init Login: using username/password"); loginSubj = loginContext.getSubject(); } if (loginSubj != null) { ret = Subject.doAs(loginSubj, action); } } catch (LoginException le) { String msgDesc = "executeUnderKerberos: Login failure using given" + " configuration parameters, username : `" + userName + "`."; HadoopException hdpException = new HadoopException(msgDesc, le); LOG.error(msgDesc, le); hdpException.generateResponseDataMap(false, BaseClient.getMessage(le), msgDesc + errMsg, null, null); throw hdpException; } catch (SecurityException se) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, se); LOG.error(msgDesc, se); hdpException.generateResponseDataMap(false, BaseClient.getMessage(se), msgDesc + errMsg, null, null); throw hdpException; } finally { if (loginContext != null) { if (subject != null) { try { loginContext.logout(); } catch (LoginException e) { throw new IOException("logout failure", e); } } } } return ret; }
From source file:org.apache.ranger.storm.client.StormClient.java
public static <T> T executeUnderKerberos(String userName, String password, PrivilegedAction<T> action) throws IOException { final String errMsg = " You can still save the repository and start creating " + "policies, but you would not be able to use autocomplete for " + "resource names. Check xa_portal.log for more info."; class MySecureClientLoginConfiguration extends javax.security.auth.login.Configuration { private String userName; private String password; MySecureClientLoginConfiguration(String aUserName, String password) { this.userName = aUserName; this.password = password; }/* w w w .j a va 2 s . co m*/ @Override public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { Map<String, String> kerberosOptions = new HashMap<String, String>(); kerberosOptions.put("principal", this.userName); kerberosOptions.put("debug", "true"); kerberosOptions.put("useKeyTab", "false"); kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName); kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password); kerberosOptions.put("doNotPrompt", "false"); kerberosOptions.put("useFirstPass", "true"); kerberosOptions.put("tryFirstPass", "false"); kerberosOptions.put("storeKey", "true"); kerberosOptions.put("refreshKrb5Config", "true"); AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null; AppConfigurationEntry KERBEROS_PWD_SAVER = null; try { KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, kerberosOptions); KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions); } catch (IllegalArgumentException e) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, e); LOG.error(msgDesc, e); hdpException.generateResponseDataMap(false, BaseClient.getMessage(e), msgDesc + errMsg, null, null); throw hdpException; } LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal")); return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN }; } } ; T ret = null; Subject subject = null; LoginContext loginContext = null; try { subject = new Subject(); LOG.debug("executeUnderKerberos():user=" + userName + ",pass="); LOG.debug("executeUnderKerberos():Creating config.."); MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(userName, password); LOG.debug("executeUnderKerberos():Creating Context.."); loginContext = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf); LOG.debug("executeUnderKerberos():Logging in.."); loginContext.login(); Subject loginSubj = loginContext.getSubject(); if (loginSubj != null) { ret = Subject.doAs(loginSubj, action); } } catch (LoginException le) { String msgDesc = "executeUnderKerberos: Login failure using given" + " configuration parameters, username : `" + userName + "`."; HadoopException hdpException = new HadoopException(msgDesc, le); LOG.error(msgDesc, le); hdpException.generateResponseDataMap(false, BaseClient.getMessage(le), msgDesc + errMsg, null, null); throw hdpException; } catch (SecurityException se) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, se); LOG.error(msgDesc, se); hdpException.generateResponseDataMap(false, BaseClient.getMessage(se), msgDesc + errMsg, null, null); throw hdpException; } finally { if (loginContext != null) { if (subject != null) { try { loginContext.logout(); } catch (LoginException e) { throw new IOException("logout failure", e); } } } } return ret; }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithUnauthorizedUser() throws Exception { // create an unauthorized User with Kerberos String userPrinciple = "user/" + SentryServiceIntegrationBase.SERVER_HOST; String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user.keytab"); SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login(); Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override/* ww w .ja v a 2s . co m*/ public Void run() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.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 (!exceptionContainsMessage(e, expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithCaseSensitiveUser() throws Exception { // USER1 is present in the list of users who are allowed to connect to sentry web ui. String userPrinciple = "user1/" + SentryServiceIntegrationBase.SERVER_HOST; String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user1.keytab"); SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login(); Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override//from www .j a va2 s . c o m public Void run() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Login with user1 should fail"); } catch (AuthenticationException e) { String expectedError = "status code: 403"; if (!exceptionContainsMessage(e, expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
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(); Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override/*from w ww.j a va2 s. c om*/ 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.servicemix.nmr.core.security.JaasAuthenticationService.java
public void authenticate(Subject subject, String domain, final String user, final Object credentials) throws GeneralSecurityException { if (LOG.isDebugEnabled()) { LOG.debug("Authenticating '" + user + "' with '" + credentials + "'"); }// w w w .j av a 2 s . c o m LoginContext loginContext = new LoginContext(domain, 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(user); } else if (callbacks[i] instanceof PasswordCallback && credentials instanceof String) { ((PasswordCallback) callbacks[i]).setPassword(((String) credentials).toCharArray()); } else if (callbacks[i] instanceof CertificateCallback && credentials instanceof X509Certificate) { ((CertificateCallback) callbacks[i]).setCertificate((X509Certificate) credentials); } else { throw new UnsupportedCallbackException(callbacks[i]); } } } }); loginContext.login(); }
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.//from w w w .ja v a2 s. c o 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" }); } // 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.// w w w . j a v a 2 s.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" }); } // 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.//from w w w . j av a 2 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 www . 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; }