Example usage for java.security Principal toString

List of usage examples for java.security Principal toString

Introduction

In this page you can find the example usage for java.security Principal toString.

Prototype

public String toString();

Source Link

Document

Returns a string representation of this principal.

Usage

From source file:Main.java

/**
 * Notice that,/*from  w  ww.j ava 2  s . c o  m*/
 * If we split the signature string with ", ",
 * a value (like "Google, Inc") may be broke up unexpectedly.
 * So we check "=" at the same time.
 * (AppXplore v2.5.0 makes a mistake, too.)
 *
 * An example from Google Pinyin Input:
 *     CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
 */
public static String analyseSignature(Principal principal, String str_nl) {
    //The result of principal.toString() is like this "x, x, x";
    StringBuilder stringBuilder = new StringBuilder(principal.toString().replaceAll(", ", str_nl));

    int index1 = 0;
    int index2;
    while (index1 >= 0) {
        if ((index2 = stringBuilder.indexOf(str_nl, index1)) < 0) {
            break;
        }
        if (!stringBuilder.substring(index1, index2).contains("=")) {
            stringBuilder.replace(index1 - str_nl.length(), index1, ", ");
        }
        index1 = stringBuilder.indexOf(str_nl, index1) + str_nl.length();
    }

    return stringBuilder.toString();
}

From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java

/**
 * Show details of an X509 certificate, printing the information to STDOUT.
 *
 * @param cert the certificate to be displayed
 *//*from   w  w w. j  a  v a2s.  co  m*/
public void displayCertificate(X509Certificate cert) {
    if (cert == null) {
        return;
    }
    logger.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    Principal issuerDN = cert.getIssuerDN();
    logger.debug(" Issuer: " + issuerDN.toString());
    Date notBefore = cert.getNotBefore();
    DateFormat fmt = SimpleDateFormat.getDateTimeInstance();
    logger.debug("   From: " + fmt.format(notBefore));
    Date notAfter = cert.getNotAfter();
    logger.debug("     To: " + fmt.format(notAfter));
    Principal subjectDN = cert.getSubjectDN();
    logger.debug("Subject: " + subjectDN.toString());
    logger.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}

From source file:de.juwimm.cms.beans.foreign.security.ConQuestDaoAuthenticationProvider.java

/**
 * Attempts to login the user given the Authentication objects principal and credential
 *
 * @param auth The Authentication object to be authenticated.
 *
 * @return The authenticated Authentication object, with it's grantedAuthorities set.
 *
 * @throws AuthenticationException This implementation does not handle 'locked' or 'disabled' accounts. This method
 *         only throws a AuthenticationServiceException, with the message of the LoginException that will be
 *         thrown, should the loginContext.login() method fail.
 *//* w  w  w  .ja v  a  2s .c om*/
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (auth instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;

        try {
            //Create the LoginContext object, and pass our InternallCallbackHandler
            LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth));

            //Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
            loginContext.login();

            //create a set to hold the authorities, and add any that have already been applied.
            Set authorities = new HashSet();

            if (request.getAuthorities() != null) {
                authorities.addAll(Arrays.asList(request.getAuthorities()));
            }

            //get the subject principals and pass them to each of the AuthorityGranters
            Set principals = loginContext.getSubject().getPrincipals();

            authorities.add(new JaasGrantedAuthority("*", new AllPrincipal()));

            for (Iterator iterator = principals.iterator(); iterator.hasNext();) {
                Principal principal = (Principal) iterator.next();
                if (principal instanceof Group) {
                    Group g = (Group) principal;
                    if (g.members() != null) {
                        Enumeration members = g.members();
                        while (members.hasMoreElements()) {
                            Principal object = (Principal) members.nextElement();
                            authorities.add(new JaasGrantedAuthority(object.toString(), object));
                        }
                    } else {
                        authorities.add(new JaasGrantedAuthority(g.toString(), g));
                    }
                }
            }

            //Convert the authorities set back to an array and apply it to the token.
            JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
                    request.getCredentials(),
                    (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]),
                    loginContext);

            //Publish the success event
            publishSuccessEvent(result);

            //we're done, return the token.
            return result;
        } catch (LoginException loginException) {
            SpringSecurityException ase = loginExceptionResolver.resolveException(loginException);

            publishFailureEvent(request, ase);
            throw ase;
        }
    }

    return null;
}

From source file:com.ecyrd.jspwiki.auth.authorize.GroupManager.java

