下面列出了怎么用javax.naming.ldap.Rdn的API类实例代码及写法,或者点击链接到github查看源代码。
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
/**
* Returns Subject DN from X509Certificate
*
* @param cert
* @return Subject DN as a user name
*/
@Override
public String getUserName(Certificate cert) {
X509Certificate certificate = (X509Certificate) cert;
String dn = certificate.getSubjectDN().getName();
LdapName ldapDn = getLdapName(dn);
if (key == null) {
throw new IllegalArgumentException("Must set a key");
}
for (Rdn rdn : ldapDn.getRdns()) {
if (key.equalsIgnoreCase(rdn.getType())) {
return (String)rdn.getValue();
}
}
throw new IllegalArgumentException("No " + key + " key found in certificate DN: " + dn);
}
/**
* Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
*
* Example:
*
* CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
* CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
* CN=test1, O=testOrg, C=US compared to -> false
* compared to -> true
*
* @param dn1 the first DN to compare
* @param dn2 the second DN to compare
* @return true if the DNs are equivalent, false otherwise
*/
public static boolean compareDNs(String dn1, String dn2) {
if (dn1 == null) {
dn1 = "";
}
if (dn2 == null) {
dn2 = "";
}
if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
return dn1.equals(dn2);
}
try {
List<Rdn> rdn1 = new LdapName(dn1).getRdns();
List<Rdn> rdn2 = new LdapName(dn2).getRdns();
return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
} catch (InvalidNameException e) {
logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
return false;
}
}
/**
* Extract rdn value from username
* @param dn distinguished name or username
* @return username
*/
private String extractRdnValue(String dn) throws IOException {
if (dn.startsWith("uid=")) {
String rdn = dn;
if (rdn.indexOf(',') > 0) {
rdn = rdn.substring(0, rdn.indexOf(','));
}
try {
return (String) new Rdn(rdn).getValue();
} catch (InvalidNameException e) {
throw new IOException(e);
}
} else {
return dn;
}
}
public void testLdapDnAuthentication() throws NamingException {
String dn = new Rdn("uid", Settings.getProperty("davmail.username"))+",ou=people";
Hashtable<String, String> env = new Hashtable<>();
//env.put("java.naming.security.authentication", "CRAM-MD5");
env.put("java.naming.security.authentication", "simple");
env.put("java.naming.security.principal", dn);
env.put("java.naming.security.credentials", Settings.getProperty("davmail.password"));
env.put("com.sun.jndi.ldap.connect.pool", "true");
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.provider.url", "ldap://127.0.0.1:" + Settings.getIntProperty("davmail.ldapPort"));
env.put("java.naming.referral", "follow");
new InitialLdapContext(env, null);
}
/**
* Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
*
* Example:
*
* CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
* CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
* CN=test1, O=testOrg, C=US compared to -> false
* compared to -> true
*
* @param dn1 the first DN to compare
* @param dn2 the second DN to compare
* @return true if the DNs are equivalent, false otherwise
*/
public static boolean compareDNs(String dn1, String dn2) {
if (dn1 == null) {
dn1 = "";
}
if (dn2 == null) {
dn2 = "";
}
if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
return dn1.equals(dn2);
}
try {
List<Rdn> rdn1 = new LdapName(dn1).getRdns();
List<Rdn> rdn2 = new LdapName(dn2).getRdns();
return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
} catch (InvalidNameException e) {
logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
return false;
}
}
/**
* Attempts to normalize a DN by taking it and reversing the components if it
* doesn't start with CN. Some systems requires the DN components be in a
* specific order, or that order reversed. We cannot arbitrarily reorder the
* components however, e.g., sorting them.
*/
public static String normalizeDN(String userName) {
String normalizedUserName = userName.trim().toLowerCase();
try {
if (!normalizedUserName.startsWith("cn") || Pattern.compile(",[^ ]").matcher(normalizedUserName).find()) {
LdapName name = new LdapName(userName);
StringBuilder sb = new StringBuilder();
ArrayList<Rdn> rdns = new ArrayList<>(name.getRdns());
if (rdns.size() > 0 && !rdns.get(0).toString().toLowerCase().startsWith("cn"))
Collections.reverse(rdns);
for (Rdn rdn : rdns) {
if (sb.length() > 0)
sb.append(", ");
sb.append(rdn.toString());
}
normalizedUserName = sb.toString().toLowerCase();
}
} catch (InvalidNameException e) {
// ignore -- might be a sid rather than a DN
}
log.trace("Normalized [" + userName + "] into [" + normalizedUserName + "]");
return normalizedUserName;
}
private LdapEntry parseRole(String dn, String groupNameAttribute, URI groupReferralAddress) {
try {
LdapName ldapName = new LdapName(Rdn.unescapeValue(dn).toString());
for (int i = ldapName.size() - 1; i >= 0; i--) {
String rdnString = ldapName.get(i);
Rdn rdn = new Rdn(rdnString);
Attribute attr = rdn.toAttributes().get(groupNameAttribute);
if (attr != null) {
Object value = attr.get();
if (value != null) {
return new LdapEntry( (value instanceof byte[]) ? new String((byte[]) value, StandardCharsets.UTF_8) : value.toString(), dn, groupReferralAddress);
}
}
}
} catch (NamingException e) {
SECURITY_LOGGER.tracef("Unable to parse role from DN (%s): %s", dn, e.getMessage());
}
return null;
}
private static String extractCN(String subjectDN) {
/*
* Get commonName using LdapName API
* The DN of X509 certificates are in rfc2253 format. Ldap uses the same format.
*
* Doesn't use X500Name because it's internal API
*/
try {
LdapName ldapName = new LdapName(subjectDN);
for (Rdn rdn : ldapName.getRdns()) {
if ("CN".equalsIgnoreCase(rdn.getType())) {
return rdn.getValue().toString();
}
}
throw new RuntimeException("Could not extract commonName from certificate subjectDN: " + subjectDN);
} catch (InvalidNameException e) {
throw new RuntimeException("Could not extract commonName from certificate", e);
}
}
public static String extractCnFromDn(String dn) {
String cn = null;
try {
LdapName ldapName = new LdapName(dn);
for (Rdn rdn : ldapName.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
cn = (String) rdn.getValue();
}
}
} catch (InvalidNameException e) {
throw new IllegalArgumentException("Invalid DN: " + dn, e);
}
if (cn == null) {
throw new IllegalArgumentException("Can't find CN in DN: " + dn);
}
return cn;
}
private static String extractCommonName(String principal) throws SSLException {
if (principal == null) {
return null;
}
try {
LdapName ldapName = new LdapName(principal);
for (Rdn rdn : ldapName.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
Object obj = rdn.getValue();
if (obj != null) {
return obj.toString();
}
}
}
return null;
} catch (InvalidNameException e) {
throw new SSLException("DN value \"" + principal + "\" is invalid");
}
}
/**
* Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
* <p>
* Example:
* <p>
* CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
* CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
* CN=test1, O=testOrg, C=US compared to -> false
* compared to -> true
*
* @param dn1 the first DN to compare
* @param dn2 the second DN to compare
* @return true if the DNs are equivalent, false otherwise
*/
public static boolean compareDNs(String dn1, String dn2) {
if (dn1 == null) {
dn1 = "";
}
if (dn2 == null) {
dn2 = "";
}
if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
return dn1.equals(dn2);
}
try {
List<Rdn> rdn1 = new LdapName(dn1).getRdns();
List<Rdn> rdn2 = new LdapName(dn2).getRdns();
return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
} catch (InvalidNameException e) {
logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
return false;
}
}
/**
* Find an the info from the cert chain provided. <code>null</code> if none found
*/
protected String findCertInfo(X509Certificate[] x509certificates) throws NamingException {
if (x509certificates != null && x509certificates.length != 0) {
// Only ever use the first certificate, as this si the client supplied one.
// Further ones are trust stores and CAs that have signed the first cert.
Principal subject = x509certificates[0].getSubjectDN();
if (subject != null && subject.getName() != null) {
List<Rdn> rdns;
try {
rdns = new LdapName(subject.getName()).getRdns();
}
catch (InvalidNameException ine) {
return null;
}
return certInfoExtractor.extractCertInfo(rdns);
}
}
return null;
}
public DNCacheEntry( Rdn[] userRDN, LdapName baseDN )
{
if ( userRDN == null ) {
throw new IllegalArgumentException("Argument 'userRDN' cannot be null.");
}
if ( baseDN == null ) {
throw new IllegalArgumentException("Argument 'baseDN' cannot be null.");
}
this.userRDN = userRDN;
this.baseDN = baseDN;
}
/**
* Maps a distinguished name (RFC 2253) to a fully qualified domain name.
* Processes a sequence of RDNs having a DC attribute.
* The special RDN "DC=." denotes the root of the domain tree.
* Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
* RDN "DC=." all reset the domain name and processing continues.
*
* @param dn A string distinguished name (RFC 2253).
* @return A domain name or null if none can be derived.
* @throw InvalidNameException If the distinugished name is invalid.
*/
static String mapDnToDomainName(String dn) throws InvalidNameException {
if (dn == null) {
return null;
}
StringBuffer domain = new StringBuffer();
LdapName ldapName = new LdapName(dn);
// process RDNs left-to-right
//List<Rdn> rdnList = ldapName.getRdns();
List<Rdn> rdnList = ldapName.getRdns();
for (int i = rdnList.size() - 1; i >= 0; i--) {
//Rdn rdn = rdnList.get(i);
Rdn rdn = rdnList.get(i);
// single-valued RDN with a DC attribute
if ((rdn.size() == 1) &&
("dc".equalsIgnoreCase(rdn.getType()) )) {
Object attrval = rdn.getValue();
if (attrval instanceof String) {
if (attrval.equals(".") ||
(domain.length() == 1 && domain.charAt(0) == '.')) {
domain.setLength(0); // reset (when current or previous
// RDN value is "DC=.")
}
if (domain.length() > 0) {
domain.append('.');
}
domain.append(attrval);
} else {
domain.setLength(0); // reset (when binary-valued attribute)
}
} else {
domain.setLength(0); // reset (when multi-valued RDN or non-DC)
}
}
return (domain.length() != 0) ? domain.toString() : null;
}
static void printEscapedVal(Object[] values) {
String escVal;
for (int i = 0; i < values.length; i++) {
escVal = Rdn.escapeValue(values[i]);
System.out.println("Orig val: " + values[i] +
" Escaped val: " + escVal);
}
}
@Override
public String extractPrincipal(final X509Certificate x509Certificate, final Type type) {
if (x509Certificate == null) {
return null;
}
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
String dnString = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
final X500Principal principal = x509Certificate.getSubjectX500Principal();
return principal.toString();
}
});
//remove whitespaces
try {
final LdapName ln = new LdapName(dnString);
final List<Rdn> rdns = new ArrayList<>(ln.getRdns());
Collections.reverse(rdns);
dnString = String.join(",", rdns.stream().map(r->r.toString()).collect(Collectors.toList()));
} catch (InvalidNameException e) {
log.error("Unable to parse: {}",dnString, e);
}
if(log.isTraceEnabled()) {
log.trace("principal: {}", dnString);
}
return dnString;
}
/**
* Maps a distinguished name (RFC 2253) to a fully qualified domain name.
* Processes a sequence of RDNs having a DC attribute.
* The special RDN "DC=." denotes the root of the domain tree.
* Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
* RDN "DC=." all reset the domain name and processing continues.
*
* @param dn A string distinguished name (RFC 2253).
* @return A domain name or null if none can be derived.
* @throw InvalidNameException If the distinugished name is invalid.
*/
static String mapDnToDomainName(String dn) throws InvalidNameException {
if (dn == null) {
return null;
}
StringBuffer domain = new StringBuffer();
LdapName ldapName = new LdapName(dn);
// process RDNs left-to-right
//List<Rdn> rdnList = ldapName.getRdns();
List<Rdn> rdnList = ldapName.getRdns();
for (int i = rdnList.size() - 1; i >= 0; i--) {
//Rdn rdn = rdnList.get(i);
Rdn rdn = rdnList.get(i);
// single-valued RDN with a DC attribute
if ((rdn.size() == 1) &&
("dc".equalsIgnoreCase(rdn.getType()) )) {
Object attrval = rdn.getValue();
if (attrval instanceof String) {
if (attrval.equals(".") ||
(domain.length() == 1 && domain.charAt(0) == '.')) {
domain.setLength(0); // reset (when current or previous
// RDN value is "DC=.")
}
if (domain.length() > 0) {
domain.append('.');
}
domain.append(attrval);
} else {
domain.setLength(0); // reset (when binary-valued attribute)
}
} else {
domain.setLength(0); // reset (when multi-valued RDN or non-DC)
}
}
return (domain.length() != 0) ? domain.toString() : null;
}
static void printEscapedVal(Object[] values) {
String escVal;
for (int i = 0; i < values.length; i++) {
escVal = Rdn.escapeValue(values[i]);
System.out.println("Orig val: " + values[i] +
" Escaped val: " + escVal);
}
}
/**
* Maps a distinguished name (RFC 2253) to a fully qualified domain name.
* Processes a sequence of RDNs having a DC attribute.
* The special RDN "DC=." denotes the root of the domain tree.
* Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
* RDN "DC=." all reset the domain name and processing continues.
*
* @param dn A string distinguished name (RFC 2253).
* @return A domain name or null if none can be derived.
* @throw InvalidNameException If the distinugished name is invalid.
*/
static String mapDnToDomainName(String dn) throws InvalidNameException {
if (dn == null) {
return null;
}
StringBuffer domain = new StringBuffer();
LdapName ldapName = new LdapName(dn);
// process RDNs left-to-right
//List<Rdn> rdnList = ldapName.getRdns();
List<Rdn> rdnList = ldapName.getRdns();
for (int i = rdnList.size() - 1; i >= 0; i--) {
//Rdn rdn = rdnList.get(i);
Rdn rdn = rdnList.get(i);
// single-valued RDN with a DC attribute
if ((rdn.size() == 1) &&
("dc".equalsIgnoreCase(rdn.getType()) )) {
Object attrval = rdn.getValue();
if (attrval instanceof String) {
if (attrval.equals(".") ||
(domain.length() == 1 && domain.charAt(0) == '.')) {
domain.setLength(0); // reset (when current or previous
// RDN value is "DC=.")
}
if (domain.length() > 0) {
domain.append('.');
}
domain.append(attrval);
} else {
domain.setLength(0); // reset (when binary-valued attribute)
}
} else {
domain.setLength(0); // reset (when multi-valued RDN or non-DC)
}
}
return (domain.length() != 0) ? domain.toString() : null;
}
static void printEscapedVal(Object[] values) {
String escVal;
for (int i = 0; i < values.length; i++) {
escVal = Rdn.escapeValue(values[i]);
System.out.println("Orig val: " + values[i] +
" Escaped val: " + escVal);
}
}
private static String[] getComponents(String dn, String componentName) {
componentName = componentName.toUpperCase();
ArrayList<String> components = new ArrayList<String>();
try {
LdapName name = new LdapName(dn);
for (Rdn rdn : name.getRdns()) {
if (componentName.equals(rdn.getType().toUpperCase())) {
components.add(String.valueOf(rdn.getValue()));
}
}
} catch (InvalidNameException e) {
// ignore -- invalid name, so can't find components
}
return components.toArray(new String[0]);
}
/**
*
* @see <a href="https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java>https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java</a>
*/
public static Set<String> parse( String distinguishedName, String identifier ) throws Exception
{
final Set<String> result = new HashSet<>();
final LdapName ln = new LdapName( distinguishedName);
for( final Rdn rdn : ln.getRdns() )
{
if( rdn.getType().equalsIgnoreCase( identifier ) )
{
result.add( rdn.getValue().toString() );
}
}
return result;
}
public Name getTemporaryName(Name originalName) {
LdapName temporaryName = LdapUtils.newLdapName(originalName);
// Add tempSuffix to the leaf node name.
try {
String leafNode = (String) temporaryName.remove(temporaryName.size() - 1);
temporaryName.add(new Rdn(leafNode + tempSuffix));
} catch (InvalidNameException e) {
throw new org.springframework.ldap.InvalidNameException(e);
}
return temporaryName;
}
static String[] extractCNs(final String subjectPrincipal) throws SSLException {
if (subjectPrincipal == null) {
return null;
}
final List<String> cns = new ArrayList<String>();
try {
final LdapName subjectDN = new LdapName(subjectPrincipal);
final List<Rdn> rdns = subjectDN.getRdns();
for (int i = rdns.size() - 1; i >= 0; i--) {
final Rdn rds = rdns.get(i);
final Attributes attributes = rds.toAttributes();
final Attribute cn = attributes.get("cn");
if (cn != null) {
try {
final Object value = cn.get();
if (value != null) {
cns.add(value.toString());
}
} catch (NamingException ignore) {
}
}
}
} catch (InvalidNameException e) {
throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
}
return cns.isEmpty() ? null : cns.toArray(new String[ cns.size() ]);
}
public static LdapName createNewAbsolute( LdapName base, Rdn[] relative )
{
final LdapName result = (LdapName) base.clone();
for (int i = relative.length - 1; i >= 0; i--) {
result.add(relative[i]);
}
return result;
}