Example usage for javax.security.auth.kerberos KerberosPrincipal getName

List of usage examples for javax.security.auth.kerberos KerberosPrincipal getName

Introduction

In this page you can find the example usage for javax.security.auth.kerberos KerberosPrincipal getName.

Prototype

public String getName() 

Source Link

Document

The returned string corresponds to the single-string representation of a Kerberos Principal name as specified in Section 2.1 of <a href=http://www.ietf.org/rfc/rfc1964.txt>RFC 1964</a>.

Usage

From source file:ddf.security.sts.claimsHandler.AttributeMapLoader.java

/**
 * Obtains the user name from the principal.
 *
 * @param principal Describing the current user that should be used for retrieving claims.
 * @return the user name if the principal has one, null if no name is specified or if principal
 * is null.//w  w w  .  j  ava2  s  .  c o m
 */
public static String getUser(Principal principal) {
    String user = null;
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        st = new StringTokenizer(st.nextToken(), "/");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        StringTokenizer st = new StringTokenizer(x500p.getName(), ",");
        while (st.hasMoreElements()) {
            // token is in the format:
            // syntaxAndUniqueId
            // cn
            // ou
            // o
            // loc
            // state
            // country
            String[] strArr = st.nextToken().split("=");
            if (strArr.length > 1 && strArr[0].equalsIgnoreCase("cn")) {
                user = strArr[1];
                break;
            }
        }
    } else if (principal != null) {
        user = principal.getName();
    }

    return user;
}

From source file:com.buaa.cfs.utils.SecurityUtil.java

/**
 * TGS must have the server principal of the form "krbtgt/FOO@FOO".
 *
 * @param principal/*from  w  w  w  . ja  va2 s  .c o m*/
 *
 * @return true or false
 */
static boolean isTGSPrincipal(KerberosPrincipal principal) {
    if (principal == null)
        return false;
    if (principal.getName().equals("krbtgt/" + principal.getRealm() + "@" + principal.getRealm())) {
        return true;
    }
    return false;
}

From source file:ddf.security.sts.SecurityAttributesClaimsHandler.java

/**
 * @param parameters/*from w  w  w.j a  v a 2s. com*/
 * @param claimsColl
 * @param principal
 * @return
 */
private String getUserFromClaimsParameters(ClaimsParameters parameters) {
    Principal principal = parameters.getPrincipal();
    String user = null;
    if (parameters.getAdditionalProperties() != null
            && parameters.getAdditionalProperties().containsKey(WSConstants.USERNAME_LN)) {
        user = (String) parameters.getAdditionalProperties().get(WSConstants.USERNAME_LN);
    } else {
        if (principal instanceof KerberosPrincipal) {
            KerberosPrincipal kp = (KerberosPrincipal) principal;
            StringTokenizer st = new StringTokenizer(kp.getName(), "@");
            user = st.nextToken();
        } else if (principal instanceof X500Principal) {
            // 1.2.840.113549.1.9.1=#160d69346365406c6d636f2e636f6d,CN=client,OU=I4CE,O=Lockheed
            // Martin,L=Goodyear,ST=Arizona,C=US
            X500Principal xp = (X500Principal) principal;
            StringTokenizer st = new StringTokenizer(xp.getName(), ",");
            @SuppressWarnings("unused")
            String syntaxAndUniqueId = st.nextToken();
            String cn = st.nextToken();
            // String ou = st.nextToken();
            // String o = st.nextToken();
            // String loc = st.nextToken();
            // String state = st.nextToken();
            // String country = st.nextToken();

            StringTokenizer userTokenizer = new StringTokenizer(cn, "=");
            // String cnKey = userTokenizer.nextToken();
            user = userTokenizer.nextToken();
        } else if (principal != null) {
            user = principal.getName();
        } else {
            LOGGER.warn("Principal is null");
        }
    }

    return user;
}

From source file:org.apache.cxf.sts.claims.LdapClaimsHandler.java

