Java Code Examples for javax.security.auth.Subject#getPrincipals()

The following examples show how to use javax.security.auth.Subject#getPrincipals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BrokerImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
public SocketConnectionMetaData getConnectionMetaData()
{
    Subject subject = Subject.getSubject(AccessController.getContext());
    final SocketConnectionPrincipal principal;
    if(subject != null)
    {
        Set<SocketConnectionPrincipal> principals = subject.getPrincipals(SocketConnectionPrincipal.class);
        if(!principals.isEmpty())
        {
            principal = principals.iterator().next();
        }
        else
        {
            principal = null;
        }
    }
    else
    {
        principal = null;
    }
    return principal == null ? null : principal.getConnectionMetaData();
}
 
Example 2
Source File: Krb5ProxyImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean isRelated(Subject subject, Principal princ) {
    if (princ == null) return false;
    Set<Principal> principals =
            subject.getPrincipals(Principal.class);
    if (principals.contains(princ)) {
        // bound to this principal
        return true;
    }
    for (KeyTab pc: subject.getPrivateCredentials(KeyTab.class)) {
        if (!pc.isBound()) {
            return true;
        }
    }
    return false;
}
 
Example 3
Source File: ConnectorBootstrap.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void checkAccessFileEntries(Subject subject) {
    if (subject == null) {
        throw new SecurityException(
                "Access denied! No matching entries found in " +
                "the access file [" + accessFile + "] as the " +
                "authenticated Subject is null");
    }
    final Set<Principal> principals = subject.getPrincipals();
    for (Principal p1: principals) {
        if (properties.containsKey(p1.getName())) {
            return;
        }
    }

    final Set<String> principalsStr = new HashSet<>();
    for (Principal p2: principals) {
        principalsStr.add(p2.getName());
    }
    throw new SecurityException(
            "Access denied! No entries found in the access file [" +
            accessFile + "] for any of the authenticated identities " +
            principalsStr);
}
 
Example 4
Source File: Krb5ProxyImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean isRelated(Subject subject, Principal princ) {
    if (princ == null) return false;
    Set<Principal> principals =
            subject.getPrincipals(Principal.class);
    if (principals.contains(princ)) {
        // bound to this principal
        return true;
    }
    for (KeyTab pc: subject.getPrivateCredentials(KeyTab.class)) {
        if (!pc.isBound()) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: Synch3.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        subject.getPrincipals(X500Principal.class);
    }
    finished = true;
}
 
Example 6
Source File: GhidraPrincipal.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the GhidraPrincipal object contained within a Subject, or null if
 * not found.
 * 
 * @param subj user subject
 * @return GhidraPrincipal or null
 */
public static GhidraPrincipal getGhidraPrincipal(Subject subj) {
	if (subj != null) {
		Set<GhidraPrincipal> set = subj.getPrincipals(GhidraPrincipal.class);
		if (!set.isEmpty()) {
			return set.iterator().next();
		}
	}
	return null;
}
 
Example 7
Source File: Synch.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    new Thread() {
        public void run() {
            Principal last = new X500Principal("CN=Bob");
            for (int i = 0; !finished; i++) {
                Principal next = new X500Principal("CN=Bob" + i);
                principals.add(next);
                principals.remove(last);
                last = next;
            }
        }
    }.start();
    for (int i = 0; i < 1000; i++) {
        Subject.doAs(
            subject,
            new PrivilegedAction() {
                public Object run() {
                    return Subject.doAs(
                        new Subject(true,
                                    Collections.singleton(
                                        new X500Principal("CN=Claire")),
                                    Collections.EMPTY_SET,
                                    Collections.EMPTY_SET),
                        new PrivilegedAction() {
                            public Object run() {
                                return null;
                            }
                        });
                }
            });
    }
    finished = true;
}
 
Example 8
Source File: ServiceEJB.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@RolesAllowed("Tester")
public String getSubjectClass() throws Exception {
    Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
    System.out.printf("ServiceEJB.getSubjectClass, subject=%s\n", subject);
    Set<? extends Principal> principalSet = subject.getPrincipals(JsonWebToken.class);
    if (principalSet.size() > 0) {
        return "subject.getPrincipals(JsonWebToken.class) ok";
    }
    throw new IllegalStateException("subject.getPrincipals(JsonWebToken.class) == 0");
}
 
Example 9
Source File: ActiveMQJAASSecurityManager.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public String getUserFromSubject(Subject subject) {
   String validatedUser = "";
   Set<UserPrincipal> users = subject.getPrincipals(UserPrincipal.class);

   // should only ever be 1 UserPrincipal
   for (UserPrincipal userPrincipal : users) {
      validatedUser = userPrincipal.getName();
   }
   return validatedUser;
}
 
Example 10
Source File: EventCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public Map<String, String> convertSubject(Subject subject) {
    Map<String, String> map = new HashMap<String, String>();
    Set<Principal> principals = subject.getPrincipals();
    for (Principal principal : principals) {
        if (map.get(principal.getClass().getSimpleName()) != null) {
            map.put(principal.getClass().getSimpleName(), map.get(principal.getClass().getSimpleName()) + "," + principal.getName());
        } else {
            map.put(principal.getClass().getSimpleName(), principal.getName());
        }
    }
    return map;
}
 
