下面列出了javax.naming.directory.DirContext#getAttributes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
String getDnsAttributes(String ip) {
try {
Hashtable<String, String> env = new Hashtable<>();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
// TODO don't specify ws1, instead use ns servers for s.maxmind.com
env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(licenseKey + "." + ip
+ ".s.maxmind.com", new String[] { "txt" });
// System.out.println(attrs.get("txt").get());
String str = attrs.get("txt").get().toString();
return str;
} catch (NamingException e) {
// TODO fix this to handle exceptions
System.out.println("DNS error");
return null;
}
}
private String invokeLdap(GSSCredential gssCredential) throws NamingException {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
if (gssCredential != null) {
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put(Sasl.CREDENTIALS, gssCredential);
}
DirContext ctx = new InitialDirContext(env);
try {
Attributes attrs = ctx.getAttributes("uid=hnelson,ou=People,dc=keycloak,dc=org");
String cn = (String) attrs.get("cn").get();
String sn = (String) attrs.get("sn").get();
return cn + " " + sn;
} finally {
ctx.close();
}
}
protected String invokeLdap(GSSCredential gssCredential, String username) throws NamingException {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
if (gssCredential != null) {
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put(Sasl.CREDENTIALS, gssCredential);
}
DirContext ctx = new InitialDirContext(env);
try {
Attributes attrs = ctx.getAttributes("uid=" + username + ",ou=People,dc=keycloak,dc=org");
String cn = (String) attrs.get("cn").get();
String sn = (String) attrs.get("sn").get();
return cn + " " + sn;
} finally {
ctx.close();
}
}
/**
* Returns a server's address and port for the specified hostname, looking up the SRV record if possible
* Copied from Minecraft src
*/
private static String[] getServerAddress(String serverHost) {
try {
Class.forName("com.sun.jndi.dns.DnsContextFactory");
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("java.naming.provider.url", "dns:");
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext dircontext = new InitialDirContext(hashtable);
Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + serverHost, new String[] {"SRV"});
String[] astring = attributes.get("srv").get().toString().split(" ", 4);
return new String[] {astring[3], astring[2]};
} catch (Throwable var6) {
return new String[] {serverHost, Integer.toString(25565)};
}
}
/**
* Returns the hostname associated with the specified IP address by the
* provided nameserver.
*
* @param hostIp
* The address to reverse lookup
* @param ns
* The host name of a reachable DNS server
* @return The host name associated with the provided IP
* @throws NamingException
* If a NamingException is encountered
*/
public static String reverseDns(InetAddress hostIp, String ns)
throws NamingException {
//
// Builds the reverse IP lookup form
// This is formed by reversing the IP numbers and appending in-addr.arpa
//
String[] parts = hostIp.getHostAddress().split("\\.");
String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
+ parts[0] + ".in-addr.arpa";
DirContext ictx = new InitialDirContext();
Attributes attribute =
ictx.getAttributes("dns://" // Use "dns:///" if the default
+ ((ns == null) ? "" : ns) +
// nameserver is to be used
"/" + reverseIP, new String[] { "PTR" });
ictx.close();
return attribute.get("PTR").get().toString();
}
private static LDAPUser invokeLdap(GSSCredential gssCredential, String username) throws NamingException {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
if (gssCredential != null) {
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put(Sasl.CREDENTIALS, gssCredential);
}
DirContext ctx = new InitialDirContext(env);
try {
Attributes attrs = ctx.getAttributes("uid=" + username + ",ou=People,dc=keycloak,dc=org");
String uid = username;
String cn = (String) attrs.get("cn").get();
String sn = (String) attrs.get("sn").get();
return new LDAPUser(uid, cn, sn);
} finally {
ctx.close();
}
}
public String uid2ext(String uid) {
try {
DirContext ctx = null;
try {
ctx = getDirContext();
Attributes attributes = ctx.getAttributes(
ApplicationProperties.getProperty("tmtbl.authenticate.ldap.uid2ext").replaceAll("%", uid),
new String[] {
ApplicationProperties.getProperty("tmtbl.authenticate.ldap.externalId", "puid")
});
if (attributes!=null) {
Attribute puid = attributes.get(ApplicationProperties.getProperty("tmtbl.authenticate.ldap.externalId", "puid"));
if (puid!=null) return (String)puid.get();
}
} finally {
if (ctx!=null) ctx.close();
}
} catch (Exception e) {
Debug.error("Unable to translate uid to ext, "+e.getMessage());
}
return null;
}
/**
* verify if there is a mail server registered to the domain name. and return the email servers count
*/
public static int mailServersCount( String hostName ) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" } );
Attribute attr = attrs.get( "MX" );
if ( attr == null ) {
return ( 0 );
}
return ( attr.size() );
}
private static ArrayList<String> getMX( String hostName ) throws NamingException {
// Perform a DNS lookup for MX records in the domain
Hashtable<String, String> env = new Hashtable<String, String>();
env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" } );
Attribute attr = attrs.get( "MX" );
// if we don't have an MX record, try the machine itself
if ( ( attr == null ) || ( attr.size() == 0 ) ) {
attrs = ictx.getAttributes( hostName, new String[] { "A" } );
attr = attrs.get( "A" );
if ( attr == null ) {
throw new NamingException( BaseMessages.getString( PKG, "MailValidator.NoMatchName", hostName ) );
}
}
// Huzzah! we have machines to try. Return them as an array list
// NOTE: We SHOULD take the preference into account to be absolutely
// correct. This is left as an exercise for anyone who cares.
ArrayList<String> res = new ArrayList<>();
NamingEnumeration<?> en = attr.getAll();
while ( en.hasMore() ) {
String x = (String) en.next();
String[] f = x.split( " " );
if ( f[ 1 ].endsWith( "." ) ) {
f[ 1 ] = f[ 1 ].substring( 0, ( f[ 1 ].length() - 1 ) );
}
res.add( f[ 1 ] );
}
return res;
}
/**
* verify if there is a mail server registered to the domain name. and return the email servers count
*/
public static int mailServersCount( String hostName ) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" } );
Attribute attr = attrs.get( "MX" );
if ( attr == null ) {
return ( 0 );
}
return ( attr.size() );
}
/**
* Use the distinguished name to locate the directory
* entry for the user with the specified username and
* return a User object; otherwise return <code>null</code>.
*
* @param context The directory context
* @param username The username
* @param attrIds String[]containing names of attributes to
* @param dn Distinguished name of the user
* retrieve.
*
* @exception NamingException if a directory server error occurs
*/
protected User getUserByPattern(DirContext context,
String username,
String[] attrIds,
String dn)
throws NamingException {
// If no attributes are requested, no need to look for them
if (attrIds == null || attrIds.length == 0) {
return new User(username, dn, null, null,null);
}
// Get required attributes from user entry
Attributes attrs = null;
try {
attrs = context.getAttributes(dn, attrIds);
} catch (NameNotFoundException e) {
return (null);
}
if (attrs == null)
return (null);
// Retrieve value of userPassword
String password = null;
if (userPassword != null)
password = getAttributeValue(userPassword, attrs);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
}
// Retrieve values of userRoleName attribute
ArrayList<String> roles = null;
if (userRoleName != null)
roles = addAttributeValues(userRoleName, attrs, roles);
return new User(username, dn, password, roles, userRoleAttrValue);
}
/**
* Check credentials by binding to the directory as the user
*
* @param context The directory context
* @param user The User to be authenticated
* @param credentials Authentication credentials
*
* @exception NamingException if a directory server error occurs
*/
protected boolean bindAsUser(DirContext context,
User user,
String credentials)
throws NamingException {
if (credentials == null || user == null)
return (false);
String dn = user.getDN();
if (dn == null)
return (false);
// Validate the credentials specified by the user
if (containerLog.isTraceEnabled()) {
containerLog.trace(" validating credentials by binding as the user");
}
userCredentialsAdd(context, dn, credentials);
// Elicit an LDAP bind operation
boolean validated = false;
try {
if (containerLog.isTraceEnabled()) {
containerLog.trace(" binding as " + dn);
}
context.getAttributes("", null);
validated = true;
}
catch (AuthenticationException e) {
if (containerLog.isTraceEnabled()) {
containerLog.trace(" bind attempt failed");
}
}
userCredentialsRemove(context);
return (validated);
}
/**
* Returns the hostname associated with the specified IP address by the
* provided nameserver.
*
* Loopback addresses
* @param hostIp The address to reverse lookup
* @param ns The host name of a reachable DNS server
* @return The host name associated with the provided IP
* @throws NamingException If a NamingException is encountered
*/
public static String reverseDns(InetAddress hostIp, String ns)
throws NamingException {
//
// Builds the reverse IP lookup form
// This is formed by reversing the IP numbers and appending in-addr.arpa
//
String[] parts = hostIp.getHostAddress().split("\\.");
String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
+ parts[0] + ".in-addr.arpa";
DirContext ictx = new InitialDirContext();
Attributes attribute;
try {
attribute = ictx.getAttributes("dns://" // Use "dns:///" if the default
+ ((ns == null) ? "" : ns) +
// nameserver is to be used
"/" + reverseIP, new String[] { "PTR" });
} finally {
ictx.close();
}
String hostname = attribute.get("PTR").get().toString();
int hostnameLength = hostname.length();
if (hostname.charAt(hostnameLength - 1) == '.') {
hostname = hostname.substring(0, hostnameLength - 1);
}
return hostname;
}
private ArrayList getMX(String hostName) throws NamingException {
// Perform a DNS lookup for MX records in the domain
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(hostName, new String[]{"MX"});
Attribute attr = attrs.get("MX");
// if we don't have an MX record, try the machine itself
if ((attr == null) || (attr.size() == 0)) {
attrs = ictx.getAttributes(hostName, new String[]{"A"});
attr = attrs.get("A");
if (attr == null)
throw new NamingException("No match for name '" + hostName
+ "'");
}
// Huzzah! we have machines to try. Return them as an array list
// NOTE: We SHOULD take the preference into account to be absolutely
// correct. This is left as an exercise for anyone who cares.
ArrayList res = new ArrayList();
NamingEnumeration en = attr.getAll();
while (en.hasMore()) {
String mailhost;
String x = (String) en.next();
String f[] = x.split(" ");
// THE fix *************
if (f.length == 1)
mailhost = f[0];
else if (f[1].endsWith("."))
mailhost = f[1].substring(0, (f[1].length() - 1));
else
mailhost = f[1];
// THE fix *************
res.add(mailhost);
}
return res;
}
/**
* Use the distinguished name to locate the directory
* entry for the user with the specified username and
* return a User object; otherwise return <code>null</code>.
*
* @param context The directory context
* @param username The username
* @param attrIds String[]containing names of attributes to
* @param dn Distinguished name of the user
* retrieve.
*
* @exception NamingException if a directory server error occurs
*/
protected User getUserByPattern(DirContext context,
String username,
String[] attrIds,
String dn)
throws NamingException {
// If no attributes are requested, no need to look for them
if (attrIds == null || attrIds.length == 0) {
return new User(username, dn, null, null,null);
}
// Get required attributes from user entry
Attributes attrs = null;
try {
attrs = context.getAttributes(dn, attrIds);
} catch (NameNotFoundException e) {
return null;
}
if (attrs == null)
return null;
// Retrieve value of userPassword
String password = null;
if (userPassword != null)
password = getAttributeValue(userPassword, attrs);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
}
// Retrieve values of userRoleName attribute
ArrayList<String> roles = null;
if (userRoleName != null)
roles = addAttributeValues(userRoleName, attrs, roles);
return new User(username, dn, password, roles, userRoleAttrValue);
}
/**
* Retrieves selected attributes associated with a named object.
*
* @return the requested attributes; never null
* @param name the name of the object from which to retrieve attributes
* @param attrIds the identifiers of the attributes to retrieve. null
* indicates that all attributes should be retrieved; an empty array
* indicates that none should be retrieved
* @exception NamingException if a naming exception is encountered
*/
@Override
public final Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
// First check for aliases
if (!aliases.isEmpty()) {
AliasResult result = findAlias(name);
if (result.dirContext != null) {
return result.dirContext.getAttributes(
result.aliasName, attrIds);
}
}
// Next do a standard lookup
Attributes attrs = doGetAttributes(name, attrIds);
if (attrs != null)
return attrs;
String resourceName = "/META-INF/resources" + name;
// Check the alternate locations
for (DirContext altDirContext : altDirContexts) {
if (altDirContext instanceof BaseDirContext)
attrs = ((BaseDirContext) altDirContext).doGetAttributes(resourceName, attrIds);
else {
try {
attrs = altDirContext.getAttributes(name, attrIds);
} catch (NamingException ne) {
// Ignore
}
}
if (attrs != null)
return attrs;
}
// Really not found
throw new NameNotFoundException(
sm.getString("resources.notFound", name));
}
private Optional<String> lookupName(String name, Type type) throws NamingException {
DirContext ctx = new InitialDirContext();
Attributes attributes = ctx.getAttributes("dns:/" + name, new String[]{type.value});
Optional<Attribute> attribute = Optional.ofNullable(attributes.get(type.value));
if (attribute.isPresent()) {
return Optional.ofNullable(attribute.get().get()).map(Object::toString);
}
return Optional.empty();
}
private AttributeSchema createAttributeSchema(String name, DirContext schemaContext)
throws NamingException, ClassNotFoundException {
// Get the schema definition
Attributes attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + name);
String syntax = null;
while(syntax == null) {
Attribute syntaxAttribute = attributeSchema.get("SYNTAX");
if(syntaxAttribute != null) {
syntax = ((String)syntaxAttribute.get()).split("\\{")[0];
} else {
// Try to recursively retrieve syntax for super definition.
Attribute supAttribute = attributeSchema.get("SUP");
if(supAttribute == null) {
// Well, at least we tried
throw new IllegalArgumentException("Unable to get syntax definition for attribute " + name);
} else {
attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + supAttribute.get());
}
}
}
// Is it binary?
boolean isBinary=binarySet.contains(syntax);
// Use it to look up the required Java class
ClassInfo classInfo = syntaxToJavaClass.getClassInfo(syntax);
// Now we can set the java class
String javaClassName = null;
boolean isPrimitive = false;
boolean isArray = false;
if (classInfo!=null) {
javaClassName=classInfo.getClassName();
Class<?> javaClass=Class.forName(classInfo.getFullClassName());
javaClassName=javaClass.getSimpleName();
isPrimitive=javaClass.isPrimitive();
isArray=javaClass.isArray();
} else {
if (isBinary) {
javaClassName="byte[]";
isPrimitive=false;
isArray=true;
} else {
javaClassName="String";
isPrimitive=false;
isArray=false;
}
}
return new AttributeSchema(name, syntax,
attributeSchema.get("SINGLE-VALUE") == null,
isPrimitive, isBinary, isArray, javaClassName);
}
/**
* Get user name list from DN list.
*
* @param userListFromSearch
* @return
* @throws UserStoreException
*/
private List<String> getUserNamesFromDNList(List<String> userListFromSearch) throws UserStoreException {
List<String> userNameList = new ArrayList<>();
DirContext dirContext = this.connectionSource.getContext();
String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
String displayNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);
String[] requiredAttributes = {userNameProperty, displayNameAttribute};
for (String user : userListFromSearch) {
try {
String displayName = null;
String userName = null;
Attributes userAttributes = dirContext.getAttributes(escapeDNForSearch(user), requiredAttributes);
if (userAttributes != null) {
Attribute userNameAttribute = userAttributes.get(userNameProperty);
if (userNameAttribute != null) {
userName = (String) userNameAttribute.get();
}
if (StringUtils.isNotEmpty(displayNameAttribute)) {
Attribute displayAttribute = userAttributes.get(displayNameAttribute);
if (displayAttribute != null) {
displayName = (String) displayAttribute.get();
}
}
}
String domainName =
realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
/* Username will be null in the special case where the username attribute has changed to another
and having different userNameProperty than the current user-mgt.xml. */
if (userName != null) {
user = UserCoreUtil.getCombinedName(domainName, userName, displayName);
userNameList.add(user);
} else {
// Skip listing users which are not applicable to current user-mgt.xml
if (log.isDebugEnabled()) {
log.debug(String.format("User %s doesn't have the user name property %s", user,
userNameProperty));
}
}
} catch (NamingException e) {
log.error(String.format("Error in reading user information in the user store for the user %s, %s",
user, e.getMessage()));
throw new UserStoreException(e.getMessage(), e);
}
}
return userNameList;
}
@Override
public UserInfo doLookup(String searchId) throws Exception {
String query = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.identify");
if (query == null) return null;
DirContext ctx = null;
try {
ctx = getDirContext();
String idAttributeName = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.externalId","uid");
String loginAttributeName = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid");
Attributes attributes = ctx.getAttributes(query.replaceAll("%", searchId), new String[] {idAttributeName, loginAttributeName, "cn", "givenName", "sn", "mail"});
Attribute idAttribute = attributes.get(idAttributeName);
if (idAttribute == null) return null;
UserInfo user = new UserInfo();
user.setExternalId((String)idAttribute.get());
user.setUserName((String)attributes.get(loginAttributeName).get());
if (attributes.get("cn") != null)
user.setName((String)attributes.get("cn").get());
if (attributes.get("givenName") != null)
user.setFirstName((String)attributes.get("givenName").get());
if (attributes.get("cn") != null)
user.setName((String)attributes.get("cn").get());
if (attributes.get("sn") != null)
user.setLastName((String)attributes.get("sn").get());
if (attributes.get("mail") != null) {
user.setEmail((String)attributes.get("mail").get());
} else {
String email = user.getUserName() + "@";
for (String x: query.split(","))
if (x.startsWith("dc=")) email += (email.endsWith("@") ? "" : ".") + x.substring(3);
if (!email.endsWith("@")) user.setEmail(email);
}
return user;
} finally {
if (ctx != null) ctx.close();
}
}