public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    String user = null;//from ww w. ja  v a  2s .co  m
    boolean useLdapLookup = false;

    Principal principal = parameters.getPrincipal();
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        LOG.warning("Unsupported principal type X500: " + x500p.getName());
        return new ProcessedClaimCollection();
    } else if (principal != null) {
        user = principal.getName();
        if (user == null) {
            LOG.warning("User must not be null");
            return new ProcessedClaimCollection();
        }
        useLdapLookup = LdapUtils.isDN(user);

    } else {
        LOG.warning("Principal is null");
        return new ProcessedClaimCollection();
    }

    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Retrieve claims for user " + user);
    }

    Map<String, Attribute> ldapAttributes = null;
    if (useLdapLookup) {
        AttributesMapper mapper = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<String, Attribute>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

        Object result = ldap.lookup(user, mapper);
        ldapAttributes = CastUtils.cast((Map<?, ?>) result);
    } else {
        List<String> searchAttributeList = new ArrayList<String>();
        for (Claim claim : claims) {
            if (getClaimsLdapAttributeMapping().keySet().contains(claim.getClaimType().toString())) {
                searchAttributeList.add(getClaimsLdapAttributeMapping().get(claim.getClaimType().toString()));
            } else {
                if (LOG.isLoggable(Level.FINER)) {
                    LOG.finer("Unsupported claim: " + claim.getClaimType());
                }
            }
        }

        String[] searchAttributes = null;
        searchAttributes = searchAttributeList.toArray(new String[searchAttributeList.size()]);

        ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, this.userBaseDn, this.getObjectClass(),
                this.getUserNameAttribute(), user, searchAttributes);
    }

    if (ldapAttributes == null || ldapAttributes.size() == 0) {
        //No result
        if (LOG.isLoggable(Level.INFO)) {
            LOG.finest("User '" + user + "' not found");
        }
        return new ProcessedClaimCollection();
    }

    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();

    for (Claim claim : claims) {
        URI claimType = claim.getClaimType();
        String ldapAttribute = getClaimsLdapAttributeMapping().get(claimType.toString());
        Attribute attr = ldapAttributes.get(ldapAttribute);
        if (attr == null) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("Claim '" + claim.getClaimType() + "' is null");
            }
        } else {
            ProcessedClaim c = new ProcessedClaim();
            c.setClaimType(claimType);
            c.setPrincipal(principal);

            StringBuilder claimValue = new StringBuilder();
            try {
                NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll();
                while (list.hasMore()) {
                    Object obj = list.next();
                    if (!(obj instanceof String)) {
                        LOG.warning("LDAP attribute '" + ldapAttribute + "' has got an unsupported value type");
                        break;
                    }
                    String itemValue = (String) obj;
                    if (this.isX500FilterEnabled()) {
                        try {
                            X500Principal x500p = new X500Principal(itemValue);
                            itemValue = x500p.getName();
                            int index = itemValue.indexOf('=');
                            itemValue = itemValue.substring(index + 1, itemValue.indexOf(',', index));
                        } catch (Exception ex) {
                            //Ignore, not X500 compliant thus use the whole string as the value
                        }
                    }
                    claimValue.append(itemValue);
                    if (list.hasMore()) {
                        claimValue.append(this.getDelimiter());
                    }
                }
            } catch (NamingException ex) {
                LOG.warning("Failed to read value of LDAP attribute '" + ldapAttribute + "'");
            }

            c.addValue(claimValue.toString());
            // c.setIssuer(issuer);
            // c.setOriginalIssuer(originalIssuer);
            // c.setNamespace(namespace);
            claimsColl.add(c);
        }
    }

    return claimsColl;
}

From source file:org.apache.cxf.sts.claims.LdapGroupClaimsHandler.java

public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {

    boolean found = false;
    for (Claim claim : claims) {
        if (claim.getClaimType().toString().equals(this.groupURI)) {
            found = true;/*from  w  ww.ja  v a  2  s.c  o m*/
            break;
        }
    }
    if (!found) {
        return new ProcessedClaimCollection();
    }

    String user = null;

    Principal principal = parameters.getPrincipal();
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        LOG.warning("Unsupported principal type X500: " + x500p.getName());
    } else if (principal != null) {
        user = principal.getName();
        if (user == null) {
            LOG.warning("Principal name must not be null");
        }
    } else {
        LOG.warning("Principal is null");
    }
    if (user == null) {
        return new ProcessedClaimCollection();
    }

    if (!LdapUtils.isDN(user)) {
        Name dn = LdapUtils.getDnOfEntry(ldap, this.userBaseDn, this.getUserObjectClass(),
                this.getUserNameAttribute(), user);
        if (dn != null) {
            user = dn.toString();
            LOG.fine("DN for (" + this.getUserNameAttribute() + "=" + user + ") found: " + user);
        } else {
            LOG.warning("DN not found for user '" + user + "'");
            return new ProcessedClaimCollection();
        }
    }

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("Retrieve groups for user " + user);
    }

    List<String> groups = null;
    groups = LdapUtils.getAttributeOfEntries(ldap, this.groupBaseDn, this.getGroupObjectClass(),
            this.groupMemberAttribute, user, "cn");

    if (groups == null || groups.size() == 0) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("No groups found for user '" + user + "'");
        }
        return new ProcessedClaimCollection();
    }

    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Groups for user '" + parameters.getPrincipal().getName() + "': " + groups);
    }

    String scope = null;
    if (getAppliesToScopeMapping() != null && getAppliesToScopeMapping().size() > 0
            && parameters.getAppliesToAddress() != null) {
        scope = getAppliesToScopeMapping().get(parameters.getAppliesToAddress());
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("AppliesTo matchs with scope: " + scope);
        }
    }

    String regex = this.groupNameGlobalFilter;
    regex = regex.replaceAll(ROLE, ".*");
    Pattern globalPattern = Pattern.compile(regex);

    //If AppliesTo value can be mapped to a Scope Name
    //ex. https://localhost/doubleit/services/doubleittransport  -> Demo
    Pattern scopePattern = null;
    if (scope != null) {
        regex = this.groupNameScopedFilter;
        regex = regex.replaceAll(SCOPE, scope).replaceAll(ROLE, ".*");
        scopePattern = Pattern.compile(regex);
    }

    List<String> filteredGroups = new ArrayList<String>();
    for (String group : groups) {
        if (scopePattern != null && scopePattern.matcher(group).matches()) {
            //Group matches the scoped filter
            //ex. (default groupNameScopeFilter)
            //  Demo_User -> Role=User
            //  Demo_Admin -> Role=Admin
            String filter = this.groupNameScopedFilter;
            String role = null;
            if (isUseFullGroupNameAsValue()) {
                role = group;
            } else {
                role = parseRole(group, filter.replaceAll(SCOPE, scope));
            }
            filteredGroups.add(role);
        } else {
            if (globalPattern.matcher(group).matches()) {
                //Group matches the global filter
                //ex. (default groupNameGlobalFilter)
                //  User -> Role=User
                //  Admin -> Role=Admin
                String role = null;
                if (isUseFullGroupNameAsValue()) {
                    role = group;
                } else {
                    role = parseRole(group, this.groupNameGlobalFilter);
                }
                filteredGroups.add(role);
            } else {
                LOG.finer("Group '" + group + "' doesn't match scoped and global group filter");
            }
        }
    }

    LOG.info("Filtered groups: " + filteredGroups);
    if (filteredGroups.size() == 0) {
        LOG.info("No matching groups found for user '" + principal + "'");
        return new ProcessedClaimCollection();
    }

    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
    ProcessedClaim c = new ProcessedClaim();
    c.setClaimType(URI.create(this.groupURI));
    c.setPrincipal(principal);
    c.setValues(new ArrayList<Object>(filteredGroups));
    // c.setIssuer(issuer);
    // c.setOriginalIssuer(originalIssuer);
    // c.setNamespace(namespace);
    claimsColl.add(c);

    return claimsColl;
}