Example 11
Source File: SubjectEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/getSubjectClass")
@RolesAllowed("Tester")
public String getSubjectClass(@Context SecurityContext sec) throws Exception {
    Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
    Set<? extends Principal> principalSet = subject.getPrincipals(JsonWebToken.class);
    if (principalSet.size() > 0) {
        return "subject.getPrincipals(JWTPrincipal.class) ok";
    }
    throw new IllegalStateException("subject.getPrincipals(JWTPrincipal.class) == 0");
}
 
Example 12
Source File: Synch2.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    final Set credentials = subject.getPrivateCredentials();
    credentials.add("Dummy credential");
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        synchronized (credentials) {
            for (Iterator it = credentials.iterator(); it.hasNext(); ) {
                it.next();
            }
        }
    }
    finished = true;
}
 
Example 13
Source File: RMIServerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static synchronized String makeConnectionId(String protocol,
                                                    Subject subject) {
    connectionIdNumber++;

    String clientHost = "";
    try {
        clientHost = RemoteServer.getClientHost();
        /*
         * According to the rules specified in the javax.management.remote
         * package description, a numeric IPv6 address (detected by the
         * presence of otherwise forbidden ":" character) forming a part
         * of the connection id must be enclosed in square brackets.
         */
        if (clientHost.contains(":")) {
            clientHost = "[" + clientHost + "]";
        }
    } catch (ServerNotActiveException e) {
        logger.trace("makeConnectionId", "getClientHost", e);
    }

    final StringBuilder buf = new StringBuilder();
    buf.append(protocol).append(":");
    if (clientHost.length() > 0)
        buf.append("//").append(clientHost);
    buf.append(" ");
    if (subject != null) {
        Set<Principal> principals = subject.getPrincipals();
        String sep = "";
        for (Iterator<Principal> it = principals.iterator(); it.hasNext(); ) {
            Principal p = it.next();
            String name = p.getName().replace(' ', '_').replace(';', ':');
            buf.append(sep).append(name);
            sep = ";";
        }
    }
    buf.append(" ").append(connectionIdNumber);
    if (logger.traceOn())
        logger.trace("newConnectionId","connectionId="+buf);
    return buf.toString();
}
 
Example 14
Source File: SimpleStandard.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the "monitorRole" identity.
 */
