javax.security.auth.Subject Java Examples

The following examples show how to use javax.security.auth.Subject. 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: KrbCredSubKey.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 9 votes vote down vote up
public static void main(String[] args) throws Exception {

        // We don't care about clock difference
        new FileOutputStream("krb5.conf").write(
                "[libdefaults]\nclockskew=999999999".getBytes());
        System.setProperty("java.security.krb5.conf", "krb5.conf");
        Config.refresh();

        Subject subj = new Subject();
        KerberosPrincipal kp = new KerberosPrincipal(princ);
        KerberosKey kk = new KerberosKey(
                kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0);
        subj.getPrincipals().add(kp);
        subj.getPrivateCredentials().add(kk);

        Subject.doAs(subj, new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                GSSManager man = GSSManager.getInstance();
                GSSContext ctxt = man.createContext(man.createCredential(
                        null, GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY));
                return ctxt.acceptSecContext(token, 0, token.length);
            }
        });
    }
 
Example #2
Source File: SecurityUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static <T> T doAs(
    Subject subject,
    PrivilegedExceptionAction<T> privilegedExceptionAction
) throws PrivilegedActionException {
  checkDoAsPermission();
  if (privilegedExceptionAction == null) {
    throw new RuntimeException("No privileged exception action provided");
  }

  // The bug this class patches only affects JDK 8 & 9. In later JDK not only the issue is fixed but
  // the code collides with this patch causing strange behavior due to concurrency issues/race conditions.
  // Apply only the patch for versions <9, use the JDK AccessController directly for 9+ versions.
  if (getJavaVersion() <= 9) {
    return AccessController.doPrivileged(privilegedExceptionAction,
        createContext(subject, AccessController.getContext()));
  } else {
    return AccessController.doPrivileged(privilegedExceptionAction, AccessController.getContext());
  }
}
 
Example #3
Source File: Context.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public Context impersonate(final String someone) throws Exception {
    try {
        GSSCredential creds = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
            @Override
            public GSSCredential run() throws Exception {
                GSSManager m = GSSManager.getInstance();
                GSSName other = m.createName(someone, GSSName.NT_USER_NAME);
                if (Context.this.cred == null) {
                    Context.this.cred = m.createCredential(GSSCredential.INITIATE_ONLY);
                }
                return ((ExtendedGSSCredential)Context.this.cred).impersonate(other);
            }
        });
        Context out = new Context();
        out.s = s;
        out.cred = creds;
        out.name = name + " as " + out.cred.getName().toString();
        return out;
    } catch (PrivilegedActionException pae) {
        throw pae.getException();
    }
}
 
Example #4
Source File: SemaphoreArrayListManagedConnectionPool.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a connection event listener
 *
 * @param subject the subject
 * @param cri the connection request information
 * @return the new listener
 * @throws ResourceException for any error
 */
private ConnectionListener createConnectionEventListener(Subject subject, ConnectionRequestInfo cri)
   throws ResourceException
{
   long start = pool.getInternalStatistics().isEnabled() ? System.currentTimeMillis() : 0L;

   ManagedConnection mc = mcf.createManagedConnection(subject, cri);

   if (pool.getInternalStatistics().isEnabled())
   {
      pool.getInternalStatistics().deltaTotalCreationTime(System.currentTimeMillis() - start);
      pool.getInternalStatistics().deltaCreatedCount();
   }
   try
   {
      return cm.createConnectionListener(mc, this);
   }
   catch (ResourceException re)
   {
      if (pool.getInternalStatistics().isEnabled())
         pool.getInternalStatistics().deltaDestroyedCount();
      mc.destroy();
      throw re;
   }
}
 
Example #5
Source File: NestedActions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object run() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    System.out.println("principals = " + subject.getPrincipals());

    try {
        Utils.writeFile(filename);
        new File(filename).delete();
        throw new RuntimeException(
                "Test failed: no AccessControlException thrown");
    } catch (AccessControlException ace) {
        System.out.println(
                "AccessControlException thrown as expected: "
                + ace.getMessage());
    }

    ReadFromFileNegativeAction readFromFile
            = new ReadFromFileNegativeAction(filename);
    return Subject.doAs(subject, readFromFile);
}
 
