List of usage examples for javax.security.auth Subject getPrincipals
public Set<Principal> getPrincipals()
From source file:org.apache.karaf.jaas.modules.ldap.LdapLoginModuleTest.java
@Test public void testRoleMappingFqdn() throws Exception { Properties options = ldapLoginModuleOptions(); options.put(LDAPOptions.ROLE_MAPPING, "cn=admin,ou=groups,dc=example,dc=com=karaf;cn=admin,ou=mygroups,dc=example,dc=com=another"); options.put(LDAPOptions.ROLE_BASE_DN, "ou=groups,dc=example,dc=com"); options.put(LDAPOptions.ROLE_SEARCH_SUBTREE, "true"); options.put(LDAPOptions.ROLE_FILTER, "(member=%fqdn)"); options.put(LDAPOptions.ROLE_NAME_ATTRIBUTE, "description"); 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("admin"); } else if (cb instanceof PasswordCallback) { ((PasswordCallback) cb).setPassword("admin123".toCharArray()); }// w w w. ja va2 s.co m } } }; Subject subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals(2, subject.getPrincipals().size()); final List<String> roles = new ArrayList<String>(Arrays.asList("karaf")); boolean foundUser = false; boolean foundRole = false; for (Principal principal : subject.getPrincipals()) { if (principal instanceof UserPrincipal) { assertEquals("admin", principal.getName()); foundUser = true; } else if (principal instanceof RolePrincipal) { assertTrue(roles.remove(principal.getName())); foundRole = true; } } assertTrue(foundUser); assertTrue(foundRole); assertTrue(roles.isEmpty()); assertTrue(module.logout()); assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size()); }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Create a proxy user using username of the effective user and the ugi of the real user. * * @param user// ww w.j a va 2 s .c o m * @param realUser * * @return proxyUser ugi */ public static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser) { if (user == null || user.isEmpty()) { throw new IllegalArgumentException("Null user"); } if (realUser == null) { throw new IllegalArgumentException("Null real user"); } Subject subject = new Subject(); Set<Principal> principals = subject.getPrincipals(); principals.add(new User(user)); principals.add(new RealUser(realUser)); UserGroupInformation result = new UserGroupInformation(subject); result.setAuthenticationMethod(AuthenticationMethod.PROXY); return result; }
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."); }/* w w w . j a v a 2s . c o 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:com.buaa.cfs.security.UserGroupInformation.java
/** * Create a UserGroupInformation from a Kerberos ticket cache. * * @param user The principal name to load from the ticket cache * * @throws IOException if the kerberos login fails *//*w w w . j av a 2 s. c o m*/ public static UserGroupInformation getUGIFromTicketCache(String ticketCache, String user) throws IOException { if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) { return getBestUGI(null, user); } try { Map<String, String> krbOptions = new HashMap<String, String>(); if (IBM_JAVA) { krbOptions.put("useDefaultCcache", "true"); // The first value searched when "useDefaultCcache" is used. System.setProperty("KRB5CCNAME", ticketCache); } else { krbOptions.put("doNotPrompt", "true"); krbOptions.put("useTicketCache", "true"); krbOptions.put("useKeyTab", "false"); krbOptions.put("ticketCache", ticketCache); } krbOptions.put("renewTGT", "false"); krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS); AppConfigurationEntry ace = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), LoginModuleControlFlag.REQUIRED, krbOptions); DynamicConfiguration dynConf = new DynamicConfiguration(new AppConfigurationEntry[] { ace }); LoginContext login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf); login.login(); Subject loginSubject = login.getSubject(); Set<Principal> loginPrincipals = loginSubject.getPrincipals(); if (loginPrincipals.isEmpty()) { throw new RuntimeException("No login principals found!"); } if (loginPrincipals.size() != 1) { LOG.warn("found more than one principal in the ticket cache file " + ticketCache); } User ugiUser = new User(loginPrincipals.iterator().next().getName(), AuthenticationMethod.KERBEROS, login); loginSubject.getPrincipals().add(ugiUser); UserGroupInformation ugi = new UserGroupInformation(loginSubject); ugi.setLogin(login); ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS); return ugi; } catch (LoginException le) { throw new IOException("failure to login using ticket cache file " + ticketCache, le); } }
From source file:org.apache.qpid.server.security.access.config.RuleSet.java
/** * Filtered rules list based on a subject and operation. * * Allows only enabled rules with identity equal to all, the same, or a group with identity as a member, * and operation is either all or the same operation. *//* ww w. j a v a 2 s . c om*/ public List<Rule> getRules(final Subject subject, final Operation operation, final ObjectType objectType) { final Map<ObjectType, List<Rule>> objects = getObjectToRuleCache(subject, operation); // Lookup object type rules for the operation if (!objects.containsKey(objectType)) { final Set<Principal> principals = subject.getPrincipals(); boolean controlled = false; List<Rule> filtered = new LinkedList<Rule>(); for (Rule rule : _rules.values()) { final Action ruleAction = rule.getAction(); if (rule.isEnabled() && (ruleAction.getOperation() == Operation.ALL || ruleAction.getOperation() == operation) && (ruleAction.getObjectType() == ObjectType.ALL || ruleAction.getObjectType() == objectType)) { controlled = true; if (isRelevant(principals, rule)) { filtered.add(rule); } } } // Return null if there are no rules at all for this operation and object type if (filtered.isEmpty() && controlled == false) { filtered = null; } // Save the rules we selected objects.put(objectType, filtered); if (_logger.isDebugEnabled()) { _logger.debug("Cached " + objectType + " RulesList: " + filtered); } } // Return the cached rules List<Rule> rules = objects.get(objectType); if (_logger.isDebugEnabled()) { _logger.debug("Returning RuleList: " + rules); } return rules; }
From source file:org.apache.jetspeed.portlets.security.JetspeedPrincipalManagementPortlet.java
private static boolean hasPrincipal(Subject subject, JetspeedPrincipal jp) { Iterator<Principal> principals = subject.getPrincipals().iterator(); while (principals.hasNext()) { Principal p = principals.next(); if (p instanceof JetspeedPrincipal && ((JetspeedPrincipal) p).getType().getName().equals(jp.getType().getName()) && p.getName().equals(jp.getName())) { return true; }/*w w w .j ava 2 s. c om*/ } return false; }
From source file:org.apache.catalina.realm.JAASRealm.java
/** * Construct and return a <code>java.security.Principal</code> instance * representing the authenticated user for the specified Subject. If no * such Principal can be constructed, return <code>null</code>. * * @param subject The Subject representing the logged in user *///from w ww . j ava 2s .c o m protected Principal createPrincipal(String username, Subject subject) { // Prepare to scan the Principals for this Subject String password = null; // Will not be carried forward ArrayList roles = new ArrayList(); // Scan the Principals for this Subject Iterator principals = subject.getPrincipals().iterator(); while (principals.hasNext()) { Principal principal = (Principal) principals.next(); // No need to look further - that's our own stuff if (principal instanceof GenericPrincipal) { if (log.isDebugEnabled()) log.debug("Found old GenericPrincipal " + principal); return principal; } String principalClass = principal.getClass().getName(); if (log.isDebugEnabled()) log.info("Principal: " + principalClass + " " + principal); if (userClasses.contains(principalClass)) { // Override the default - which is the original user, accepted by // the friendly LoginManager username = principal.getName(); } if (roleClasses.contains(principalClass)) { roles.add(principal.getName()); } // Same as Jboss - that's a pretty clean solution if ((principal instanceof Group) && "Roles".equals(principal.getName())) { Group grp = (Group) principal; Enumeration en = grp.members(); while (en.hasMoreElements()) { Principal roleP = (Principal) en.nextElement(); roles.add(roleP.getName()); } } } // Create the resulting Principal for our authenticated user if (username != null) { return (new GenericPrincipal(this, username, password, roles)); } else { return (null); } }
From source file:org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter.java
@Override protected void init() throws ServletException { super.init(); if (m_krbRealm == null) { throw new ServletException("Kerberos realm not specified"); }/*from ww w . j a v a 2 s .co m*/ if (m_password == null) { throw new ServletException("HTTP service account password not specified"); } if (m_loginEntryName == null) { throw new ServletException("Invalid login entry specified"); } // Get the local host name String localName = null; try { localName = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException ex) { throw new ServletException("Failed to get local host name"); } // Create a login context for the HTTP server service try { // Login the HTTP server service m_loginContext = new LoginContext(m_loginEntryName, this); m_loginContext.login(); // DEBUG if (getLogger().isDebugEnabled()) getLogger().debug("HTTP Kerberos login successful"); } catch (LoginException ex) { // Debug if (getLogger().isErrorEnabled()) getLogger().error("HTTP Kerberos web filter error", ex); throw new ServletException("Failed to login HTTP server service"); } // Get the HTTP service account name from the subject Subject subj = m_loginContext.getSubject(); Principal princ = subj.getPrincipals().iterator().next(); m_accountName = princ.getName(); // DEBUG if (getLogger().isDebugEnabled()) getLogger().debug("Logged on using principal " + m_accountName); // Create the Oid list for the SPNEGO NegTokenInit, include NTLMSSP for fallback Vector<Oid> mechTypes = new Vector<Oid>(); mechTypes.add(OID.KERBEROS5); mechTypes.add(OID.MSKERBEROS5); // Build the SPNEGO NegTokenInit blob try { // Build the mechListMIC principle // // Note: This field is not as specified String mecListMIC = null; StringBuilder mic = new StringBuilder(); mic.append(localName); mic.append("$@"); mic.append(m_krbRealm); mecListMIC = mic.toString(); // Build the SPNEGO NegTokenInit that contains the authentication types that the HTTP server accepts NegTokenInit negTokenInit = new NegTokenInit(mechTypes, mecListMIC); // Encode the NegTokenInit blob negTokenInit.encode(); } catch (IOException ex) { // Debug if (getLogger().isErrorEnabled()) getLogger().error("Error creating SPNEGO NegTokenInit blob", ex); throw new ServletException("Failed to create SPNEGO NegTokenInit blob"); } }
From source file:org.flowerplatform.web.tests.codesync.CodeSyncWikiTest.java
public void testDokuWiki() { Subject subject = new Subject(); final FlowerWebPrincipal principal = new FlowerWebPrincipal(0); final String technology = "Doku"; String url = "http://csp1/dokuwiki/lib/exe/xmlrpc.php"; String user = ""; String password = ""; principal.getWikiClientConfigurations().put(technology, new DokuWikiClientConfiguration(url, user, password)); subject.getPrincipals().add(principal); Subject.doAsPrivileged(subject, new PrivilegedAction<Void>() { @Override//w w w . j a v a 2 s .c o m public Void run() { FlexContext.setThreadLocalSession(new HttpFlexSession()); FlexContext.setUserPrincipal(principal); RecordingTestWebCommunicationChannel cc = new RecordingTestWebCommunicationChannel(); cc.setPrincipal((FlowerWebPrincipal) principal); ServiceInvocationContext context = new ServiceInvocationContext(cc); Object wiki = DokuWikiPlugin.getInstance().getWikiPages("proiecte:flower:teste"); WikiPlugin.getInstance().getConfigurationProviders().put(technology, new DokuWikiConfigurationProvider()); WikiPlugin wikiPlugin = WikiPlugin.getInstance(); File project = getProject(); ResourceSet resourceSet = CodeSyncPlugin.getInstance().getOrCreateResourceSet(project, "mindmapEditorStatefulService"); CodeSyncRoot leftRoot = wikiPlugin.getWikiTree(null, resourceSet, wiki, "proiecte:flower:teste", technology); CodeSyncRoot rightRoot = wikiPlugin.getWikiTree(project, resourceSet, null, "proiecte:flower:teste", technology); expected = new Pair[] { new Pair(WikiPlugin.FOLDER_CATEGORY, 0), // Crispico new Pair(WikiPlugin.FOLDER_CATEGORY, 1), // proiecte new Pair(WikiPlugin.FOLDER_CATEGORY, 2), // flower new Pair(WikiPlugin.PAGE_CATEGORY, 3), // teste new Pair(WikiPlugin.FOLDER_CATEGORY, 4), // teste new Pair(WikiPlugin.PAGE_CATEGORY, 5), // new_test new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 6), new Pair(WikiPlugin.HEADING_LEVEL_3_CATEGORY, 7), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 8), new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4), new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4), new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 5), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.FLOWER_BLOCK_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 5), new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4) }; test(leftRoot, rightRoot, resourceSet, technology, expected); return null; } }, null); }
From source file:com.nulli.openam.plugins.NeoUniversalCondition.java
/** * {@inheritDoc}/*from w ww . ja v a 2s . c om*/ */ @SuppressWarnings("deprecation") @Override public ConditionDecision evaluate(String realm, Subject subject, String resourceName, Map<String, Set<String>> env) throws EntitlementException { Map<String, Set<String>> advices = new HashMap<String, Set<String>>(); if (!subject.getPrincipals().isEmpty() && paramsJson != null) { try { String cypherResult = null; JSONObject params = sanitizeParams(paramsJson, realm, subject, resourceName, env); cypherResult = neoQuery(cypherQuery, params); if (cypherResult == null) { throw new ConnectionException( "Error response received from the Graph DB while querying NeoClientType!"); } if (cypherResult.equalsIgnoreCase(allowCypherResult)) { return new ConditionDecision(true, advices); } else if (cypherResult.equalsIgnoreCase(denyCypherResult)) { return new ConditionDecision(false, advices); } } catch (ConnectionException ex) { Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex); } } return new ConditionDecision(false, advices); // This is a deny }