Example usage for java.security Principal getName

List of usage examples for java.security Principal getName

Introduction

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

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:org.overlord.security.eval.webapp4.services.JaxrsService.java

/**
 * @param principal//from ww  w .ja v  a2 s  .  c o  m
 * @return
 * @throws Exception
 * @throws FactoryConfigurationError
 * @throws XMLStreamException
 * @throws ProcessingException
 * @throws UnsupportedEncodingException
 */
protected static String createSAMLAssertion() throws Exception {
    Principal principal = SecurityContextAssociation.getPrincipal();
    NameIDType issuer = SAMLAssertionFactory.createNameID(null, null, "/security-eval-webapp-4");
    SubjectType subject = AssertionUtil.createAssertionSubject(principal.getName());
    AssertionType assertion = AssertionUtil.createAssertion(UUID.randomUUID().toString(), issuer);
    assertion.setSubject(subject);
    AssertionUtil.createTimedConditions(assertion, 10000);
    ConditionAbstractType restriction = SAMLAssertionFactory.createAudienceRestriction("/security-eval-jaxrs");
    assertion.getConditions().addCondition(restriction);
    addRoleStatements(assertion, principal);

    return AssertionUtil.asString(assertion);
}

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

private static String getUserId(Principal... principals) {
    for (Principal p : principals) {
        if (p instanceof UserPrincipal) {
            return p.getName(); // return first
        }/*from  ww  w . ja  va2 s  . c om*/
    }
    return null;
}

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

private static List<String> getRoleIds(Principal... principals) {
    ArrayList<String> result = new ArrayList<String>();
    for (Principal p : principals) {
        if (p instanceof RolePrincipal) {
            result.add(p.getName());
        }//from w  w  w.j  av a  2 s . c o m
    }
    return result;
}

From source file:alfio.controller.AdminController.java

private static void downloadTicketsCSV(String eventName, String fileName, String[] header, Principal principal,
        HttpServletResponse response, EventManager eventManager, Function<Ticket, String[]> ticketMapper)
        throws IOException {
    Validate.isTrue(StringUtils.isNotBlank(eventName), "Event name is not valid");
    List<Ticket> tickets = eventManager.findAllConfirmedTickets(eventName, principal.getName());
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-" + fileName + ".csv");
    try (ServletOutputStream out = response.getOutputStream()) {
        for (int marker : BOM_MARKERS) {//UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897
            out.write(marker);//  w  ww . j  a v  a 2s  . c o m
        }
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out));
        writer.writeNext(header);
        tickets.stream().map(ticketMapper).forEach(writer::writeNext);
        writer.flush();
        out.flush();
    }
}

From source file:com.jdon.strutsutil.FormBeanUtil.java

public static String getName(HttpServletRequest request) throws Exception {
    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        Debug.logError("[JdonFramework] No Principal", module);
        throw new Exception(" No Principal");
    }/*from w w  w . j  a va2 s.  c om*/
    return principal.getName();
}

From source file:org.motrice.bpm.hippo.util.ServletUserNameUtil.java

public static UserInfo getUserName(final HttpServletRequest request) {
    UserInfo result = null;/*from ww  w  .  java2 s  . co m*/

    /*
     * log.error("ServletUserNameUtil:error");
     * log.warn("ServletUserNameUtil:warn");
     * log.info("ServletUserNameUtil:info");
     * log.debug("ServletUserNameUtil:debug");
     * log.trace("ServletUserNameUtil:trace");
     */
    checkEngine();
    // / trying shibboleth
    String Shib_Identity_Provider = (String) request.getAttribute("Shib-Identity-Provider");
    log.info("request.getAttribute(Shib-Identity-Provider) = " + Shib_Identity_Provider);
    String Shib_Application_ID = (String) request.getAttribute("Shib-Application-ID");
    log.info("request.getAttribute(Shib-Application-ID) = " + Shib_Application_ID);
    // log.info("request.getHeader(Shib-Identity-Provider)  = "
    // + request.getHeader("Shib-Identity-Provider"));
    if ((Shib_Identity_Provider != null) && (Shib_Application_ID.equals("default"))) {
        // the names of the attributes are set in attribute-*.xml files in
        // /etc/shibboleth for the SP
        // Different IdPs might privide different attributes, it probable
        // makes sence
        // to make the mapping in the attribute-*.xml to the same attribute name for the different IdPs.
        String Subject_SerialNumber = (String) request.getAttribute("Subject_SerialNumber");
        // String gn = (String) request.getAttribute("GivenName");
        String gn = getAttributeShibboleth("GivenName", request);
        String sn = getAttributeShibboleth("Subject_Surname", request);
        //String sn_id = (String) request.getAttribute("sn_id");
        String sn_id = null;
        String cn = getAttributeShibboleth("Subject_CommonName", request);
        log.info("Subject_SerialNumber = " + Subject_SerialNumber + " gn = " + gn + " sn = " + sn + " cn = "
                + cn);
        result = engine.getUserBySerial(Subject_SerialNumber, gn, sn, sn_id, cn);
    }

    if ((Shib_Identity_Provider != null) && (Shib_Application_ID.equals("internal"))) {
        // the names of the attributes are set in attribute-*.xml files in
        // /etc/shibboleth for the SP
        // Different IdPs might privide different attributes, it probable
        // makes sence
        // to make the mapping in the attribute-*.xml to the same attribute name for the different IdPs.
        String cn = getAttributeShibboleth("Subject_CommonName", request);
        log.info(" cn = " + cn);
        String userBaseDn = ConfigUtil.getConfigProperties().getProperty("userDirectoryService.userBaseDn");
        String baseDn = ConfigUtil.getConfigProperties().getProperty("userDirectoryService.baseDn");
        // String dn ="cn="+cn+",ou=Personal,ou=Organisation,ou=Malmo,dc=adm,dc=malmo,dc=se" ; // NOTE  
        String dn = "cn=" + cn + "," + userBaseDn + "," + baseDn; // 
        log.info(" dn = " + dn);
        // log.info("Subject_SerialNumber = " + Subject_SerialNumber + " gn = "
        //          + gn + " sn = " + sn + " cn = " + cn);
        result = engine.getUserByDn(dn);
    }

    if (result == null) {

        log.info("Trying openAM");
        // OPEN AM
        String dn = request.getHeader("x-ipl-dn");
        String ser = request.getHeader("x-ipl-ser");
        String certificateSubject = request.getHeader("x-ipl-cer-sub");

        if (dn == null) {
            if (ser != null) {
                result = engine.getUserBySerial(ser, certificateSubject);
            }
        } else {
            if (ser == null) {
                result = engine.getUserByDn(dn);
            } else {
                log.debug("Only one of header x-ipl-dn and x-ipl-ser should be used");
                log.debug("x-ipl-dn=[  {} ]", dn);
                log.debug("x-ipl-ser=[  {} ]", ser);

                /**
                 * TODO workaround to detect by path komin/extern
                 */
                String pathInfo = request.getPathInfo();
                if (pathInfo != null && pathInfo.indexOf("komin") > 0) {
                    result = engine.getUserByDn(dn);
                } else {
                    result = engine.getUserBySerial(ser, certificateSubject);
                }

            }
        }

        if (result == null) {

            log.info("userName header not found, get user principal instead");
            log.info("Only one of header x-ipl-dn and x-ipl-ser should be used");
            log.info("x-ipl-dn=[{} ]", dn);
            log.info("x-ipl-ser=[{}  ]", ser);
            log.info("x-ipl-cer-sub=[{}]", certificateSubject);

            Principal principal = request.getUserPrincipal();
            if (principal != null) {
                String hippoDn = "CN=" + principal.getName()
                        + ",OU=Personal,OU=Organisation,OU=Hippo Internal User,DC=adm,DC=inherit,DC=se";
                result = engine.getUserByDn(hippoDn);
                // "CN=tesetj,OU=Personal,OU=Organisation,OU=Malmo,DC=adm,DC=malmo,DC=se"

            }

        }

        log.info("Render page with userInfo=[ {} ]", result);

        Enumeration attributes = request.getAttributeNames();
        while (attributes.hasMoreElements()) {
            String attr_name = (String) attributes.nextElement();
            Object attr_val = request.getAttribute(attr_name);
            log.info(attr_name + " = " + attr_val);

        }
    }
    log.info("request.getAttribute(GivenName) = {} ", getAttributeShibboleth("GivenName", request));
    log.info("request.getAttribute(sn_id) = {} ", getAttributeShibboleth("sn_id", request));
    log.info("request.getAttribute(SecurityLevelDescription) = {} ",
            getAttributeShibboleth("SecurityLevelDescription", request));
    log.info("request.getAttribute(Subject_CountryName) = {} ",
            getAttributeShibboleth("Subject_CountryName", request));
    log.info("request.getAttribute(Subject_CommonName) = {} ",
            getAttributeShibboleth("Subject_CommonName", request));
    log.info("request.getAttribute(CertificateSerialNumber) = {} ",
            getAttributeShibboleth("CertificateSerialNumber", request));
    log.info("request.getAttribute(dateOfBirth) = {} ", getAttributeShibboleth("dateOfBirth", request));
    log.info("request.getAttribute(Subject_OrganisationName) = {} ",
            getAttributeShibboleth("Subject_OrganisationName", request));
    log.info("request.getAttribute(Issuer_OrganizationName) = {} ",
            getAttributeShibboleth("Issuer_OrganizationName", request));
    log.info("request.getAttribute(sn_type) = {} ", getAttributeShibboleth("sn_type", request));
    log.info("request.getAttribute(Subject_Surname) = {} ", getAttributeShibboleth("Subject_Surname", request));
    log.info("request.getAttribute(Subject_SerialNumber) = {} ",
            getAttributeShibboleth("Subject_SerialNumber", request));
    log.info("request.getAttribute(Gender) = ", getAttributeShibboleth("Gender", request));
    log.info("request.getAttribute(ValidationOcspResponse, request) = {} ",
            getAttributeShibboleth("ValidationOcspResponse", request));
    log.info("request.getAttribute(SecurityLevel) = {} ", getAttributeShibboleth("SecurityLevel", request));
    log.info("request.getAttribute(Issuer_CommonName) = {} ",
            getAttributeShibboleth("Issuer_CommonName", request));
    log.info("request.getAttribute(age) = {} ", getAttributeShibboleth("age", request));
    log.info("request.getAttribute(affiliation) = {} ", getAttributeShibboleth("affiliation", request));
    log.info("request.getAttribute(entitlement) = {} ", getAttributeShibboleth("entitlement", request));
    log.info("request.getAttribute(eppn) = {} ", getAttributeShibboleth("eppn", request));
    log.info("request.getAttribute(persistent-id) = {} ", getAttributeShibboleth("persistent-id", request));
    log.info("request.getAttribute(telephoneNumber) = {} ", getAttributeShibboleth("telephoneNumber", request));
    log.info("request.getAttribute(unscoped-affiliation) = {} ",
            getAttributeShibboleth("unscoped-affiliation", request));
    return result;
}

From source file:ddf.security.SubjectUtils.java

/**
 * Retrieves the user name from a given subject.
 *
 * @param subject Subject to get the user name from.
 * @param defaultName Name to send back if no user name was found.
 * @param returnDisplayName return formatted user name for displaying
 * @return String representation of the user name if available or defaultName if no user name
 *     could be found or incoming subject was null.
 *//*from   w  w  w  . ja  v  a  2  s . c  om*/
public static String getName(Subject subject, String defaultName, boolean returnDisplayName) {
    String name = defaultName;
    if (subject != null) {
        PrincipalCollection principals = subject.getPrincipals();
        if (principals != null) {
            SecurityAssertion assertion = principals.oneByType(SecurityAssertion.class);
            if (assertion != null) {
                Principal principal = assertion.getPrincipal();
                if (principal instanceof KerberosPrincipal) {
                    StringTokenizer st = new StringTokenizer(principal.getName(), "@");
                    st = new StringTokenizer(st.nextToken(), "/");
                    name = st.nextToken();
                } else {
                    name = principal.getName();
                }

                if (returnDisplayName) {
                    name = getDisplayName(principal, name);
                }

            } else {
                // send back the primary principal as a string
                name = principals.getPrimaryPrincipal().toString();
            }
        } else {
            LOGGER.debug(
                    "No principals located in the incoming subject, cannot look up user name. Using default name of {}.",
                    defaultName);
        }
    } else {
        LOGGER.debug("Incoming subject was null, cannot look up user name. Using default name of {}.",
                defaultName);
    }

    LOGGER.debug("Sending back name {}.", name);
    return name;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyBasicAuthenticator.java

public static Principal checkLogin(SecurityRequestWrapper request, HttpServletResponse response,
        XWikiContext context) throws Exception {
    // Always verify authentication
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null) {
        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = convertUsername(parseUsername(decoded), context);
        String password = parsePassword(decoded);

        Principal principal = authenticate(username, password, context);

        if (principal != null) {
            // login successful
            request.getSession().removeAttribute(LOGIN_ATTEMPTS);

            // make sure the Principal contains wiki name information
            if (!StringUtils.contains(principal.getName(), ':')) {
                principal = new SimplePrincipal(context.getDatabase() + ":" + principal.getName());
            }/*  w ww  .j  av  a  2s  . co m*/

            request.setUserPrincipal(principal);

            return principal;
        }
    }

    return null;
}

From source file:org.apache.sentry.binding.solr.authz.SentrySolrPluginImpl.java

/**
 * Workaround until SOLR-10814 is fixed. This method allows extracting short user-name from
 * Solr provided {@linkplain Principal} instance.
 *
 * @param ctx The Solr provided authorization context
 * @return The short name of the authenticated user for this request
 *//*from w  ww.  ja  va  2  s .  c  o m*/
public static String getShortUserName(Principal princ) {
    if (princ instanceof BasicUserPrincipal) {
        return princ.getName();
    }

    KerberosName name = new KerberosName(princ.getName());
    try {
        return name.getShortName();
    } catch (IOException e) {
        LOG.error("Error converting kerberos name. principal = {}, KerberosName.rules = {}", princ,
                KerberosName.getRules());
        throw new SolrException(ErrorCode.SERVER_ERROR, "Unexpected error converting a kerberos name", e);
    }
}

From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static X509Certificate generateVMCertificate(final RSAPublicKey publicKey, final String principal,
        final int expirationDays) throws AuthException {
    try {/*from ww  w.j  a  v a 2  s. c o  m*/
        final X500Principal subjectDn = new X500Principal(principal);
        final Credentials euareCred = SystemCredentials.lookup(Euare.class);
        final Principal signer = euareCred.getCertificate().getSubjectDN();
        final PrivateKey signingKey = euareCred.getPrivateKey();
        final Date notAfter = DateUtils.addDays(Calendar.getInstance().getTime(), expirationDays);
        final X509Certificate cert = Certs.generateCertificate(publicKey, subjectDn,
                new X500Principal(signer.getName()), signingKey, notAfter);
        if (cert == null) {
            throw new Exception("Null returned");
        }
        return cert;
    } catch (final Exception ex) {
        throw new AuthException("failed to generate VM certificate", ex);
    }
}