Example #6
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;
    
    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());
    
    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example #7
Source File: NotificationAccessControllerTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void fetchNotification(
    String connectionId,
    ObjectName name,
    Notification notification,
    Subject subject)
    throws SecurityException {
    echo("fetchNotification:");
    echo("\tconnectionId: " +  connectionId);
    echo("\tname: " +  name);
    echo("\tnotification: " +  notification);
    echo("\tsubject: " +
         (subject == null ? null : subject.getPrincipals()));
    if (!throwException)
        if (name.getCanonicalName().equals("domain:name=2,type=NB")
            &&
            subject != null
            &&
            subject.getPrincipals().contains(new JMXPrincipal("role")))
            throw new SecurityException();
}
 
Example #8
Source File: SubjectActions.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static LoginContext createLoginContext(String securityDomain, Subject subject,
   CallbackHandler handler)
   throws LoginException
{
   LoginContextAction action = new LoginContextAction(securityDomain, subject, handler);
   try
   {
      LoginContext lc = AccessController.doPrivileged(action);
      return lc;
   }
   catch(PrivilegedActionException e)
   {
      Exception ex = e.getException();
      if( ex instanceof LoginException )
         throw (LoginException) ex;
      else
         throw new LoginException(ex.getLocalizedMessage());
   }
}
 
Example #9
Source File: HelloWorldManagedConnectionFactory.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns a matched connection from the candidate set of connections. 
 *
 * @param connectionSet Candidate connection set
 * @param subject Caller's security information
 * @param cxRequestInfo Additional resource adapter specific connection request information
 * @throws ResourceException generic exception
 * @return ManagedConnection if resource adapter finds an acceptable match otherwise null 
 */
public ManagedConnection matchManagedConnections(Set connectionSet,
                                                 Subject subject, ConnectionRequestInfo cxRequestInfo) 
   throws ResourceException
{
   ManagedConnection result = null;

   Iterator it = connectionSet.iterator();
   while (result == null && it.hasNext()) 
   {
      ManagedConnection mc = (ManagedConnection)it.next();
      if (mc instanceof HelloWorldManagedConnection) 
      {
         HelloWorldManagedConnection hwmc = (HelloWorldManagedConnection)mc;
         result = hwmc;
      }
   }

   return result;
}
 
Example #10
Source File: SelfExpansion.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Subject s = new Subject();
    s.getPrincipals().add
            (new javax.security.auth.x500.X500Principal("CN=test"));
    s.getPrivateCredentials().add(new String("test"));
    try {
        Subject.doAsPrivileged(s, new PrivilegedAction() {
            public Object run() {
                java.util.Iterator i = Subject.getSubject
                            (AccessController.getContext
                            ()).getPrivateCredentials().iterator();
                return i.next();
            }
        }, null);
        System.out.println("Test succeeded");
    } catch (Exception e) {
        System.out.println("Test failed");
        e.printStackTrace();
        throw e;
    }
}
 
Example #11
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 #12
Source File: SwitchCaseIdentityAssertionFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoGroups() throws Exception {
  FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
  EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "upper" ).anyTimes();
  EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "upper" ).anyTimes();
  EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
  ServletContext context = EasyMock.createNiceMock(ServletContext.class);
  EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
  EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
  EasyMock.replay( config );
  EasyMock.replay( context );

  SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();

  Subject subject = new Subject();
  subject.getPrincipals().add(new PrimaryPrincipal( "[email protected]" ) );

  filter.init(config);
  String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
  String[] groups = filter.mapGroupPrincipals(actual, subject);
  assertThat( actual, is( "[email protected]" ) );
  assertThat( groups, is( nullValue() ) );

}
 
Example #13
Source File: NotificationAccessControllerTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void addNotificationListener(
    String connectionId,
    ObjectName name,
    Subject subject)
    throws SecurityException {
    echo("addNotificationListener:");
    echo("\tconnectionId: " +  connectionId);
    echo("\tname: " +  name);
    echo("\tsubject: " +
         (subject == null ? null : subject.getPrincipals()));
    if (throwException)
        if (name.getCanonicalName().equals("domain:name=1,type=NB")
            &&
            subject != null
            &&
            subject.getPrincipals().contains(new JMXPrincipal("role")))
            throw new SecurityException();
}
 
