當前位置: 首頁>>代碼示例>>Java>>正文


Java Subject.getPrincipals方法代碼示例

本文整理匯總了Java中javax.security.auth.Subject.getPrincipals方法的典型用法代碼示例。如果您正苦於以下問題:Java Subject.getPrincipals方法的具體用法?Java Subject.getPrincipals怎麽用?Java Subject.getPrincipals使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.security.auth.Subject的用法示例。


在下文中一共展示了Subject.getPrincipals方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: isRelated

import javax.security.auth.Subject; //導入方法依賴的package包/類
@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;
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:17,代碼來源:Krb5ProxyImpl.java

示例2: getUseridFromJAASSubject

import javax.security.auth.Subject; //導入方法依賴的package包/類
private static String getUseridFromJAASSubject() {
    Subject subject = Subject.getSubject(AccessController.getContext());
    LOGGER.trace("Subject of caller: {}", subject);
    if (subject != null) {
        Set<Principal> principals = subject.getPrincipals();
        LOGGER.trace("Public principals of caller: {}", principals);
        for (Principal pC : principals) {
            if (!(pC instanceof Group)) {
                String userIdFound = pC.getName();
                String userIdUsed = userIdFound;
                if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) {
                    userIdUsed = userIdFound.toLowerCase();
                }
                LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed);
                return userIdUsed;
            }
        }
    }
    LOGGER.trace("No userid found in subject!");
    return null;
}
 
開發者ID:Taskana,項目名稱:taskana,代碼行數:22,代碼來源:CurrentUserContext.java

示例3: checkAccessFileEntries

import javax.security.auth.Subject; //導入方法依賴的package包/類
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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:ConnectorBootstrap.java

示例4: createProxyUser

import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
 * Create a proxy user using username of the effective user and the ugi of the
 * real user.
 * @param user
 * @param realUser
 * @return proxyUser ugi
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation createProxyUser(String user,
    UserGroupInformation realUser) {
  if (user == null || user.isEmpty()) {
    throw new IllegalArgumentException("Null user");
  }
  if (realUser == null) {
    throw new IllegalArgumentException("Null real user");
  }
  Subject subject = new Subject();
  Set<Principal> principals = subject.getPrincipals();
  principals.add(new User(user));
  principals.add(new RealUser(realUser));
  UserGroupInformation result =new UserGroupInformation(subject);
  result.setAuthenticationMethod(AuthenticationMethod.PROXY);
  return result;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:26,代碼來源:UserGroupInformation.java

示例5: checkSubject

import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:SimpleStandard.java

示例6: getUGIFromTicketCache

import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
 * Create a UserGroupInformation from a Kerberos ticket cache.
 * 
 * @param user                The principal name to load from the ticket
 *                            cache
 * @param ticketCachePath     the path to the ticket cache file
 *
 * @throws IOException        if the kerberos login fails
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation getUGIFromTicketCache(
          String ticketCache, String user) throws IOException {
  if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) {
    return getBestUGI(null, user);
  }
  try {
    Map<String,String> krbOptions = new HashMap<String,String>();
    if (IBM_JAVA) {
      krbOptions.put("useDefaultCcache", "true");
      // The first value searched when "useDefaultCcache" is used.
      System.setProperty("KRB5CCNAME", ticketCache);
    } else {
      krbOptions.put("doNotPrompt", "true");
      krbOptions.put("useTicketCache", "true");
      krbOptions.put("useKeyTab", "false");
      krbOptions.put("ticketCache", ticketCache);
    }
    krbOptions.put("renewTGT", "false");
    krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS);
    AppConfigurationEntry ace = new AppConfigurationEntry(
        KerberosUtil.getKrb5LoginModuleName(),
        LoginModuleControlFlag.REQUIRED,
        krbOptions);
    DynamicConfiguration dynConf =
        new DynamicConfiguration(new AppConfigurationEntry[]{ ace });
    LoginContext login = newLoginContext(
        HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf);
    login.login();

    Subject loginSubject = login.getSubject();
    Set<Principal> loginPrincipals = loginSubject.getPrincipals();
    if (loginPrincipals.isEmpty()) {
      throw new RuntimeException("No login principals found!");
    }
    if (loginPrincipals.size() != 1) {
      LOG.warn("found more than one principal in the ticket cache file " +
        ticketCache);
    }
    User ugiUser = new User(loginPrincipals.iterator().next().getName(),
        AuthenticationMethod.KERBEROS, login);
    loginSubject.getPrincipals().add(ugiUser);
    UserGroupInformation ugi = new UserGroupInformation(loginSubject);
    ugi.setLogin(login);
    ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    return ugi;
  } catch (LoginException le) {
    throw new IOException("failure to login using ticket cache file " +
        ticketCache, le);
  }
}
 
開發者ID:nucypher,項目名稱:hadoop-oss,代碼行數:62,代碼來源:UserGroupInformation.java

示例7: main

import javax.security.auth.Subject; //導入方法依賴的package包/類
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;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:37,代碼來源:Synch.java

示例8: getSubjectClass

import javax.security.auth.Subject; //導入方法依賴的package包/類
@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");
}
 
開發者ID:eclipse,項目名稱:microprofile-jwt-auth,代碼行數:11,代碼來源:ServiceEJB.java

示例9: makeConnectionId

import javax.security.auth.Subject; //導入方法依賴的package包/類
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();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:41,代碼來源:RMIServerImpl.java

示例10: getCallerPrincipals

import javax.security.auth.Subject; //導入方法依賴的package包/類
protected Principal[] getCallerPrincipals() {
	final Subject caller = getContextSubjectAccess().getContextSubject();
	if ( caller == null ) {
		return new Principal[0];
	}

	final Set<Principal> principalsSet = caller.getPrincipals();
	return principalsSet.toArray( new Principal[ principalsSet.size()] );
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:10,代碼來源:StandardJaccServiceImpl.java

示例11: getSubjectPrincipals

import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
 * Retrieves the {@linkplain Subject} principals
 * @param subject The subject
 * @return If the {@code Subject} is immutable it will return the principals directly.
 *         If the {@code Subject} is mutable it will create an unmodifiable copy.
 */
private static Collection<Principal> getSubjectPrincipals(Subject subject) {
    if (subject.isReadOnly()) {
        return subject.getPrincipals();
    }

    List<Principal> principals = Arrays.asList(subject.getPrincipals().toArray(new Principal[0]));
    return Collections.unmodifiableList(principals);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:15,代碼來源:SubjectDelegator.java

示例12: main

import javax.security.auth.Subject; //導入方法依賴的package包/類
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");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:63,代碼來源:StandardCallbacks.java

示例13: main

import javax.security.auth.Subject; //導入方法依賴的package包/類
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;
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:29,代碼來源:Synch2.java

示例14: checkSubject

import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the principalName identity.
 */
private void checkSubject(String op) {
    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(op+": Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals(principalName))
        throw new SecurityException(op+": Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:SimpleStandard.java

示例15: check

import javax.security.auth.Subject; //導入方法依賴的package包/類
private void check(final Subject subject, final Function<Access, Boolean> accessCheck) {
    for (final Principal principal : subject.getPrincipals()) {
        final Access access = accesses.get(principal.getName());
        LOGGER.log(Level.FINE, "Check for principal: {0} -> {1}", new Object[]{principal.getName(), access});
        if (access != null && accessCheck.apply(access)) {
            return;
        }
    }

    throw new SecurityException("Illegal access");
}
 
開發者ID:MinBZK,項目名稱:OperatieBRP,代碼行數:12,代碼來源:PropertiesAccessController.java


注:本文中的javax.security.auth.Subject.getPrincipals方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。