/**
 * Listens for {@link com.ecyrd.jspwiki.event.WikiSecurityEvent#PROFILE_NAME_CHANGED}
 * events. If a user profile's name changes, each group is inspected. If an entry contains
 * a name that has changed, it is replaced with the new one. No group events are emitted
 * as a consequence of this method, because the group memberships are still the same; it is
 * only the representations of the names within that are changing.
 * @param event the incoming event/*from  w  w  w.  j av a 2  s.c  o  m*/
 */
public void actionPerformed(WikiEvent event) {
    if (!(event instanceof WikiSecurityEvent)) {
        return;
    }

    WikiSecurityEvent se = (WikiSecurityEvent) event;
    if (se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED) {
        WikiSession session = (WikiSession) se.getSource();
        UserProfile[] profiles = (UserProfile[]) se.getTarget();
        Principal[] oldPrincipals = new Principal[] { new WikiPrincipal(profiles[0].getLoginName()),
                new WikiPrincipal(profiles[0].getFullname()), new WikiPrincipal(profiles[0].getWikiName()) };
        Principal newPrincipal = new WikiPrincipal(profiles[1].getFullname());

        // Examine each group
        int groupsChanged = 0;
        try {
            for (Group group : m_groupDatabase.groups()) {
                boolean groupChanged = false;
                for (Principal oldPrincipal : oldPrincipals) {
                    if (group.isMember(oldPrincipal)) {
                        group.remove(oldPrincipal);
                        group.add(newPrincipal);
                        groupChanged = true;
                    }
                }
                if (groupChanged) {
                    setGroup(session, group);
                    groupsChanged++;
                }
            }
        } catch (WikiException e) {
            // Oooo! This is really bad...
            log.error("Could not change user name in Group lists because of GroupDatabase error:"
                    + e.getMessage());
        }
        log.info("Profile name change for '" + newPrincipal.toString() + "' caused " + groupsChanged
                + " groups to change also.");
    }
}

From source file:com.ecyrd.jspwiki.PageManager.java

/**
 *  Listens for {@link com.ecyrd.jspwiki.event.WikiSecurityEvent#PROFILE_NAME_CHANGED}
 *  events. If a user profile's name changes, each page ACL is inspected. If an entry contains
 *  a name that has changed, it is replaced with the new one. No events are emitted
 *  as a consequence of this method, because the page contents are still the same; it is
 *  only the representations of the names within the ACL that are changing.
 * /*w w w.j av a2s  .co  m*/
 *  @param event The event
 */
public void actionPerformed(WikiEvent event) {
    if (!(event instanceof WikiSecurityEvent)) {
        return;
    }

    WikiSecurityEvent se = (WikiSecurityEvent) event;
    if (se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED) {
        UserProfile[] profiles = (UserProfile[]) se.getTarget();
        Principal[] oldPrincipals = new Principal[] { new WikiPrincipal(profiles[0].getLoginName()),
                new WikiPrincipal(profiles[0].getFullname()), new WikiPrincipal(profiles[0].getWikiName()) };
        Principal newPrincipal = new WikiPrincipal(profiles[1].getFullname());

        // Examine each page ACL
        try {
            int pagesChanged = 0;
            Collection pages = getAllPages();
            for (Iterator it = pages.iterator(); it.hasNext();) {
                WikiPage page = (WikiPage) it.next();
                boolean aclChanged = changeAcl(page, oldPrincipals, newPrincipal);
                if (aclChanged) {
                    // If the Acl needed changing, change it now
                    try {
                        m_engine.getAclManager().setPermissions(page, page.getAcl());
                    } catch (WikiSecurityException e) {
                        log.error(
                                "Could not change page ACL for page " + page.getName() + ": " + e.getMessage());
                    }
                    pagesChanged++;
                }
            }
            log.info("Profile name change for '" + newPrincipal.toString() + "' caused " + pagesChanged
                    + " page ACLs to change also.");
        } catch (ProviderException e) {
            // Oooo! This is really bad...
            log.error("Could not change user name in Page ACLs because of Provider error:" + e.getMessage());
        }
    }
}

From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java

public static byte[] getX509Cert(String nickname, Vector<Vector<Object>> cert_collection)
        throws CertificateException {
    for (int i = 0; i < cert_collection.size(); i++) {
        Vector<Object> v = cert_collection.elementAt(i);
        byte[] b = (byte[]) v.elementAt(0);
        X509CertImpl impl = null;//  w ww .  j a  v a 2  s . c om
        impl = new X509CertImpl(b);
        Principal subjectdn = impl.getSubjectDN();
        if (LDAPDN.equals(subjectdn.toString(), nickname))
            return b;
    }
    return null;
}