Example #14
Source File: SelectionManagerTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void selectWithDifferentPermissions() throws Exception {
    PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER.updateProperty("10");
    System.out.println("PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER=" +
                       PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER);
    System.setSecurityManager(securityManagerRejectingUser());

    RMCore.topologyManager = mock(TopologyManager.class);
    RMCore rmCore = mock(RMCore.class);
    when(RMCore.topologyManager.getHandler(Matchers.<TopologyDescriptor> any())).thenReturn(selectAllTopology());

    SelectionManager selectionManager = createSelectionManager(rmCore);

    ArrayList<RMNode> freeNodes = new ArrayList<>();
    freeNodes.add(createMockedNode("admin"));
    freeNodes.add(createMockedNode("user"));
    when(rmCore.getFreeNodes()).thenReturn(freeNodes);

    Criteria criteria = new Criteria(2);
    criteria.setTopology(TopologyDescriptor.ARBITRARY);

    Subject subject = Subjects.create("admin");
    NodeSet nodes = selectionManager.selectNodes(criteria, new Client(subject, false));

    assertEquals(1, nodes.size());
}
 
Example #15
Source File: Implies.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    X500Principal duke = new X500Principal("CN=Duke");
    // should not throw NullPointerException
    testImplies(duke, (Subject)null, false);

    Set<Principal> principals = new HashSet<>();
    principals.add(duke);
    testImplies(duke, principals, true);

    X500Principal tux = new X500Principal("CN=Tux");
    principals.add(tux);
    testImplies(duke, principals, true);

    principals.add(new KerberosPrincipal("[email protected]"));
    testImplies(duke, principals, true);

    principals.clear();
    principals.add(tux);
    testImplies(duke, principals, false);

    System.out.println("test passed");
}
 
Example #16
Source File: StormRestAPIClient.java    From streamline with Apache License 2.0 6 votes vote down vote up
private Map doGetRequest(String requestUrl) {
    try {
        LOG.debug("GET request to Storm cluster: " + requestUrl);
        return Subject.doAs(subject, new PrivilegedAction<Map>() {
            @Override
            public Map run() {
                return JsonClientUtil.getEntity(client.target(requestUrl), STORM_REST_API_MEDIA_TYPE, Map.class);
            }
        });
    } catch (RuntimeException ex) {
        Throwable cause = ex.getCause();
        // JsonClientUtil wraps exception, so need to compare
        if (cause instanceof javax.ws.rs.ProcessingException) {
            if (ex.getCause().getCause() instanceof IOException) {
                throw new StormNotReachableException("Exception while requesting " + requestUrl, ex);
            }
        } else if (cause instanceof WebApplicationException) {
            throw WrappedWebApplicationException.of((WebApplicationException)cause);
        }

        throw ex;
    }
}
 
Example #17
Source File: NestedActions.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object run() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    System.out.println("principals = " + subject.getPrincipals());

    try {
        Utils.writeFile(filename);
        new File(filename).delete();
        throw new RuntimeException(
                "Test failed: no AccessControlException thrown");
    } catch (AccessControlException ace) {
        System.out.println(
                "AccessControlException thrown as expected: "
                + ace.getMessage());
    }

    ReadFromFileNegativeAction readFromFile
            = new ReadFromFileNegativeAction(filename);
    return Subject.doAs(subject, readFromFile);
}
 
Example #18
Source File: KrbPasswordSaverLoginModule.java    From ranger with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void initialize(Subject subject, CallbackHandler callbackhandler, Map<String, ?> sharedMap, Map<String, ?> options) {
	
	this.sharedState = sharedMap;
	
	String userName = (options != null) ? (String)options.get(USERNAME_PARAM) : null;
	if (userName != null) {
		this.sharedState.put(USERNAME_PARAM,userName);
	}
	String password = (options != null) ? (String)options.get(PASSWORD_PARAM) : null;
	
	if (password != null) {
		this.sharedState.put(PASSWORD_PARAM,password.toCharArray());
	}
}
 
