Example usage for javax.naming.ldap LdapName getRdns

List of usage examples for javax.naming.ldap LdapName getRdns

Introduction

In this page you can find the example usage for javax.naming.ldap LdapName getRdns.

Prototype

public List<Rdn> getRdns() 

Source Link

Document

Retrieves the list of relative distinguished names.

Usage

From source file:org.apache.syncope.console.wicket.markup.html.form.preview.BinaryCertPreviewer.java

@Override
public Component preview() {
    final Label commonNameLabel = new Label("certCommonName", new Model<String>());
    final ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes);
    try {/*from w ww . j  ava  2s . c  o m*/
        final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(certificateStream);

        final StringBuilder commonNameBuilder = new StringBuilder("cn=");

        final LdapName ldapName = new LdapName(certificate.getIssuerDN().getName());

        for (Rdn rdn : ldapName.getRdns()) {
            if ("CN".equalsIgnoreCase(rdn.getType())) {
                commonNameBuilder
                        .append(rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString());
            }
        }
        commonNameLabel.setDefaultModelObject(commonNameBuilder.toString());
    } catch (Exception e) {
        LOG.error("Error evaluating certificate file", e);
        throw new IllegalArgumentException("Error evaluating certificate file", e);
    } finally {
        IOUtils.closeQuietly(certificateStream);
    }
    return this.add(commonNameLabel);
}

From source file:org.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java

private String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig) throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }//  w  ww  .j  a  va2  s  .co  m

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = this.getNameInSpaceForUserName(userName, ldapConfiguration);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, false);
    return list.toArray(new String[list.size()]);
}

From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java

private static String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig, DirContext ldapConnectionContext)
        throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }//  w  w  w .j  a v a 2 s . c  o  m

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = getNameInSpaceForUserName(userName, ldapAuthConfig, ldapConnectionContext);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty,
            ldapConnectionContext);
    return list.toArray(new String[list.size()]);
}

From source file:org.codehaus.plexus.redback.common.ldap.connection.LdapConnectionConfiguration.java

public LdapConnectionConfiguration(String hostname, int port, LdapName baseDn, String contextFactory,
        LdapName bindDn, String password, String authenticationMethod, Properties extraProperties)
        throws LdapException {
    this.hostname = hostname;

    this.port = port;

    if (baseDn != null) {
        this.baseDn = new LdapName(baseDn.getRdns());
    }/*from www. ja v  a  2  s.c o  m*/

    this.contextFactory = contextFactory;

    if (bindDn != null) {
        this.bindDn = new LdapName(bindDn.getRdns());
    }

    this.password = password;

    this.authenticationMethod = authenticationMethod;

    this.extraProperties = extraProperties;

    check();
}

From source file:org.dcm4che3.conf.dicom.ldap.LdapConfigUtils.java

public static List<Rdn> getNonBaseRdns(String dn, String baseDN) throws InvalidNameException {
    LdapName baseDnName = new LdapName(baseDN);
    LdapName name = new LdapName(dn);

    // ffd to the interesting part
    List<Rdn> rdns = new LinkedList<Rdn>(name.getRdns());
    List<Rdn> baseRdns = baseDnName.getRdns();

    return getNonBaseRdns(rdns, baseRdns);
}

From source file:org.glite.slcs.pki.bouncycastle.X509PrincipalUtil.java

/**
 * Creates a {@link X509Principal} with the given name.
 * <p>/*from   w w  w  .  j a v a2s  .co  m*/
 * In the <code>name</code> the RDNs, like <code>CN=B+CN=A</code>, will
 * be sorted alphabetically. Literal characters like <code>+</code>,
 * <code>=</code> must be escaped.
 * 
 * @param name
 *            The {@link X509Principal} name.
 * @return the {@link X509Principal}.
 * @throws GeneralSecurityException
 *             if an error occurs.
 */
