List of usage examples for javax.security.auth Subject doAs
public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action) throws java.security.PrivilegedActionException
From source file:org.apache.ranger.services.hive.client.HiveClient.java
public List<String> getColumnList(String columnNameMatching, List<String> dbList, List<String> tblList, List<String> colList) throws HadoopException { final String clmNameMatching = columnNameMatching; final List<String> databaseList = dbList; final List<String> tableList = tblList; final List<String> clmList = colList; List<String> columnList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() { public List<String> run() { List<String> ret = null; try { ret = getClmList(clmNameMatching, databaseList, tableList, clmList); } catch (HadoopException he) { LOG.error("<== HiveClient getColumnList() :Unable to get the Column List", he); throw he; }/*from ww w. j a v a 2 s .c om*/ return ret; } }); return columnList; }
From source file:org.apache.ranger.biz.KmsKeyMgr.java
public VXKmsKey rolloverKey(String provider, VXKmsKey vXKey) throws Exception { String providers[] = null;/*from w w w . j a v a 2 s.c om*/ try { providers = getKMSURL(provider); } catch (Exception e) { logger.error("rolloverKey(" + provider + ", " + vXKey.getName() + ") failed", e); } VXKmsKey ret = null; boolean isKerberos = false; try { isKerberos = checkKerberos(); } catch (Exception e1) { logger.error("checkKerberos(" + provider + ") failed", e1); } if (providers != null) { for (int i = 0; i < providers.length; i++) { Client c = getClient(); String rollRest = KMS_ROLL_KEY_URI.replaceAll(Pattern.quote("${alias}"), vXKey.getName()); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String uri = providers[i] + (providers[i].endsWith("/") ? rollRest : ("/" + rollRest)); if (!isKerberos) { uri = uri.concat("?user.name=" + currentUserLoginId); } else { uri = uri.concat("?doAs=" + currentUserLoginId); } final WebResource r = c.resource(uri); Gson gson = new GsonBuilder().create(); final String jsonString = gson.toJson(vXKey); try { String response = null; if (!isKerberos) { response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, jsonString); } else { Subject sub = getSubjectForKerberos(provider); response = Subject.doAs(sub, new PrivilegedAction<String>() { @Override public String run() { return r.accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } }); } logger.debug("Roll RESPONSE: [" + response + "]"); ret = gson.fromJson(response, VXKmsKey.class); break; } catch (Exception e) { if (e instanceof UniformInterfaceException || i == providers.length - 1) throw e; else continue; } } } return ret; }
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; }/* w w w.j ava 2s.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:com.ikon.module.jcr.stuff.JCRUtils.java
/** * Get JCR Session// ww w . java 2 s . co m */ public static Session getSession() throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException { Subject subject = null; Object obj = null; // Resolve subject // Subject userSubject=(Subject)PolicyContext.getContext("javax.security.auth.Subject.container"); if (EnvironmentDetector.isServerJBoss()) { try { InitialContext ctx = new InitialContext(); subject = (Subject) ctx.lookup("java:/comp/env/security/subject"); ctx.close(); } catch (NamingException e) { throw new javax.jcr.LoginException(e.getMessage()); } } else if (EnvironmentDetector.isServerTomcat()) { subject = Subject.getSubject(AccessController.getContext()); } // Obtain JCR session if (subject != null) { obj = Subject.doAs(subject, new PrivilegedAction<Object>() { public Object run() { Session s = null; try { s = JcrRepositoryModule.getRepository().login(); } catch (javax.jcr.LoginException e) { return e; } catch (javax.jcr.RepositoryException e) { return e; } return s; } }); } // Validate JCR session if (obj instanceof javax.jcr.LoginException) { throw (javax.jcr.LoginException) obj; } else if (obj instanceof javax.jcr.RepositoryException) { throw (javax.jcr.RepositoryException) obj; } else if (obj instanceof javax.jcr.Session) { Session session = (javax.jcr.Session) obj; log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions, session, StackTraceUtils.whoCalledMe() }); JcrAuthModule.loadUserData(session); return session; } else { return null; } }
From source file:org.apache.drill.exec.server.rest.spnego.TestDrillSpnegoAuthenticator.java
/** * Test to verify authentication fails when client sends invalid SPNEGO token for the * {@link WebServerConstants#SPENGO_LOGIN_RESOURCE_PATH} resource. * @throws Exception/*from w w w.j a v a 2s. c o m*/ */ @Test public void testSpnegoLoginInvalidToken() throws Exception { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final HttpSession session = Mockito.mock(HttpSession.class); // Create client subject using it's principal and keytab final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(spnegoHelper.CLIENT_PRINCIPAL, spnegoHelper.clientKeytab.getAbsoluteFile()); // Generate a SPNEGO token for the peer SERVER_PRINCIPAL from this CLIENT_PRINCIPAL final String token = Subject.doAs(clientSubject, new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { final GSSManager gssManager = GSSManager.getInstance(); GSSContext gssContext = null; try { final Oid oid = GSSUtil.GSS_SPNEGO_MECH_OID; final GSSName serviceName = gssManager.createName(spnegoHelper.SERVER_PRINCIPAL, GSSName.NT_USER_NAME, oid); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] outToken = new byte[0]; outToken = gssContext.initSecContext(outToken, 0, outToken.length); return Base64.encodeBase64String(outToken); } finally { if (gssContext != null) { gssContext.dispose(); } } } }); Mockito.when(request.getSession(true)).thenReturn(session); final String httpReqAuthHeader = String.format("%s:%s", HttpHeader.NEGOTIATE.asString(), String.format("%s%s", "1234", token)); Mockito.when(request.getHeader(HttpHeader.AUTHORIZATION.asString())).thenReturn(httpReqAuthHeader); Mockito.when(request.getRequestURI()).thenReturn(WebServerConstants.SPENGO_LOGIN_RESOURCE_PATH); assertEquals(spnegoAuthenticator.validateRequest(request, response, false), Authentication.UNAUTHENTICATED); verify(session, never()).setAttribute(SessionAuthentication.__J_AUTHENTICATED, null); verify(response, never()).sendError(401); verify(response, never()).setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), HttpHeader.NEGOTIATE.asString()); }
From source file:com.lucidworks.security.authentication.server.KerberosAuthenticationHandler.java
/** * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only * after the Kerberos SPNEGO sequence has completed successfully. * <p/>// www .j ava 2 s . c o m * * @param request the HTTP client request. * @param response the HTTP client response. * * @return an authentication token if the Kerberos SPNEGO sequence is complete and valid, * <code>null</code> if it is in progress (in this case the handler handles the response to the client). * * @throws IOException thrown if an IO error occurred. * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed. */ @Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) { response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (authorization == null) { LOG.trace("SPNEGO starting"); } else { LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' : {}", authorization); } } else { authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); Subject serverSubject = loginContext.getSubject(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { if (PlatformName.IBM_JAVA) { // IBM JDK needs non-null credentials to be passed to createContext here, with // SPNEGO mechanism specified, otherwise JGSS will use its default mechanism // only, which is Kerberos V5. gssCreds = gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); } gssContext = gssManager.createContext(gssCreds); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = base64.encodeToString(serverToken); response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }
From source file:org.wildfly.test.integration.elytron.sasl.mgmt.AbstractKerberosMgmtSaslTestBase.java
/** * Asserts that given user can authenticate with given Kerberos SASL mechanism. *//* w w w . j a v a 2s. c om*/ protected void assertKerberosSaslMechPasses(String mech, String user, String password, boolean withSsl) throws MalformedURLException, LoginException, Exception { // 1. Authenticate to Kerberos. final LoginContext lc = KerberosTestUtils.loginWithKerberos(KRB5_CONFIGURATION, user, password); try { AuthenticationConfiguration authCfg = AuthenticationConfiguration.empty() .setSaslMechanismSelector(SaslMechanismSelector.fromString(mech)) .useGSSCredential(getGSSCredential(lc.getSubject())); AuthenticationContext authnCtx = AuthenticationContext.empty().with(MatchRule.ALL, authCfg); if (withSsl) { authnCtx = authnCtx.withSsl(MatchRule.ALL, sslFactory); } final AuthenticationContext authnCtxFinal = authnCtx; Subject.doAs(lc.getSubject(), (PrivilegedAction<Void>) () -> { authnCtxFinal.run(() -> assertWhoAmI(user + "@JBOSS.ORG", withSsl)); return null; }); } finally { lc.logout(); } }
From source file:org.josso.alfresco.agent.AlfrescoSSOAgentFilter.java
protected void setAuthenticatedUser(final HttpServletRequest req, final HttpServletResponse res, final HttpSession httpSess, final String userName) { UserTransaction tx = serviceRegistry.getTransactionService().getUserTransaction(); Subject.doAs(AlfrescoPrivilegdedActions.getAdminSubject(), AlfrescoPrivilegdedActions.clearCurrentSecurityContextAction(authComponent)); ticketComponent.clearCurrentTicket(); try {/*from www.ja v a 2 s . co m*/ tx.begin(); Subject.doAs(AlfrescoPrivilegdedActions.getAdminSubject(), AlfrescoPrivilegdedActions.setCurrentUserAction(userName)); Subject.doAs(AlfrescoPrivilegdedActions.getAdminSubject(), AlfrescoPrivilegdedActions.createUserAction(serviceRegistry, userName, httpSess)); FacesHelper.getFacesContext(req, res, _ctx); FacesContext fc = FacesContext.getCurrentInstance(); Map session = fc.getExternalContext().getSessionMap(); session.remove(AuthenticationHelper.SESSION_INVALIDATED); tx.commit(); } catch (Throwable ex) { logger.error(ex); try { tx.rollback(); } catch (Exception ex2) { logger.error("Failed to rollback transaction", ex2); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException("Failed to execute transactional method", ex); } } }
From source file:org.apache.drill.exec.server.rest.spnego.TestSpnegoAuthentication.java
/** * Validate successful {@link DrillSpnegoLoginService#login(String, Object)} when provided with client token for a * configured service principal./* ww w.j a va 2 s .com*/ * @throws Exception */ @Test public void testDrillSpnegoLoginService() throws Exception { // Create client subject using it's principal and keytab final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(spnegoHelper.CLIENT_PRINCIPAL, spnegoHelper.clientKeytab.getAbsoluteFile()); // Generate a SPNEGO token for the peer SERVER_PRINCIPAL from this CLIENT_PRINCIPAL final String token = Subject.doAs(clientSubject, new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { final GSSManager gssManager = GSSManager.getInstance(); GSSContext gssContext = null; try { final Oid oid = GSSUtil.GSS_SPNEGO_MECH_OID; final GSSName serviceName = gssManager.createName(spnegoHelper.SERVER_PRINCIPAL, GSSName.NT_USER_NAME, oid); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] outToken = new byte[0]; outToken = gssContext.initSecContext(outToken, 0, outToken.length); return Base64.encodeBase64String(outToken); } finally { if (gssContext != null) { gssContext.dispose(); } } } }); // Create a DrillbitContext with service principal and keytab for DrillSpnegoLoginService final DrillConfig newConfig = new DrillConfig(DrillConfig.create() .withValue(ExecConstants.HTTP_AUTHENTICATION_MECHANISMS, ConfigValueFactory.fromIterable(Lists.newArrayList("spnego"))) .withValue(ExecConstants.HTTP_SPNEGO_PRINCIPAL, ConfigValueFactory.fromAnyRef(spnegoHelper.SERVER_PRINCIPAL)) .withValue(ExecConstants.HTTP_SPNEGO_KEYTAB, ConfigValueFactory.fromAnyRef(spnegoHelper.serverKeytab.toString()))); final SystemOptionManager optionManager = Mockito.mock(SystemOptionManager.class); Mockito.when(optionManager.getOption(ExecConstants.ADMIN_USERS_VALIDATOR)) .thenReturn(ExecConstants.ADMIN_USERS_VALIDATOR.DEFAULT_ADMIN_USERS); Mockito.when(optionManager.getOption(ExecConstants.ADMIN_USER_GROUPS_VALIDATOR)) .thenReturn(ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.DEFAULT_ADMIN_USER_GROUPS); final DrillbitContext drillbitContext = Mockito.mock(DrillbitContext.class); Mockito.when(drillbitContext.getConfig()).thenReturn(newConfig); Mockito.when(drillbitContext.getOptionManager()).thenReturn(optionManager); final DrillSpnegoLoginService loginService = new DrillSpnegoLoginService(drillbitContext); // Authenticate the client using its SPNEGO token final UserIdentity user = loginService.login(null, token); // Validate the UserIdentity of authenticated client assertTrue(user != null); assertTrue(user.getUserPrincipal().getName().equals(spnegoHelper.CLIENT_SHORT_NAME)); assertTrue(user.isUserInRole("authenticated", null)); }
From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java
private String getEncodedKerberosTicket(boolean spnego) throws Exception { System.setProperty("java.security.auth.login.config", "src/test/resources/kerberos.jaas"); System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true"); Oid kerberos5Oid = null; if (spnego) { kerberos5Oid = new Oid("1.3.6.1.5.5.2"); } else {// ww w. j ava 2 s.c o m kerberos5Oid = new Oid("1.2.840.113554.1.2.2"); } GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName("bob@service.ws.apache.org", GSSName.NT_HOSTBASED_SERVICE); GSSContext context = manager.createContext(serverName.canonicalize(kerberos5Oid), kerberos5Oid, null, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(true); final byte[] token = new byte[0]; String contextName = "alice"; LoginContext lc = new LoginContext(contextName); lc.login(); byte[] ticket = (byte[]) Subject.doAs(lc.getSubject(), new CreateServiceTicketAction(context, token)); return Base64.encode(ticket); }