Example #19
Source File: Synch3.java    From jdk8u-dev-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 #20
Source File: RMIConnector.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected Integer addListenerForMBeanRemovedNotif()
throws IOException, InstanceNotFoundException {
    NotificationFilterSupport clientFilter =
            new NotificationFilterSupport();
    clientFilter.enableType(
            MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
    MarshalledObject<NotificationFilter> sFilter =
        new MarshalledObject<NotificationFilter>(clientFilter);

    Integer[] listenerIDs;
    final ObjectName[] names =
        new ObjectName[] {MBeanServerDelegate.DELEGATE_NAME};
    final MarshalledObject<NotificationFilter>[] filters =
        Util.cast(new MarshalledObject<?>[] {sFilter});
    final Subject[] subjects = new Subject[] {null};
    try {
        listenerIDs =
                connection.addNotificationListeners(names,
                filters,
                subjects);

    } catch (IOException ioe) {
        communicatorAdmin.gotIOException(ioe);

        listenerIDs =
                connection.addNotificationListeners(names,
                filters,
                subjects);
    }
    return listenerIDs[0];
}
 
Example #21
Source File: HelloWorldManagedConnectionImpl.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
/**
 * @see ManagedConnection#getConnection(Subject, ConnectionRequestInfo)
 */
public Object getConnection(
	Subject subject,
	ConnectionRequestInfo cxRequestInfo)
	throws ResourceException {

	connection = new HelloWorldConnectionImpl(this);
	return connection;
}
 
Example #22
Source File: SimpleStandard.java    From jdk8u-jdk 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 #23
Source File: RuleBasedAccessControlTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccessIsDeniedIfRuleThrowsException() throws Exception
{
    final Subject subject = TestPrincipalUtils.createTestSubject("user1");
    final InetAddress inetAddress = InetAddress.getLocalHost();
    final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1);

    AMQPConnection connectionModel = mock(AMQPConnection.class);
    when(connectionModel.getRemoteSocketAddress()).thenReturn(inetSocketAddress);

    subject.getPrincipals().add(new ConnectionPrincipal(connectionModel));

    Subject.doAs(subject, new PrivilegedExceptionAction<Object>()
    {
        @Override
        public Object run() throws Exception
        {


            RuleSet mockRuleSet = mock(RuleSet.class);
            when(mockRuleSet.check(
                    subject,
                    LegacyOperation.ACCESS,
                    ObjectType.VIRTUALHOST,
                    ObjectProperties.EMPTY)).thenThrow(new RuntimeException());

            RuleBasedAccessControl accessControl = new RuleBasedAccessControl(mockRuleSet,
                                                                              BrokerModel.getInstance());
            Result result = accessControl.authorise(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY);

            assertEquals(Result.DENIED, result);
            return null;
        }
    });

}
 
Example #24
Source File: RMIConnector.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
protected Integer addListenerForMBeanRemovedNotif()
throws IOException, InstanceNotFoundException {
    NotificationFilterSupport clientFilter =
            new NotificationFilterSupport();
    clientFilter.enableType(
            MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
    MarshalledObject<NotificationFilter> sFilter =
        new MarshalledObject<NotificationFilter>(clientFilter);

    Integer[] listenerIDs;
    final ObjectName[] names =
        new ObjectName[] {MBeanServerDelegate.DELEGATE_NAME};
    final MarshalledObject<NotificationFilter>[] filters =
        Util.cast(new MarshalledObject<?>[] {sFilter});
    final Subject[] subjects = new Subject[] {null};
    try {
        listenerIDs =
                connection.addNotificationListeners(names,
                filters,
                subjects);

    } catch (IOException ioe) {
        communicatorAdmin.gotIOException(ioe);

        listenerIDs =
                connection.addNotificationListeners(names,
                filters,
                subjects);
    }
    return listenerIDs[0];
}
 
Example #25
Source File: OAuth2PreemptiveAuthenticatorTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttemptAuthenticationUnauthorizedUser() throws Exception
{
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getServerName()).thenReturn("localhost");
    when(mockRequest.getHeader("Authorization")).thenReturn("Bearer " + TEST_UNAUTHORIZED_ACCESS_TOKEN);
    Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration);
    assertNotNull("Authenticator failed unexpectedly", subject);
    final Set<Principal> principals = subject.getPrincipals();
    assertEquals("Subject created with unexpected principal",
                        TEST_UNAUTHORIZED_USER,
                        principals.iterator().next().getName());
}
 
