Example usage for java.security Principal getClass

List of usage examples for java.security Principal getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:edu.ku.brc.af.auth.specify.SpecifySecurityMgr.java

public void grantPermission(Subject currentSubject, Principal principalToMatchTo, Permission perm) {
    log.debug("grantPermission"); //$NON-NLS-1$
    if (currentSubject == null) {
        log.error("grantPermission - subject is null - cannot grant permission"); //$NON-NLS-1$
        return;/*  w w  w.  j  a v  a 2  s.com*/
    }
    if (perm == null) {
        log.error("grantPermission - permission is null - cannot grant permission"); //$NON-NLS-1$
        return;
    }
    Set<Principal> p = currentSubject.getPrincipals();
    if (p == null) {
        log.error(
                "grantPermission - there are no principals associated with this user - cannot grant permission"); //$NON-NLS-1$
        return;
    }

    Iterator<Principal> it = p.iterator();
    while (it.hasNext()) {
        Principal principal = it.next();
        String principalClassName = principal.getClass().getCanonicalName();
        if (principalClassName.equals(SpPrincipal.class.getCanonicalName())) {
            SpPrincipal spp = (SpPrincipal) principal;
            String principalType = spp.getGroupSubClass();
            String principalName = spp.getName();
            SpPrincipal mySpPrincipal = PermissionService.getSpPrincipalByName(principalName);
            if (principalToMatchTo == null) {
                PermissionService.giveSpPrincipalPermission(mySpPrincipal, perm);

            } else if (principalType.equals(principalToMatchTo.getClass().getCanonicalName())) {
                PermissionService.giveSpPrincipalPermission(mySpPrincipal, perm);
            }
        }
    }
}

From source file:net.sourceforge.safr.jaas.permission.PermissionManagerImpl.java

private PermissionMap getPermissionMap(Principal principal) {
    if (principal instanceof UserPrincipal) {
        return userPermissions;
    }/*from   ww w  .j a v  a 2 s .c  o  m*/
    if (principal instanceof RolePrincipal) {
        return rolePermissions;
    }
    throw new IllegalArgumentException("unsupported principal class " + principal.getClass());
}

From source file:com.bitplan.rest.RestServerImpl.java

/**
 * check the principal//from w  w w  . jav  a 2  s  . c  o m
 * 
 * @param principal
 * @throws Exception
 */
protected Principal checkPrincipal(Principal principal) throws Exception {
    LOGGER.info("Principal is " + principal.getClass().getName());
    LOGGER.info("DN=" + principal.getName());
    // no check of principal
    return principal;
    // CN=Client, OU=HQ Schiefbahn, O=BITPlan GmbH, L=Willich, ST=Germany, C=DE
}

From source file:it.geosolutions.geostore.services.rest.impl.RESTServiceImpl.java

/**
 * @return User - The authenticated user that is accessing this service, or null if guest access.
 *//*from   w ww  .  j  a  va2s. c om*/
protected User extractAuthUser(SecurityContext sc) throws InternalErrorWebEx {
    if (sc == null)
        throw new InternalErrorWebEx("Missing auth info");
    else {
        Principal principal = sc.getUserPrincipal();
        if (principal == null) {
            // If I'm here I'm sure that the service is running is allowed for the unauthenticated users
            // due to service-based authorization step that uses annotations on services declaration (seee module geostore-rest-api). 
            // So I'm going to create a Principal to be used during resources-based authorization.
            principal = createGuestPrincipal();
        }
        if (!(principal instanceof UsernamePasswordAuthenticationToken)) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Mismatching auth principal");
            }
            throw new InternalErrorWebEx("Mismatching auth principal (" + principal.getClass() + ")");
        }

        UsernamePasswordAuthenticationToken usrToken = (UsernamePasswordAuthenticationToken) principal;

        //DamianoG 06/03/2014 Why create a new Instance when we can deal with the object taken from the DB? Being the instance taken from DB Transient we avoid problems saving security rules...
        //            User user = new User();
        //            user.setName(usrToken.getName());
        //            for (GrantedAuthority authority : usrToken.getAuthorities()) {
        //                if (authority != null) {
        //                    if (authority.getAuthority() != null
        //                            && authority.getAuthority().contains("ADMIN"))
        //                        user.setRole(Role.ADMIN);
        //
        //                    if (authority.getAuthority() != null
        //                            && authority.getAuthority().contains("USER") && user.getRole() == null)
        //                        user.setRole(Role.USER);
        //
        //                    if (user.getRole() == null)
        //                        user.setRole(Role.GUEST);
        //                }
        //            }
        User user = (User) usrToken.getPrincipal();

        LOGGER.info("Accessing service with user " + user.getName() + " and role " + user.getRole());

        return user;
    }
}

From source file:com.ecyrd.jspwiki.auth.SecurityVerifier.java