From source file:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java

/**
 * Finish the authentication process successfully.
 * // w  ww.j  a v a  2  s.co  m
 * <p>Sets the attribute {@link ExternalAuthentication#SUBJECT_KEY}.</p>
 * 
 * @param key the conversation key
 * @param httpRequest the HTTP request
 * @param httpResponse the HTTP response
 * @param kerberosPrincipal the Kerberos principal to return
 * 
 * @throws IOException 
 * @throws ExternalAuthenticationException 
 */
private void finishWithSuccess(@Nonnull @NotEmpty final String key,
        @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse,
        @Nonnull final KerberosPrincipal kerberosPrincipal)
        throws ExternalAuthenticationException, IOException {

    // Store the user as a username and as a real KerberosPrincipal object.
    final Subject subject = new Subject();
    subject.getPrincipals().add(new UsernamePrincipal(kerberosPrincipal.getName()));
    subject.getPrincipals().add(kerberosPrincipal);

    // Finish the external authentication task and return to the flow.
    httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);
    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Create a UserGroupInformation from a Subject with Kerberos principal.
 *
 * @throws IOException if the kerberos login fails
 *///  ww  w  . ja v  a 2 s .co m
public static UserGroupInformation getUGIFromSubject(Subject subject) throws IOException {
    if (subject == null) {
        throw new IOException("Subject must not be null");
    }

    if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) {
        throw new IOException("Provided Subject must contain a KerberosPrincipal");
    }

    KerberosPrincipal principal = subject.getPrincipals(KerberosPrincipal.class).iterator().next();

    User ugiUser = new User(principal.getName(), AuthenticationMethod.KERBEROS, null);
    subject.getPrincipals().add(ugiUser);
    UserGroupInformation ugi = new UserGroupInformation(subject);
    ugi.setLogin(null);
    ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    return ugi;
}

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Get the Kerberos TGT//from w w w .  j  a  v a  2s  .com
 * @return the user's TGT or null if none was found
 */
private synchronized KerberosTicket getTGT() {
    Set<KerberosTicket> tickets = subject.getPrivateCredentials(KerberosTicket.class);
    for (KerberosTicket ticket : tickets) {
        KerberosPrincipal server = ticket.getServer();
        if (server.getName().equals("krbtgt/" + server.getRealm() + "@" + server.getRealm())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found tgt " + ticket);
            }
            return ticket;
        }
    }
    return null;
}

From source file:org.apache.nifi.security.krb.AbstractKerberosUser.java

/**
 * TGS must have the server principal of the form "krbtgt/FOO@FOO".
 *
 * @param principal the principal to check
 * @return true if the principal is the TGS, false otherwise
 *//*from  www .  j  a v  a 2  s.co  m*/
private boolean isTGSPrincipal(final KerberosPrincipal principal) {
    if (principal == null) {
        return false;
    }

    if (principal.getName().equals("krbtgt/" + principal.getRealm() + "@" + principal.getRealm())) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Found TGT principal: " + principal.getName());
        }
        return true;
    }

    return false;
}