public X509Principal createX509Principal(String name) throws GeneralSecurityException {
    Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>();
    Vector<Object> values = new Vector<Object>();
    Vector<Boolean> added = new Vector<Boolean>();
    start_ = false;
    try {
        LdapName ldapName = new LdapName(name);
        LOG.debug("RDNs: " + ldapName.getRdns());
        Rdn[] rdnArray = new Rdn[ldapName.getRdns().size()];
        ldapName.getRdns().toArray(rdnArray);
        for (int i = rdnArray.length - 1; i >= 0; i--) {
            readRdn(rdnArray[i], oids, values, added);
            start_ = false;
        }
        X509Principal principal = buildX509Principal(oids, values, added);
        return principal;
    } catch (Exception e) {
        // NamingException or IOException
        LOG.error("Fail to create X509Principal(" + name + ")", e);
        throw new GeneralSecurityException("Fail to create X509Principal(" + name + "): " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Simple helper that replaces ", " by "," in the provided dn and returns the lower case version of the result for
 * comparison purpose./*from  w  w  w.jav a  2s .com*/
 *
 * @param dn the raw unnormalized dn
 * @return lowercase version without whitespace after commas
 * @throws InvalidNameException
 */
protected static String pseudoNormalizeDn(String dn) throws InvalidNameException {
    LdapName ldapName = new LdapName(dn);
    List<String> rdns = new ArrayList<>();
    for (Rdn rdn : ldapName.getRdns()) {
        String value = rdn.getValue().toString().toLowerCase().replaceAll(",", "\\\\,");
        String rdnStr = rdn.getType().toLowerCase() + "=" + value;
        rdns.add(0, rdnStr);
    }
    return StringUtils.join(rdns, ',');
}

From source file:org.security4java.X509SubjectDnRetriever.java

public String getUserName(X509Certificate clientCert) {
    if (log.isDebugEnabled()) {
        log.debug("getUserName(X509Certificate) - start");
    }/*from ww  w.j  a  va 2s .c  o  m*/
    String subject = getSubjectDN(clientCert);
    String userName = null;

    if (subject != null) {
        if (log.isDebugEnabled()) {
            log.debug("Subject is [" + subject + "].");
        }
        if (subjectDnAttribute == null) {
            if (log.isDebugEnabled()) {
                log.debug("subjectDnAttribute is null, so return the whole subject.");
            }
            userName = subject;
        } else {
            boolean foundUserName = false;
            try {
                LdapName ldapName = new LdapName(subject);
                List<Rdn> list = ldapName.getRdns();
                if (list != null) {
                    for (Rdn rdn : list) {
                        String type = rdn.getType();
                        if (subjectDnAttribute.equalsIgnoreCase(type.toString())) {
                            Object value = rdn.getValue();
                            if (value instanceof String) {
                                userName = (String) value;
                                foundUserName = true;
                                if (log.isDebugEnabled()) {
                                    log.debug("Success to retreive userName [" + userName + "].");
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (InvalidNameException e) {
                log.info("subject [" + subject + "] is not valid name : [" + e.getMessage() + "].");
            }
            if (!foundUserName) {
                log.info("subject [" + subject + "] does not contain the required attribute ["
                        + subjectDnAttributeConfiguration + "]. Return the whole subject.");
                userName = subject;
            }
        }

    }

    if (log.isDebugEnabled()) {
        log.debug("getUserName(X509Certificate) - end; Ret is [" + userName + "].");
    }
    return userName;
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java

public Collection<String> getGroupNames(SearchResult sr) throws NamingException {
    Set<String> groupNames = new HashSet<String>();
    // group names in the current entry
    Attributes attrs = sr.getAttributes();
    Set<String> entryGroups = replaceWhitespace(getValues(attrs, Index.USER_GROUP));
    if (entryGroups != null) {
        groupNames.addAll(entryGroups);//from  ww w  .  j ava 2  s .  c o m
    }

    // group names found in distinguished name
    if (sr.isRelative()) {
        String name = sr.getName();
        LdapName ldapName = new LdapName(name);
        List<Rdn> rdns = ldapName.getRdns();
        for (Rdn rdn : rdns) {
            Attributes rdnsAttributes = rdn.toAttributes();
            Set<String> rdnsGroups = replaceWhitespace(getValues(rdnsAttributes, Index.USER_GROUP));
            if (rdnsGroups != null) {
                groupNames.addAll(rdnsGroups);
            }

        }
    }
    //only if there is no already defined group, add the default user group
    if (groupNames.isEmpty()) {
        String defaultGroupName = getAttrMap().getDefaultGroupName();
        if (defaultGroupName != null) {
            groupNames.add(defaultGroupName);
        }
    }
    return groupNames;
}

From source file:org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.MutualSSLAuthenticator.java

/**
 * To set the authentication context in current message context.
 *
 * @param messageContext Relevant message context.
 * @param sslCertObject  SSL certificate object.
 * @throws APISecurityException API Security Exception.
 *///from ww w  . j av  a 2 s .c o  m
private void setAuthContext(MessageContext messageContext, Object sslCertObject) throws APISecurityException {

    X509Certificate[] certs = (X509Certificate[]) sslCertObject;
    X509Certificate x509Certificate = certs[0];
    String subjectDN = x509Certificate.getSubjectDN().getName();
    String uniqueIdentifier = String
            .valueOf(x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN())
            .replaceAll(",", "#").replaceAll("\"", "'").trim();
    String tier = certificates.get(uniqueIdentifier);
    if (StringUtils.isEmpty(tier)) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "The client certificate presented is available in gateway, however it was not added against "
                            + "the API " + getAPIIdentifier(messageContext));
        }
        throw new APISecurityException(APISecurityConstants.MUTUAL_SSL_VALIDATION_FAILURE,
                APISecurityConstants.MUTUAL_SSL_VALIDATION_FAILURE_MESSAGE);
    }
    AuthenticationContext authContext = new AuthenticationContext();
    authContext.setAuthenticated(true);
    authContext.setUsername(subjectDN);
    try {
        LdapName ldapDN = new LdapName(subjectDN);
        for (Rdn rdn : ldapDN.getRdns()) {
            if (APIConstants.CERTIFICATE_COMMON_NAME.equalsIgnoreCase(rdn.getType())) {
                authContext.setUsername((String) rdn.getValue());
            }
        }
    } catch (InvalidNameException e) {
        log.warn("Cannot get the CN name from certificate:" + e.getMessage() + ". Please make sure the "
                + "certificate to include a proper common name that follows naming convention.");
        authContext.setUsername(subjectDN);
    }
    authContext.setApiTier(apiLevelPolicy);
    APIIdentifier apiIdentifier = getAPIIdentifier(messageContext);
    authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
    authContext.setStopOnQuotaReach(true);
    authContext.setApiKey(uniqueIdentifier + "_" + apiIdentifier.toString());
    authContext.setTier(tier);
    /* For the mutual SSL based authenticated request, the resource level throttling is not considered, hence
    assigning the unlimited tier for that. */
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setThrottling(APIConstants.UNLIMITED_TIER);
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    if (log.isDebugEnabled()) {
        log.debug("Auth context for the API " + getAPIIdentifier(messageContext) + ": Username["
                + authContext.getUsername() + "APIKey[(" + authContext.getApiKey() + "] Tier["
                + authContext.getTier() + "]");
    }
    APISecurityUtils.setAuthenticationContext(messageContext, authContext, null);
}