/**
 * Prints a &lt;td&gt; HTML element with the results of a permission test.
 * @param perm the permission to format//from   www  .ja v  a  2  s  .com
 * @param allowed whether the permission is allowed
 */
private final String printPermissionTest(Permission permission, Principal principal, int cols) {
    StringBuffer s = new StringBuffer();
    if (permission == null) {
        s.append("    <td colspan=\"" + cols + "\" align=\"center\" title=\"N/A\">");
        s.append("&nbsp;</td>\n");
    } else {
        boolean allowed = verifyStaticPermission(principal, permission);
        s.append("    <td colspan=\"" + cols + "\" align=\"center\" title=\"");
        s.append(allowed ? "ALLOW: " : "DENY: ");
        s.append(permission.getClass().getName());
        s.append(" &quot;");
        s.append(permission.getName());
        s.append("&quot;");
        if (permission.getName() != null) {
            s.append(",&quot;");
            s.append(permission.getActions());
            s.append("&quot;");
        }
        s.append(" ");
        s.append(principal.getClass().getName());
        s.append(" &quot;");
        s.append(principal.getName());
        s.append("&quot;");
        s.append("\"");
        s.append(allowed ? BG_GREEN + ">" : BG_RED + ">");
        s.append("&nbsp;</td>\n");
    }
    return s.toString();
}

From source file:com.ecyrd.jspwiki.auth.SecurityVerifier.java

/**
 * Formats and returns an HTML table containing the roles the web container
 * is aware of, and whether each role maps to particular JSPs. This method
 * throws an {@link IllegalStateException} if the authorizer is not of type
 * {@link com.ecyrd.jspwiki.auth.authorize.WebContainerAuthorizer}
 * @return the formatted HTML table containing the result of the tests
 * @throws WikiException if tests fail for unexpected reasons
 *//*from w w  w .  j a v a  2s. c o m*/
public final String containerRoleTable() throws WikiException {

    AuthorizationManager authorizationManager = m_engine.getAuthorizationManager();
    Authorizer authorizer = authorizationManager.getAuthorizer();

    // If authorizer not WebContainerAuthorizer, print error message
    if (!(authorizer instanceof WebContainerAuthorizer)) {
        throw new IllegalStateException("Authorizer should be WebContainerAuthorizer");
    }

    // Now, print a table with JSP pages listed on the left, and
    // an evaluation of each pages' constraints for each role
    // we discovered
    StringBuffer s = new StringBuffer();
    Principal[] roles = authorizer.getRoles();
    s.append("<table class=\"wikitable\" border=\"1\">\n");
    s.append("<thead>\n");
    s.append("  <tr>\n");
    s.append("    <th rowspan=\"2\">Action</th>\n");
    s.append("    <th rowspan=\"2\">Page</th>\n");
    s.append("    <th colspan=\"" + roles.length + 1 + "\">Roles</th>\n");
    s.append("  </tr>\n");
    s.append("  <tr>\n");
    s.append("    <th>Anonymous</th>\n");
    for (Principal role : roles) {
        s.append("    <th>" + role.getName() + "</th>\n");
    }
    s.append("</tr>\n");
    s.append("</thead>\n");
    s.append("<tbody>\n");

    try {
        WebContainerAuthorizer wca = (WebContainerAuthorizer) authorizer;
        for (int i = 0; i < CONTAINER_ACTIONS.length; i++) {
            String action = CONTAINER_ACTIONS[i];
            String jsp = CONTAINER_JSPS[i];

            // Print whether the page is constrained for each role
            boolean allowsAnonymous = !wca.isConstrained(jsp, Role.ALL);
            s.append("  <tr>\n");
            s.append("    <td>" + action + "</td>\n");
            s.append("    <td>" + jsp + "</td>\n");
            s.append("    <td title=\"");
            s.append(allowsAnonymous ? "ALLOW: " : "DENY: ");
            s.append(jsp);
            s.append(" Anonymous");
            s.append("\"");
            s.append(allowsAnonymous ? BG_GREEN + ">" : BG_RED + ">");
            s.append("&nbsp;</td>\n");
            for (Principal role : roles) {
                boolean allowed = allowsAnonymous || wca.isConstrained(jsp, (Role) role);
                s.append("    <td title=\"");
                s.append(allowed ? "ALLOW: " : "DENY: ");
                s.append(jsp);
                s.append(" ");
                s.append(role.getClass().getName());
                s.append(" &quot;");
                s.append(role.getName());
                s.append("&quot;");
                s.append("\"");
                s.append(allowed ? BG_GREEN + ">" : BG_RED + ">");
                s.append("&nbsp;</td>\n");
            }
            s.append("  </tr>\n");
        }
    } catch (JDOMException e) {
        // If we couldn't evaluate constraints it means
        // there's some sort of IO mess or parsing issue
        LOG.error("Malformed XML in web.xml", e);
        throw new InternalWikiException(e.getClass().getName() + ": " + e.getMessage());
    }

    s.append("</tbody>\n");
    s.append("</table>\n");
    return s.toString();
}