From source file:netscape.security.pkcs.PKCS12Util.java

public PKCS12CertInfo getCertBySubjectDN(PKCS12 pkcs12, String subjectDN) throws CertificateException {

    for (PKCS12CertInfo certInfo : pkcs12.getCertInfos()) {
        Principal certSubjectDN = certInfo.cert.getSubjectDN();
        if (LDAPDN.equals(certSubjectDN.toString(), subjectDN))
            return certInfo;
    }//from   www  . j av a  2s  .c  o  m

    return null;
}

From source file:org.apache.directory.fortress.web.control.SecUtils.java

/**
 * Enables fortress session on behalf of a java.security.Principal retrieved from the container.
 *
 * @param component/* w  w  w.  ja  v a 2s.c o m*/
 * @param servletReq
 * @param j2eePolicyMgr
 * @param accessMgr
 * @throws SecurityException
 */
public static void enableFortress(Component component, HttpServletRequest servletReq,
        J2eePolicyMgr j2eePolicyMgr, AccessMgr accessMgr) throws SecurityException {
    // Get the principal from the container:
    Principal principal = servletReq.getUserPrincipal();
    // Is this a Java EE secured page && has the User successfully authenticated already?
    boolean isSecured = principal != null;
    if (isSecured) {
        //linksLabel += " for " + principal.getName();
        if (!isLoggedIn(component)) {
            String szPrincipal = principal.toString();
            // Pull the fortress session from the realm and assert into the Web app's session along with user's perms:
            SecUtils.initializeSession(component, j2eePolicyMgr, accessMgr, szPrincipal);
        }
    }
}

From source file:org.apache.directory.fortress.web.FortressWebBasePage.java

public FortressWebBasePage() {
    // Build the title bar string.
    StringBuilder titlebuf = new StringBuilder();
    titlebuf.append("Fortress Web Administration");
    String szContextId = Config.getInstance().getProperty(GlobalIds.CONTEXT_ID_PROPERTY);
    // append the tenantId if set
    if (StringUtils.isNotEmpty(szContextId)
            && !szContextId.equalsIgnoreCase(org.apache.directory.fortress.core.GlobalIds.HOME)) {
        titlebuf.append(" : ");
        titlebuf.append(szContextId);/* w  ww  .j a va 2s  .c  om*/
    }
    // add it to title bar of page
    add(new Label(org.apache.directory.fortress.web.common.GlobalIds.TITLE_BAR, titlebuf.toString()));

    SecureBookmarkablePageLink usersLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.USERS_PAGE, UserPage.class,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_USERS);
    add(usersLink);
    PageParameters parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.RBAC_TYPE );
    SecureBookmarkablePageLink rolesLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.ROLES_PAGE, RolePage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_ROLES);
    add(rolesLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.ADMIN_TYPE );
    SecureBookmarkablePageLink admrolesLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.ADMROLES_PAGE, RoleAdminPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_ADMINROLES);
    add(admrolesLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.RBAC_TYPE );
    SecureBookmarkablePageLink objectsLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.POBJS_PAGE, ObjectPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_PERMOBJS);
    add(objectsLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.ADMIN_TYPE );
    SecureBookmarkablePageLink admobjsLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.ADMPOBJS_PAGE, ObjectAdminPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_ADMINOBJS);
    add(admobjsLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.RBAC_TYPE );
    SecureBookmarkablePageLink permsLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.PERMS_PAGE, PermPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_PERMS);
    add(permsLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.ADMIN_TYPE );
    SecureBookmarkablePageLink admpermsLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.ADMPERMS_PAGE, PermAdminPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_ADMINPERMS);
    add(admpermsLink);
    SecureBookmarkablePageLink policiesLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.PWPOLICIES_PAGE, PwPolicyPage.class,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_POLICIES);
    add(policiesLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.SSD );
    SecureBookmarkablePageLink ssdsLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.SSDS_PAGE, SdStaticPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_SSDS);
    add(ssdsLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.DSD );
    SecureBookmarkablePageLink dsdsLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.DSDS_PAGE, SdDynamicPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_DSDS);
    add(dsdsLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, GlobalIds.USEROUS );
    SecureBookmarkablePageLink userouLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.USEROUS_PAGE, OuUserPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_USEROUS);
    add(userouLink);
    parameters = new PageParameters();
    //parameters.set( GlobalIds.PAGE_TYPE, "PERMOUS" );
    SecureBookmarkablePageLink permouLink = new SecureBookmarkablePageLink(
            org.apache.directory.fortress.web.common.GlobalIds.PERMOUS_PAGE, OuPermPage.class, parameters,
            org.apache.directory.fortress.web.common.GlobalIds.ROLE_PERMOUS);
    add(permouLink);

    add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.GROUP_PAGE,
            GroupPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_GROUPS));

    add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.AUDIT_BINDS_PAGE,
            AuditBindPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_AUDIT_BINDS));

    add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.AUDIT_AUTHZS_PAGE,
            AuditAuthzPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_AUDIT_AUTHZS));

    add(new SecureBookmarkablePageLink(org.apache.directory.fortress.web.common.GlobalIds.AUDIT_MODS_PAGE,
            AuditModPage.class, org.apache.directory.fortress.web.common.GlobalIds.ROLE_AUDIT_MODS));

    add(new Label("footer", "Copyright (c) 2003-2016, The Apache Software Foundation. All Rights Reserved."));

    final Link actionLink = new Link("logout") {
        /** Default serialVersionUID */
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            setResponsePage(LogoutPage.class);
        }
    };
    add(actionLink);
    HttpServletRequest servletReq = (HttpServletRequest) getRequest().getContainerRequest();

    // RBAC Security Processing:
    Principal principal = servletReq.getUserPrincipal();
    // Is this a Java EE secured page && has the User successfully authenticated already?
    boolean isSecured = principal != null;
    if (isSecured && !isLoggedIn()) {
        // Here the principal was created by fortress realm and is a serialized instance of {@link Session}.
        String szPrincipal = principal.toString();
        Session session = null;

        String szIsJetty = System
                .getProperty(org.apache.directory.fortress.web.common.GlobalIds.IS_JETTY_SERVER);
        boolean isJetty = false;
        if (StringUtils.isNotEmpty(szIsJetty)) {
            if (szIsJetty.equalsIgnoreCase("true")) {
                isJetty = true;
            }
        }
        if (!isJetty) {
            try {
                // Deserialize the principal string into a fortress session:
                session = j2eePolicyMgr.deserialize(szPrincipal);
            } catch (SecurityException se) {
                // Can't recover....
                throw new RuntimeException(se);
            }
        }

        // If this is null, it means this app cannot share an rbac session with container and must now (re)create session here:
        if (session == null) {
            session = SecUtils.createSession(accessMgr, principal.getName());
        }

        // Now load the fortress session into the Wicket session and let wicket hold onto that for us.  Also retreive the arbac perms from server and cache those too.
        synchronized ((WicketSession) WicketSession.get()) {
            SecUtils.loadPermissionsIntoSession(delAccessMgr, session);
        }
    }
}