Example #26
Source File: SubjectDelegator.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
public AccessControlContext
    delegatedContext(AccessControlContext authenticatedACC,
                     Subject delegatedSubject,
                     boolean removeCallerContext)
        throws SecurityException {

    if (System.getSecurityManager() != null && authenticatedACC == null) {
        throw new SecurityException("Illegal AccessControlContext: null");
    }

    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
    final Collection<Permission> permissions = new ArrayList<>(ps.size());
    for(Principal p : ps) {
        final String pname = p.getClass().getName() + "." + p.getName();
        permissions.add(new SubjectDelegationPermission(pname));
    }
    PrivilegedAction<Void> action =
        new PrivilegedAction<Void>() {
            public Void run() {
                for (Permission sdp : permissions) {
                    AccessController.checkPermission(sdp);
                }
                return null;
            }
        };
    AccessController.doPrivileged(action, authenticatedACC);

    return getDelegatedAcc(delegatedSubject, removeCallerContext);
}
 
Example #27
Source File: Context.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Does something using the Subject inside
 * @param action the action
 * @param in the input byte
 * @return the output byte
 * @throws java.lang.Exception
 */
public byte[] doAs(final Action action, final byte[] in) throws Exception {
    try {
        return Subject.doAs(s, new PrivilegedExceptionAction<byte[]>() {

            @Override
            public byte[] run() throws Exception {
                return action.run(Context.this, in);
            }
        });
    } catch (PrivilegedActionException pae) {
        throw pae.getException();
    }
}
 
Example #28
Source File: GetLocalHostWithSM.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

            // try setting the local hostname
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost.isLoopbackAddress()) {
                System.err.println("Local host name is resolved into a loopback address. Quit now!");
                return;
            }
            System.setProperty("host.name", localHost.
                                            getHostName());
            String policyFileName = System.getProperty("test.src", ".") +
                          "/" + "policy.file";
            System.setProperty("java.security.policy", policyFileName);
            System.setSecurityManager(new SecurityManager());

            InetAddress localHost1 = null;
            InetAddress localHost2 = null;

            localHost1 = InetAddress.getLocalHost();

            Subject mySubject = new Subject();
            MyPrincipal userPrincipal = new MyPrincipal("test");
            mySubject.getPrincipals().add(userPrincipal);
            localHost2 = (InetAddress)Subject.doAsPrivileged(mySubject,
                                new MyAction(), null);

            if (localHost1.equals(localHost2)) {
                System.out.println("localHost1 = " + localHost1);
                throw new RuntimeException("InetAddress.getLocalHost() test " +
                                           " fails. localHost2 should be " +
                                           " the real address instead of " +
                                           " the loopback address."+localHost2);
            }
        }
 
Example #29
Source File: RMIConnectionImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public boolean isInstanceOf(ObjectName name,
                            String className,
                            Subject delegationSubject)
    throws InstanceNotFoundException, IOException {

    checkNonNull("ObjectName", name);

    try {
        final Object params[] = new Object[] { name, className };

        if (logger.debugOn())  logger.debug("isInstanceOf",
                                "connectionId=" + connectionId
                                +", name="+name
                                +", className="+className);

        return ((Boolean)
            doPrivilegedOperation(
              IS_INSTANCE_OF,
              params,
              delegationSubject)).booleanValue();
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example #30
Source File: KerberosUsernamePasswordAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if user was successfully authenticated against Kerberos
 *
 * @param username username without Kerberos realm attached
 * @param password kerberos password
 * @return  true if user was successfully authenticated
 */
public Subject authenticateSubject(String username, String password) throws LoginException {
    String principal = getKerberosPrincipal(username);

    logger.debug("Validating password of principal: " + principal);
    loginContext = new LoginContext("does-not-matter", null,
            createJaasCallbackHandler(principal, password),
            createJaasConfiguration());

    loginContext.login();
    logger.debug("Principal " + principal + " authenticated succesfully");
    return loginContext.getSubject();
}