From source file:org.apache.catalina.realm.JAASRealm.java

/**
 * Construct and return a <code>java.security.Principal</code> instance
 * representing the authenticated user for the specified Subject.  If no
 * such Principal can be constructed, return <code>null</code>.
 *
 * @param subject The Subject representing the logged in user
 *///from  w  w  w  .  ja v a 2  s. co m
protected Principal createPrincipal(String username, Subject subject) {
    // Prepare to scan the Principals for this Subject
    String password = null; // Will not be carried forward
    ArrayList roles = new ArrayList();

    // Scan the Principals for this Subject
    Iterator principals = subject.getPrincipals().iterator();
    while (principals.hasNext()) {
        Principal principal = (Principal) principals.next();
        // No need to look further - that's our own stuff
        if (principal instanceof GenericPrincipal) {
            if (log.isDebugEnabled())
                log.debug("Found old GenericPrincipal " + principal);
            return principal;
        }
        String principalClass = principal.getClass().getName();
        if (log.isDebugEnabled())
            log.info("Principal: " + principalClass + " " + principal);

        if (userClasses.contains(principalClass)) {
            // Override the default - which is the original user, accepted by
            // the friendly LoginManager
            username = principal.getName();
        }
        if (roleClasses.contains(principalClass)) {
            roles.add(principal.getName());
        }
        // Same as Jboss - that's a pretty clean solution
        if ((principal instanceof Group) && "Roles".equals(principal.getName())) {
            Group grp = (Group) principal;
            Enumeration en = grp.members();
            while (en.hasMoreElements()) {
                Principal roleP = (Principal) en.nextElement();
                roles.add(roleP.getName());
            }

        }
    }

    // Create the resulting Principal for our authenticated user
    if (username != null) {
        return (new GenericPrincipal(this, username, password, roles));
    } else {
        return (null);
    }
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

protected SAMLAssertion createBearerAssertion(SAMLTokenIssuerConfig config, Document doc, Crypto crypto,
        Date creationTime, Date expirationTime, RahasData data) throws TrustException {
    try {/* w  w w  . j  av  a 2 s  . com*/
        Principal principal = data.getPrincipal();
        SAMLAssertion assertion;
        // In the case where the principal is a UT
        if (principal instanceof WSUsernameTokenPrincipal || principal instanceof KerberosTokenPrincipal) {
            SAMLNameIdentifier nameId = null;
            if (config.getCallbackHandler() != null) {
                SAMLNameIdentifierCallback cb = new SAMLNameIdentifierCallback(data);
                cb.setUserId(principal.getName());
                SAMLCallbackHandler callbackHandler = config.getCallbackHandler();
                callbackHandler.handle(cb);
                nameId = cb.getNameId();
            } else {
                nameId = new SAMLNameIdentifier(principal.getName(), null, SAMLNameIdentifier.FORMAT_EMAIL);

            }

            return createAuthAssertion(doc, SAMLSubject.CONF_BEARER, nameId, null, config, crypto, creationTime,
                    expirationTime, data);
        } else {
            throw new TrustException("samlUnsupportedPrincipal",
                    new String[] { principal.getClass().getName() });
        }
    } catch (SAMLException e) {
        throw new TrustException("samlAssertionCreationError", e);
    }
}

From source file:org.globus.security.util.CertificateIOUtil.java

public static byte[] encodePrincipal(Principal subject) throws IOException {
    if (subject instanceof X500Principal) {
        return ((X500Principal) subject).getEncoded();
        //} else if (subject instanceof X500Name) {
        //    return ((X500Name)subject).getEncoded();
    } else if (subject instanceof X509Name) {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(bout);
        X509Name nm = (X509Name) subject;
        der.writeObject(nm.getDERObject());
        return bout.toByteArray();
    } else {/*from w  ww. j  a v a2 s .  c o  m*/
        throw new ClassCastException("unsupported input class: " + subject.getClass().toString());
    }
}

From source file:org.globus.workspace.common.SecurityUtil.java

private static byte[] encodePrincipal(Principal subject) throws IOException {

    if (subject == null) {
        throw new IllegalArgumentException("subject may not be null");
    }/*from  www.  ja  v a 2 s .com*/

    if (subject instanceof X500Principal) {

        return ((X500Principal) subject).getEncoded();

    } else if (subject instanceof X509Name) {

        ByteArrayOutputStream bout = null;
        DEROutputStream der = null;
        try {
            bout = new ByteArrayOutputStream();
            der = new DEROutputStream(bout);
            final X509Name nm = (X509Name) subject;
            der.writeObject(nm.getDERObject());
            return bout.toByteArray();
        } finally {
            if (der != null) {
                der.close();
            }
            if (bout != null) {
                bout.close();
            }
        }

    } else {
        throw new ClassCastException("unsupported input class: " + subject.getClass().toString());
    }
}