List of usage examples for javax.security.auth Subject Subject
public Subject()
From source file:org.apache.storm.security.auth.AuthUtils.java
/** * Populate a subject from credentials using the IAutoCredentials. * @param subject the subject to populate or null if a new Subject should be created. * @param autos the IAutoCredentials to call to populate the subject. * @param credentials the credentials to pull from * @return the populated subject./*from w ww. ja va 2 s. co m*/ */ public static Subject populateSubject(Subject subject, Collection<IAutoCredentials> autos, Map<String, String> credentials) { try { if (subject == null) { subject = new Subject(); } for (IAutoCredentials autoCred : autos) { autoCred.populateSubject(subject, credentials); } return subject; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.lucidworks.security.authentication.client.KerberosAuthenticator.java
/** * Implements the SPNEGO authentication sequence interaction using the current default principal * in the Kerberos cache (normally set via kinit). * * @param token the authentication token being used for the user. * * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication error occurred. */// ww w. ja v a 2 s. c om private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException { try { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null) { LOG.debug("No subject in context, logging in"); subject = new Subject(); LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration()); login.login(); } if (LOG.isDebugEnabled()) { LOG.debug("Using subject: " + subject); } Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", KerberosAuthenticator.this.url.getHost()); Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL"); GSSName serviceName = gssManager.createName(servicePrincipal, oid); oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID"); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; boolean established = false; // Loop while the context is still not established while (!established) { outToken = gssContext.initSecContext(inToken, 0, inToken.length); if (outToken != null) { sendToken(outToken); } if (!gssContext.isEstablished()) { inToken = readToken(); } else { established = true; } } } finally { if (gssContext != null) { gssContext.dispose(); gssContext = null; } } return null; } }); } catch (PrivilegedActionException ex) { throw new AuthenticationException(ex.getException()); } catch (LoginException ex) { throw new AuthenticationException(ex); } AuthenticatedURL.extractToken(conn, token); }
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 a v a2 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:backtype.storm.blobstore.BlobStoreTest.java
public void testWithAuthentication(BlobStore store) throws Exception { //Test for Nimbus Admin Subject admin = getSubject("admin"); assertStoreHasExactly(store);// w w w . j a v a2s.c o m SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT); AtomicOutputStream out = store.createBlob("test", metadata, admin); assertStoreHasExactly(store, "test"); out.write(1); out.close(); store.deleteBlob("test", admin); //Test for Supervisor Admin Subject supervisor = getSubject("supervisor"); assertStoreHasExactly(store); metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT); out = store.createBlob("test", metadata, supervisor); assertStoreHasExactly(store, "test"); out.write(1); out.close(); store.deleteBlob("test", supervisor); //Test for Nimbus itself as a user Subject nimbus = getNimbusSubject(); assertStoreHasExactly(store); metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT); out = store.createBlob("test", metadata, nimbus); assertStoreHasExactly(store, "test"); out.write(1); out.close(); store.deleteBlob("test", nimbus); // Test with a dummy test_subject for cases where subject !=null (security turned on) Subject who = getSubject("test_subject"); assertStoreHasExactly(store); // Tests for case when subject != null (security turned on) and // acls for the blob are set to WORLD_EVERYTHING metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING); out = store.createBlob("test", metadata, who); out.write(1); out.close(); assertStoreHasExactly(store, "test"); // Testing whether acls are set to WORLD_EVERYTHING assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)")); readAssertEqualsWithAuth(store, who, "test", 1); LOG.info("Deleting test"); store.deleteBlob("test", who); assertStoreHasExactly(store); // Tests for case when subject != null (security turned on) and // acls are not set for the blob (DEFAULT) LOG.info("Creating test again"); metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT); out = store.createBlob("test", metadata, who); out.write(2); out.close(); assertStoreHasExactly(store, "test"); // Testing whether acls are set to WORLD_EVERYTHING. Here the acl should not contain WORLD_EVERYTHING because // the subject is neither null nor empty. The ACL should however contain USER_EVERYTHING as user needs to have // complete access to the blob assertTrue("ACL does not contain WORLD_EVERYTHING", !metadata.toString().contains("AccessControl(type:OTHER, access:7)")); readAssertEqualsWithAuth(store, who, "test", 2); LOG.info("Updating test"); out = store.updateBlob("test", who); out.write(3); out.close(); assertStoreHasExactly(store, "test"); readAssertEqualsWithAuth(store, who, "test", 3); LOG.info("Updating test again"); out = store.updateBlob("test", who); out.write(4); out.flush(); LOG.info("SLEEPING"); Thread.sleep(2); assertStoreHasExactly(store, "test"); readAssertEqualsWithAuth(store, who, "test", 3); // Test for subject with no principals and acls set to WORLD_EVERYTHING who = new Subject(); metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING); LOG.info("Creating test"); out = store.createBlob("test-empty-subject-WE", metadata, who); out.write(2); out.close(); assertStoreHasExactly(store, "test-empty-subject-WE", "test"); // Testing whether acls are set to WORLD_EVERYTHING assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)")); readAssertEqualsWithAuth(store, who, "test-empty-subject-WE", 2); // Test for subject with no principals and acls set to DEFAULT who = new Subject(); metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT); LOG.info("Creating other"); out = store.createBlob("test-empty-subject-DEF", metadata, who); out.write(2); out.close(); assertStoreHasExactly(store, "test-empty-subject-DEF", "test", "test-empty-subject-WE"); // Testing whether acls are set to WORLD_EVERYTHING assertTrue("ACL does not contain WORLD_EVERYTHING", metadata.toString().contains("AccessControl(type:OTHER, access:7)")); readAssertEqualsWithAuth(store, who, "test-empty-subject-DEF", 2); if (store instanceof LocalFsBlobStore) { ((LocalFsBlobStore) store).fullCleanup(1); } else { fail("Error the blobstore is of unknowntype"); } try { out.close(); } catch (IOException e) { // This is likely to happen when we try to commit something that // was cleaned up. This is expected and acceptable. } }
From source file:org.hippoecm.frontend.service.restproxy.RestProxyServicePlugin.java
protected Subject getSubject() { PluginUserSession session = (PluginUserSession) UserSession.get(); Credentials credentials = session.getCredentials(); Subject subject = new Subject(); subject.getPrivateCredentials().add(credentials); subject.setReadOnly();/*w w w .j a v a 2 s. c om*/ return subject; }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
public Subject getSubject(String userid) throws Exception { LDAPAccount user = (LDAPAccount) getUser(userid); if (user == null) { throw new AuthenticationException(userid + " is not found."); }/*from w ww . j a v a 2 s . co m*/ Subject loginUser = new Subject(); ISPrincipal p = new ISPrincipal(ISPrincipal.UID_PRINCIPAL, user.getUid()); p.setDisplayName(user.getName()); loginUser.getPrincipals().add(p); for (IGroup group : user.getGroups()) { p = new ISPrincipal(LDAP_GROUP_PRINCIPAL, group.getName()); loginUser.getPrincipals().add(p); } return loginUser; }
From source file:org.apache.karaf.jaas.modules.ldap.LdapLoginModuleTest.java
@Test public void testUserNotFound() throws Exception { Properties options = ldapLoginModuleOptions(); LDAPLoginModule module = new LDAPLoginModule(); CallbackHandler cb = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback cb : callbacks) { if (cb instanceof NameCallback) { ((NameCallback) cb).setName("imnothere"); } else if (cb instanceof PasswordCallback) { ((PasswordCallback) cb).setPassword("admin123".toCharArray()); }/* w w w. j a v a 2 s . c o m*/ } } }; Subject subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertFalse(module.login()); }
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//w w w . j av 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.betaconceptframework.astroboa.security.jaas.AstroboaLoginModule.java
private void initializeAstroboaClientForIdentityStore(String identityStoreRepositoryId) { //We assume that identity store repository exists in the same Astroboa server this module runs AstroboaClient clientForInternalIdentityStore = new AstroboaClient(); //Login as SYSTEM using Subject in order to avoid calling JAAS again //TODO This must be handled differently //In order to connect to IdentityStore, one must connect only as SYSTEM for now Subject subject = new Subject(); //System identity subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM)); Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString()); for (CmsRole cmsRole : CmsRole.values()) { rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId))); }// www . j a va 2s. co m subject.getPrincipals().add(rolesPrincipal); clientForInternalIdentityStore.login(identityStoreRepositoryId, subject, RepositoryRegistry.INSTANCE .getPermanentKeyForUser(identityStoreRepositoryId, IdentityPrincipal.SYSTEM)); identityStore = clientForInternalIdentityStore.getIdentityStore(); }
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 w w.j a va2 s . c om*/ @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; }