private void checkSubject() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException("Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals("monitorRole"))
        throw new SecurityException("Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
Example 15
Source File: FirewallRule.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private InetAddress getAddressOfClient(final Subject subject)
{
    final Set<ConnectionPrincipal> principals = subject.getPrincipals(ConnectionPrincipal.class);
    if(!principals.isEmpty())
    {
        final SocketAddress address = principals.iterator().next().getConnection().getRemoteSocketAddress();
        if(address instanceof InetSocketAddress)
        {
            return ((InetSocketAddress) address).getAddress();
        }
    }
    return null;
}
 
Example 16
Source File: RMIServerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static synchronized String makeConnectionId(String protocol,
                                                    Subject subject) {
    connectionIdNumber++;

    String clientHost = "";
    try {
        clientHost = RemoteServer.getClientHost();
        /*
         * According to the rules specified in the javax.management.remote
         * package description, a numeric IPv6 address (detected by the
         * presence of otherwise forbidden ":" character) forming a part
         * of the connection id must be enclosed in square brackets.
         */
        if (clientHost.contains(":")) {
            clientHost = "[" + clientHost + "]";
        }
    } catch (ServerNotActiveException e) {
        logger.trace("makeConnectionId", "getClientHost", e);
    }

    final StringBuilder buf = new StringBuilder();
    buf.append(protocol).append(":");
    if (clientHost.length() > 0)
        buf.append("//").append(clientHost);
    buf.append(" ");
    if (subject != null) {
        Set<Principal> principals = subject.getPrincipals();
        String sep = "";
        for (Iterator<Principal> it = principals.iterator(); it.hasNext(); ) {
            Principal p = it.next();
            String name = p.getName().replace(' ', '_').replace(';', ':');
            buf.append(sep).append(name);
            sep = ";";
        }
    }
    buf.append(" ").append(connectionIdNumber);
    if (logger.traceOn())
        logger.trace("newConnectionId","connectionId="+buf);
    return buf.toString();
}
 
Example 17
Source File: StandardCallbacks.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws LoginException {
    System.setProperty("java.security.auth.login.config",
            System.getProperty("test.src")
                    + System.getProperty("file.separator")
                    + "custom.config");

    CustomCallbackHandler handler = new CustomCallbackHandler(USERNAME);
    LoginContext context = new LoginContext("StandardCallbacks", handler);

    handler.setPassword(PASSWORD);
    System.out.println("Try to login with correct password, "
            + "successful authentication is expected");
    context.login();
    System.out.println("Authentication succeeded!");

    Subject subject = context.getSubject();
    System.out.println("Authenticated user has the following principals ["
            + subject.getPrincipals().size() + " ]:");
    boolean found = true;
    for (Principal principal : subject.getPrincipals()) {
        System.out.println("principal: " + principal);
        if (principal instanceof CustomLoginModule.TestPrincipal) {
            CustomLoginModule.TestPrincipal testPrincipal =
                    (CustomLoginModule.TestPrincipal) principal;
            if (USERNAME.equals(testPrincipal.getName())) {
                System.out.println("Found test principal: "
                        + testPrincipal);
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new RuntimeException("TestPrincipal not found");
    }

    // check if all expected text output callbacks have been called
    if (!handler.info) {
        throw new RuntimeException("TextOutputCallback.INFO not called");
    }

    if (!handler.warning) {
        throw new RuntimeException("TextOutputCallback.WARNING not called");
    }

    if (!handler.error) {
        throw new RuntimeException("TextOutputCallback.ERROR not called");
    }

    System.out.println("Authenticated user has the following public "
            + "credentials [" + subject.getPublicCredentials().size()
            + "]:");
    subject.getPublicCredentials().stream().
            forEach((o) -> {
                System.out.println("public credential: " + o);
    });

    context.logout();

    System.out.println("Test passed");
}
 
Example 18
Source File: HttpServerSpnegoWithJaasTest.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
@Test public void testAuthenticatedClientsAllowed() throws Exception {
  Assume.assumeThat("Test disabled on Windows", File.separatorChar, is('/'));

  // Create the subject for the client
  final Subject clientSubject = AvaticaJaasKrbUtil.loginUsingKeytab(
      SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse(clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
          clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse(privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull(tgt);
  LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());

  // The name of the principal
  final String principalName = clientPrincipals.iterator().next().getName();

  // Run this code, logged in as the subject (the client)
  byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {
    @Override public byte[] run() throws Exception {
      // Logs in with Kerberos via GSS
      GSSManager gssManager = GSSManager.getInstance();
      Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
      GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
      GSSCredential credential = gssManager.createCredential(gssClient,
          GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

      // Passes the GSSCredential into the HTTP client implementation
      final AvaticaCommonsHttpClientSpnegoImpl httpClient =
          new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);

      return httpClient.send(new byte[0]);
    }
  });

  // We should get a response which is "OK" with our client's name
  assertNotNull(response);
  assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL,
      new String(response, StandardCharsets.UTF_8));
}
 
Example 19
Source File: TestThriftSpnegoHttpFallbackServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
private CloseableHttpClient createHttpClient() throws Exception {
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse("Found no client principals in the clientSubject.",
    clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
    clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse("Found no private credentials in the clientSubject.",
    privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull("No kerberos ticket found.", tgt);

  // The name of the principal
  final String clientPrincipalName = clientPrincipals.iterator().next().getName();

  return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
    // Logs in with Kerberos via GSS
    GSSManager gssManager = GSSManager.getInstance();
    // jGSS Kerberos login constant
    Oid oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
    GSSCredential credential = gssManager.createCredential(gssClient,
      GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

    Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
      .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
      .build();

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

    return HttpClients.custom()
      .setDefaultAuthSchemeRegistry(authRegistry)
      .setDefaultCredentialsProvider(credentialsProvider)
      .build();
  });
}
 
Example 20
Source File: SecurityServiceImpl.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Principal authenticateJaas(Session session, String name, String password,
                                  String configName, Class<? extends Principal> userClass, Collection<Class<? extends Principal>> roleClasses) {
    Subject subject;
    try {
        LoginContext login = new LoginContext(configName, new NamePasswordCallbackHandler(name, password));
        login.login();
        subject = login.getSubject();
    }
    catch (LoginException ex) {
        throw new AuthenticationFailedException(ex);
    }
    Set<? extends Principal> allPrincs = (userClass == null) ?
        new HashSet<>(subject.getPrincipals()) :
        subject.getPrincipals(userClass);
    Collection<String> roles = null;
    if (roleClasses != null) {
        roles = new HashSet<>();
        for (Class<? extends Principal> clazz : roleClasses) {
            Set<? extends Principal> rolePrincs = subject.getPrincipals(clazz);
            allPrincs.removeAll(rolePrincs);
            for (Principal role : rolePrincs) {
                roles.add(role.getName());
            }
        }
    }
    Principal user;
    if (allPrincs.isEmpty())
        throw new AuthenticationFailedException("Authentication successful but no Principals returned");
    user = allPrincs.iterator().next();
    if (roleClasses == null) {
        User localUser = getUser(user.getName());
        if (localUser != null) {
            roles = localUser.getRoles();
        }
    }
    logger.debug("For user {}:\n{}\n  Chose principal {}, roles {}", name, subject, user, roles);
    session.put(SESSION_PRINCIPAL_KEY, user);
    session.put(SESSION_ROLES_KEY, roles);
    return user;
}