From source file:org.apache.wiki.auth.authorize.GroupManager.java

/**
 * Listens for {@link org.apache.wiki.event.WikiSecurityEvent#PROFILE_NAME_CHANGED}
 * events. If a user profile's name changes, each group is inspected. If an entry contains
 * a name that has changed, it is replaced with the new one. No group events are emitted
 * as a consequence of this method, because the group memberships are still the same; it is
 * only the representations of the names within that are changing.
 * @param event the incoming event//from w ww.ja v a 2s .c om
 */
public void actionPerformed(WikiEvent event) {
    if (!(event instanceof WikiSecurityEvent)) {
        return;
    }

    WikiSecurityEvent se = (WikiSecurityEvent) event;
    if (se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED) {
        WikiSession session = se.getSrc();
        UserProfile[] profiles = (UserProfile[]) se.getTarget();
        Principal[] oldPrincipals = new Principal[] { new WikiPrincipal(profiles[0].getLoginName()),
                new WikiPrincipal(profiles[0].getFullname()), new WikiPrincipal(profiles[0].getWikiName()) };
        Principal newPrincipal = new WikiPrincipal(profiles[1].getFullname());

        // Examine each group
        int groupsChanged = 0;
        try {
            for (Group group : m_groupDatabase.groups()) {
                boolean groupChanged = false;
                for (Principal oldPrincipal : oldPrincipals) {
                    if (group.isMember(oldPrincipal)) {
                        group.remove(oldPrincipal);
                        group.add(newPrincipal);
                        groupChanged = true;
                    }
                }
                if (groupChanged) {
                    setGroup(session, group);
                    groupsChanged++;
                }
            }
        } catch (WikiException e) {
            // Oooo! This is really bad...
            log.error("Could not change user name in Group lists because of GroupDatabase error:"
                    + e.getMessage());
        }
        log.info("Profile name change for '" + newPrincipal.toString() + "' caused " + groupsChanged
                + " groups to change also.");
    }
}