📄 activedirectoryuserdatabase.java
字号:
ActiveDirectoryUser populateUserInfo(DirContext ctx, String username) throws NamingException, UserDatabaseException {
// do something useful with ctx
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setCountLimit(0);
if (log.isDebugEnabled()) {
log.debug("Populating user details (" + constraints + ")");
}
for (Iterator it = includedOUBasesList.iterator(); it.hasNext();) {
String searchBase = (String) it.next();
NamingEnumeration results = ctx.search(searchBase, USER_FILTER.replaceAll("%USERNAME%", username), constraints);
// Now step through the search results
if (results != null && results.hasMore()) {
if (log.isDebugEnabled()) {
log.debug("Found a result");
}
SearchResult sr = (SearchResult) results.next();
// This fixes the problem with / in OU's or usernames; using
// sr.getName returns a quoted string for some dns which is
// wrong
return createUser(ctx, sr);
}
}
throw new NamingException("No match found for username " + username);
}
LoginContext createLoginContext(String username, String password) throws LoginException {
LoginContext lc = null;
if (log.isDebugEnabled())
log.debug("Creating login context for " + username);
/* Set up the Callback handler, and initialise */
/* the userid and password fields */
UserPasswordCallbackHandler ch = new UserPasswordCallbackHandler();
ch.setUserId(username);
ch.setPassword(password);
/* Initialise the login context - LoginModule configured */
lc = new LoginContext(ActiveDirectoryUserDatabase.class.getName(), ch);
/* Perform the authentication */
lc.login();
Subject mSubject = lc.getSubject();
Iterator li = mSubject.getPrincipals().iterator();
Principal lPrincipal = null;
if (log.isDebugEnabled()) {
log.debug("Getting principals");
}
while (li.hasNext()) {
lPrincipal = (Principal) li.next();
if (log.isDebugEnabled()) {
log.debug("Got principal '" + lPrincipal + "'");
}
}
return lc;
}
String getDN(SearchResult sr) {
if (!checkedNameInNameSpace) {
try {
nameInNamespaceMethod = SearchResult.class.getMethod("getNameInNamespace", new Class[] {});
} catch (Throwable t) {
}
checkedNameInNameSpace = true;
}
if (nameInNamespaceMethod != null) {
try {
String nameInNamespace = ((String) nameInNamespaceMethod.invoke(sr, new Object[] {}));
if (log.isDebugEnabled())
log.debug("Name in namespace = " + nameInNamespace);
String n = nameInNamespace.replaceAll("/", "\\\\/");
if (log.isDebugEnabled()) {
log.debug("N = " + n);
log.debug("1.4 method = " + sr.getName() + "," + activeDirectoryRoot);
}
return n;
} catch (Throwable t) {
log.error("This shouldn't have failed", t);
}
}
// TODO This *must* be fixed if we are going to run on Java 1.4
Util.toDo("No SearchResult.getNameInNamespace() method available, this will fail!!");
return sr.getName() + "," + activeDirectoryRoot;
}
LoginContext getEffectiveUser() {
try {
LoginContext ctxt = getServiceAccountLoginContext();
return ctxt;
} catch (Exception e) {
log.error("Failed to get effective user.", e);
return null;
}
}
boolean inBasesList(List basesList, String dn) {
for (Iterator i = basesList.iterator(); i.hasNext();) {
if (dn.toLowerCase().endsWith("," + String.valueOf(i.next()).toLowerCase())) {
return true;
}
}
return false;
}
static String splitDomain(String domain) {
StringBuffer buf = new StringBuffer();
StringTokenizer t = new StringTokenizer(domain, ".");
while (t.hasMoreTokens()) {
if (buf.length() > 0) {
buf.append(",");
}
buf.append("DC=" + t.nextToken());
}
return buf.toString();
}
/**
* Get a user account given a DN. <code>null</code> will be returned if no
* such account can be found.
*
* @param dn dn
* @return user account
* @throws Exception on any error
*/
public User getAccountFromDN(String dn) throws Exception {
if (dn.indexOf("CN") > -1 && dn.indexOf("DC") > -1) {
// This looks like a DN so do a lookup
if (log.isInfoEnabled())
log.info("Looking up account using DN: " + dn);
UserDNAction udn = new UserDNAction(dn);
return (User) Subject.doAs(getServiceAccountLoginContext().getSubject(), udn);
} else
throw new Exception("Certificate requires subject to be DN of Active Directory user");
}
class UserDNAction implements java.security.PrivilegedAction {
String dn;
DirContext ctx;
UserDNAction(String dn) {
this.dn = dn;
}
public Object run() {
try {
if (log.isDebugEnabled())
log.debug("Running DN details action for " + dn);
// Set up environment for creating initial context
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
// Must use fully qualified hostname
env.put(Context.PROVIDER_URL, adURL);
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put("java.naming.ldap.version", "3");
env.put("com.sun.jndi.ldap.connect.pool", "true");
/* Create initial context */
ctx = new InitialDirContext(env);
return getAccountFromDN(dn, ctx);
} catch (NamingException ex) {
log.error("Failed to get user details.", ex);
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException ex1) {
}
}
}
return null;
}
}
User getAccountFromDN(String dn, DirContext ctx) throws NamingException {
StringTokenizer tokens = new StringTokenizer(dn, ",");
String elm;
String actualDN = null;
while (tokens.hasMoreTokens()) {
elm = tokens.nextToken().trim();
if (elm.toUpperCase().startsWith("CN") || elm.toUpperCase().startsWith("OU") || elm.toUpperCase().startsWith("DC")) {
actualDN = (actualDN == null ? "" : actualDN + ",") + elm;
}
}
try {
Attributes ar = ctx.getAttributes(actualDN, USER_ATTRS);
ActiveDirectoryUser user = new ActiveDirectoryUser("");
populateUserObject(dn, getRoleMap("*"), user, ar);
return user;
} catch (Exception ex) {
log.error("Cannot locate user for DN " + dn, ex);
throw new NamingException("User not found for DN " + dn);
}
}
private void populateUserObject(String dn, RoleMap groups, ActiveDirectoryUser user, Attributes ar) throws NamingException {
user.setDN(dn);
if (ar == null)
throw new NamingException("No attributes for " + user.getPrincipalName());
if (ar.get("sAMAccountName") != null)
user.setPrincipalName((String) ((Attribute) ar.get("sAMAccountName")).get());
else
user.setPrincipalName("");
if (ar.get("mail") != null)
user.setEmail((String) ((Attribute) ar.get("mail")).get());
else
user.setEmail("");
if (ar.get("cn") != null)
user.setFullname((String) ((Attribute) ar.get("cn")).get());
else
user.setFullname("");
if (ar.get(User.USER_ATTR_HOME_DIRECTORY) != null) {
user.getAttributes().setProperty(User.USER_ATTR_HOME_DIRECTORY,
(String) ((Attribute) ar.get(User.USER_ATTR_HOME_DIRECTORY)).get());
}
if (ar.get(User.USER_ATTR_HOME_DRIVE) != null) {
user.getAttributes().setProperty(User.USER_ATTR_HOME_DRIVE,
(String) ((Attribute) ar.get(User.USER_ATTR_HOME_DRIVE)).get());
}
Vector roles = new Vector();
if (ar.get("primaryGroupId") != null) {
Attribute attr = (Attribute) ar.get("primaryGroupId");
Long rid = new Long(Long.parseLong((String) attr.get()));
if (log.isDebugEnabled())
log.debug("Users primaryGroupId is " + rid.toString());
Role role = groups.getByRID(rid);
if (role != null) {
if (log.isDebugEnabled())
log.debug("Users primary group is " + ((ActiveDirectoryGroup) role).getDN());
roles.add(role);
} else {
if (log.isInfoEnabled())
log.info("Could not find primary group " + rid.toString() + " for user " + dn);
}
}
if (ar.get("memberOf") != null) {
Attribute attr = (Attribute) ar.get("memberOf");
for (int j = 0; j < attr.size(); j++) {
dn = (String) (attr).get(j);
if (log.isDebugEnabled())
log.debug("Checking if user is a member of " + dn + " a valid group");
if (groups.containsDN(dn)) {
ActiveDirectoryGroup r = (ActiveDirectoryGroup) groups.getByDN(dn);
if (r != null && !roles.contains(r)) {
roles.add(r);
if (log.isDebugEnabled())
log.debug("Member of " + dn + " [" + ((ActiveDirectoryGroup) r).getSAMAccountName() + "]");
/**
* Add the parent groups for each group since the user
* effectively belongs to those groups too.
*/
if (r.getParents() != null) {
for (int i = 0; i < r.getParents().length; i++) {
if (r.getParents()[i] == null) {
if (log.isDebugEnabled())
log.debug("Found NULL parent group in populateUserInfo");
}
else if(!roles.contains(r.getParents()[i]))
roles.add(r.getParents()[i]);
}
}
} else {
if (log.isInfoEnabled())
log.info("Could not find group " + dn);
}
}
}
}
ActiveDirectoryGroup[] r = new ActiveDirectoryGroup[roles.size()];
if (log.isDebugEnabled())
log.debug("User belongs to " + roles.size() + " roles");
roles.copyInto(r);
user.setRoles(r);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -