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:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    Enumeration e = keystore.aliases();
    for (; e.hasMoreElements();) {
        String alias = (String) e.nextElement();

        java.security.cert.Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            X509Certificate x509cert = (X509Certificate) cert;

            // Get subject
            Principal principal = x509cert.getSubjectDN();
            String subjectDn = principal.getName();

            // Get issuer
            principal = x509cert.getIssuerDN();
            String issuerDn = principal.getName();
        }//from w  ww .  j a  v  a  2s. c o  m
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;/*from  w ww . j  a  va2 s .  c o  m*/
    try {
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:com.clz.share.sec.util.SignInUtils.java

public static ResponseEntity<?> signinOauth2A(String userId) {

    Principal principal = signinPrivate(userId);
    System.out.println("         pricipal  " + principal.getName());

    ResponseEntity<?> res = null;//from   w  w  w .  j av  a 2 s .  c  o  m
    try {
        return getToken(principal);
    } catch (HttpRequestMethodNotSupportedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return res;
}

From source file:Main.java

public static String toString(Principal[] principals) {
    if (principals == null || principals.length == 0) {
        return "<empty principals>";
    }/*from w ww .ja v a  2s. com*/
    StringBuffer buf = new StringBuffer();

    buf.append("<");
    for (int i = 0; i < principals.length; i++) {
        Principal p = principals[i];
        buf.append("(class=");
        buf.append(p.getClass());
        buf.append(", name=");
        buf.append(p.getName());
        buf.append(")");
        if (i < principals.length) {
            buf.append(", ");
        }

    }
    buf.append(">");

    return buf.toString();
}

From source file:com.clz.share.sec.util.SignInUtils.java

public static ResponseEntity<?> signinOauth2(String userId) {

    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put("client_id", "appid");
    parameters.put("client_secret", "myOAuthSecret");
    parameters.put("grant_type", "password");
    parameters.put("username", "user");
    parameters.put("password", "pass");
    parameters.put("scope", "read write");

    Principal principal = signinPrivate(userId);
    System.out.println("         pricipal  " + principal.getName());

    ResponseEntity<?> res = null;// w w  w  .  j  av  a  2  s .  c o m
    try {
        return getToken(principal);
    } catch (HttpRequestMethodNotSupportedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return res;
}

From source file:com.hortonworks.example.util.Util.java

public static String getPrincipalName(HttpServletRequest request) {
    String n = null;//from   ww w  .  ja  v  a2 s  . com
    Principal p = request.getUserPrincipal();
    if (p != null) {
        n = p.getName();
    }
    return n;
}

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

/**
 * Adds the roles to the assertion as attribute statements.
 * @param assertion/*  w  w  w .  j  ava2  s . c  o  m*/
 * @param principal
 */
private static void addRoleStatements(AssertionType assertion, Principal principal) {
    AttributeType attribute = new AttributeType("Role");
    ASTChoiceType attributeAST = new ASTChoiceType(attribute);
    AttributeStatementType roleStatement = new AttributeStatementType();
    roleStatement.addAttribute(attributeAST);

    Set<Principal> userRoles = SecurityContextAssociation.getSecurityContext().getAuthorizationManager()
            .getUserRoles(principal);
    if (userRoles != null) {
        for (Principal role : userRoles) {
            attribute.addAttributeValue(role.getName());
        }
    }

    assertion.addStatement(roleStatement);
}

From source file:com.keybox.manage.util.ExternalAuthUtil.java

/**
 * external auth login method/*from www. j  a v  a2 s.  c  o  m*/
 *
 * @param auth contains username and password
 * @return auth token if success
 */
public static String login(final Auth auth) {

    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername())
            && StringUtils.isNotEmpty(auth.getPassword())) {

        Connection con = null;
        try {
            CallbackHandler handler = new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            };

            try {
                LoginContext loginContext = new LoginContext(JAAS_MODULE, handler);
                //will throw exception if login fail
                loginContext.login();
                Subject subject = loginContext.getSubject();

                con = DBUtils.getConn();
                User user = AuthDB.getUserByUID(con, auth.getUsername());

                if (user == null) {
                    user = new User();

                    user.setUserType(User.ADMINISTRATOR);
                    user.setUsername(auth.getUsername());

                    //if it looks like name is returned default it 
                    for (Principal p : subject.getPrincipals()) {
                        if (p.getName().contains(" ")) {
                            String[] name = p.getName().split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        }
                    }

                    //set email
                    if (auth.getUsername().contains("@")) {
                        user.setEmail(auth.getUsername());
                    }

                    user.setId(UserDB.insertUser(con, user));
                }

                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                //set auth token
                AuthDB.updateLogin(con, user);

            } catch (LoginException e) {
                //auth failed return empty
                authToken = null;
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }

        DBUtils.closeConn(con);
    }

    return authToken;
}

From source file:de.ingrid.portal.security.util.SecurityHelper.java

/**
 * Merge role permissions with user permissions
 * //from  www.ja va  2 s .  c  o  m
 * @param p
 *            The Principal of the user to merge the role permission with.
 * @param permissionManager
 *            The JETSPEED permission manager.
 * @param roleManager
 *            The JETSPEED role manager.
 * @return The merged Permissions.
 */
public static Permissions getMergedPermissions(Principal p, PermissionManager permissionManager,
        RoleManager roleManager) {
    Permissions result = null;
    try {
        Collection<Role> roles = roleManager.getRolesForUser(p.getName());
        result = getMergedPermissions(p, roles, permissionManager);
    } catch (SecurityException e) {
        if (log.isErrorEnabled()) {
            log.error("Error merging roles of principal '" + p.getName() + "'!", e);
        }
    }
    return result;
}

From source file:us.repasky.microblog.controllers.UserControllerTest.java

private static final Principal getMockSecurityPrincipal() {
    Principal mockPrincipal = mock(Principal.class);
    when(mockPrincipal.getName()).thenReturn(USERNAME);
    return mockPrincipal;
}