@Test public void testFileBasedAuthorization() throws Exception { final AuthorizationProvider auth = new FileBasedAuthorizationProvider("../org.csstudio.security/authorization.conf"); // "fred" is listed for full alarm access Subject user = new Subject(); user.getPrincipals().add(new UserPrincipal("fred")); Authorizations authorizations = auth.getAuthorizations(user); System.out.println(user); System.out.println(authorizations); assertThat(authorizations.haveAuthorization("alarm_ack"), equalTo(true)); assertThat(authorizations.haveAuthorization("alarm_config"), equalTo(true)); // "linux-admin" is one of the ".*-admin". May do anything user = new Subject(); user.getPrincipals().add(new UserPrincipal("linux-admin")); authorizations = auth.getAuthorizations(user); System.out.println(user); System.out.println(authorizations); assertThat(authorizations.haveAuthorization("alarm_config"), equalTo(true)); assertThat(authorizations.haveAuthorization("unspeakable-stuff"), equalTo(true)); // "Egon" can ack' (because anybody may do that), but not config user = new Subject(); user.getPrincipals().add(new UserPrincipal("Egon")); authorizations = auth.getAuthorizations(user); System.out.println(user); System.out.println(authorizations); assertThat(authorizations.haveAuthorization("alarm_ack"), equalTo(true)); assertThat(authorizations.haveAuthorization("alarm_config"), equalTo(false)); }
/** * This method is called if the LoginContext's overall authentication succeeded. * * <p>Using the SSO user name, saved by the previosuly executed login() operation, obtains from * the gateway the roles associated with the user and fills the Subject with the user and role * principals. If this LoginModule's own authentication attempted failed, then this method removes * any state that was originally saved. * * @exception javax.security.auth.login.LoginException if the commit fails. * @return true if this LoginModule's own login and commit attempts succeeded, or false otherwise. */ public boolean commit() throws LoginException { if (_succeeded == false) { return false; } else { try { // Add the SSOUser as a Principal if (!_subject.getPrincipals().contains(_ssoUserPrincipal)) { _subject.getPrincipals().add(_ssoUserPrincipal); } logger.debug("Added SSOUser Principal to the Subject : " + _ssoUserPrincipal); _ssoRolePrincipals = getRoleSets(); // Add to the Subject the SSORoles associated with the SSOUser . for (int i = 0; i < _ssoRolePrincipals.length; i++) { if (_subject.getPrincipals().contains(_ssoRolePrincipals[i])) continue; _subject.getPrincipals().add(_ssoRolePrincipals[i]); logger.debug("Added SSORole Principal to the Subject : " + _ssoRolePrincipals[i]); } commitSucceeded = true; return true; } catch (Exception e) { logger.error("Session login failed for Principal : " + _ssoUserPrincipal, e); throw new LoginException("Session login failed for Principal : " + _ssoUserPrincipal); } finally { // in any case, clean out state clearCredentials(); } } }
/** * Logout the user * * <p>This method removes the Principals associated with the {@code Subject}. * * @exception LoginException if the logout fails * @return true in all cases (this {@code LoginModule} should not be ignored). */ public boolean logout() throws LoginException { if (subject.isReadOnly()) { throw new LoginException("logout Failed: Subject is Readonly"); } // remove the added Principals from the Subject subject.getPrincipals().remove(userPrincipal); subject.getPrincipals().remove(UIDPrincipal); subject.getPrincipals().remove(GIDPrincipal); for (int i = 0; i < supplementaryGroups.size(); i++) { subject.getPrincipals().remove(supplementaryGroups.get(i)); } // clean out state ss = null; succeeded = false; commitSucceeded = false; userPrincipal = null; UIDPrincipal = null; GIDPrincipal = null; supplementaryGroups = new LinkedList<UnixNumericGroupPrincipal>(); if (debug) { System.out.println("\t\t[UnixLoginModule]: " + "logged out Subject"); } return true; }
public final void testImpliesMember() { GroupPermission p1; Permission p2; Subject s; // <groupmember> implies TestGroup if Subject has GroupPermission("TestGroup") p1 = new GroupPermission("*:<groupmember>", "view"); p2 = new GroupPermission("*:TestGroup", "view"); s = new Subject(); s.getPrincipals().add(new GroupPrincipal("MyWiki", "TestGroup")); assertTrue(subjectImplies(s, p1, p2)); // <groupmember> doesn't imply it if Subject has no GroupPermission("TestGroup") s = new Subject(); s.getPrincipals().add(new WikiPrincipal("TestGroup")); assertFalse(subjectImplies(s, p1, p2)); // <groupmember> doesn't imply it if Subject's GP doesn't match s = new Subject(); s.getPrincipals().add(new GroupPrincipal("MyWiki", "FooGroup")); assertFalse(subjectImplies(s, p1, p2)); // <groupmember> doesn't imply it if p2 isn't GroupPermission type p2 = new PagePermission("*:TestGroup", "view"); s = new Subject(); s.getPrincipals().add(new GroupPrincipal("MyWiki", "TestGroup")); assertFalse(subjectImplies(s, p1, p2)); // <groupmember> implies TestGroup if not called with Subject combiner p1 = new GroupPermission("*:<groupmember>", "view"); p2 = new GroupPermission("*:TestGroup", "view"); assertFalse(p1.impliesMember(p2)); }
/** * Merges the two {@link Subject}s in to a new {@link Subject}. The new subjects contains all the * {@link Principal}s from both subjects. If {@link #retainSubjectsPrivateCredentials} is true * then the new subject will contain all the private credentials from both subjects, if not the * new subject will not contain private credentials. If {@link #retainSubjectsPublicCredentials} * is true then the new subject will contain all the public credentials from both subjects, if not * the new subject will not contain public credentials. * * @param subject1 first subject to merge, may be null * @param subject2 second subject to merge, may be null * @return subject containing the merged information */ protected Subject mergeSubjects(Subject subject1, Subject subject2) { if (subject1 == null && subject2 == null) { return new Subject(); } if (subject1 == null) { return subject2; } if (subject2 == null) { return subject1; } Set<Principal> principals = new HashSet<Principal>(3); principals.addAll(subject1.getPrincipals()); principals.addAll(subject2.getPrincipals()); Set<Object> publicCredentials = new HashSet<Object>(3); if (retainSubjectsPublicCredentials) { LOG.debug("Merging in subjects public credentials"); publicCredentials.addAll(subject1.getPublicCredentials()); publicCredentials.addAll(subject2.getPublicCredentials()); } Set<Object> privateCredentials = new HashSet<Object>(3); if (retainSubjectsPrivateCredentials) { LOG.debug("Merging in subjects private credentials"); privateCredentials.addAll(subject1.getPrivateCredentials()); privateCredentials.addAll(subject2.getPrivateCredentials()); } return new Subject(false, principals, publicCredentials, privateCredentials); }
private boolean checkSubject(IoSessionEx session) { Subject subject = session.getSubject(); assertNotNull(subject); Set<Principal> principles = subject.getPrincipals(); assertEquals(2, principles.size()); Principal user = subject.getPrincipals(UserPrincipal.class).iterator().next(); return user != null && user.getName().equals("joe"); }
Subject getAuthenticationToken(String domain, String username, String password) { Subject subject = new Subject(); subject.getPrincipals().add(new DomainPrincipal(domain)); subject .getPrincipals() .add(new EncodedUsernamePasswordPrincipal(username, password.toCharArray())); return subject; }
/** * @see * org.jboss.as.domain.management.security.SubjectSupplemental#supplementSubject(javax.security.auth.Subject) */ public void supplementSubject(Subject subject) throws IOException { Set<RealmUser> users = subject.getPrincipals(RealmUser.class); Set<Principal> principals = subject.getPrincipals(); Properties properties = getProperties(); // In general we expect exactly one RealmUser, however we could cope with multiple // identities so load the groups for them all. for (RealmUser current : users) { principals.addAll(loadGroups(properties, current)); } }
@Override public String value() { final Subject currentSubject = Subject.getSubject(AccessController.getContext()); if (currentSubject == null || currentSubject.getPrincipals().isEmpty()) { return null; } final Principal principal = currentSubject.getPrincipals().iterator().next(); return (principal != null ? principal.getName() : null); }
/** * Return value is based on the presents and value of the {@code * X-JASPI-AUTH-MODULE-ONE-VALIDATE-REQUEST} request header. * * @param messageInfo {@inheritDoc} * @param clientSubject {@inheritDoc} * @param serviceSubject {@inheritDoc} * @return {@inheritDoc} * @throws AuthException {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public AuthStatus validateRequest( MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); String header = request.getHeader(AUTH_MODULE_ONE_VALIDATE_REQUEST_HEADER_NAME.toLowerCase()); clientSubject.getPrincipals().clear(); clientSubject .getPrincipals() .add( new Principal() { @Override public String getName() { return AUTH_MODULE_ONE_PRINCIPAL; } }); Map<String, Object> context = (Map<String, Object>) messageInfo.getMap().get(JaspiRuntime.ATTRIBUTE_AUTH_CONTEXT); context.put(AUTH_MODULE_ONE_CONTEXT_ENTRY, true); if (SUCCESS_AUTH_STATUS.equalsIgnoreCase(header)) { return AuthStatus.SUCCESS; } if (SEND_SUCCESS_AUTH_STATUS.equalsIgnoreCase(header)) { return AuthStatus.SEND_SUCCESS; } if (SEND_FAILURE_AUTH_STATUS.equalsIgnoreCase(header)) { return AuthStatus.SEND_FAILURE; } if (SEND_CONTINUE_AUTH_STATUS.equalsIgnoreCase(header)) { return AuthStatus.SEND_CONTINUE; } if (FAILURE_AUTH_STATUS.equalsIgnoreCase(header)) { return AuthStatus.FAILURE; } if (NULL_AUTH_STATUS.equalsIgnoreCase(header)) { return null; } throw new AuthException( AUTH_MODULE_ONE_VALIDATE_REQUEST_HEADER_NAME + " header not set, so throwing AuthException."); }
/** * @return <code>true</code> if this method succeeded, or <code>false</code> if this <code> * LoginModule</code> should be ignored. * @throws LoginException if the logout fails * @see javax.security.auth.spi.LoginModule#logout() */ public boolean logout() throws LoginException { if (subject.getPrincipals().isEmpty() || subject.getPublicCredentials(Credentials.class).isEmpty()) { return false; } else { // clear subject if not readonly if (!subject.isReadOnly()) { subject.getPrincipals().clear(); subject.getPublicCredentials().clear(); } return true; } }
/** @see javax.security.auth.spi.LoginModule#logout() */ @Override public boolean logout() throws LoginException { // remove JAASRole from subject subject.getPrincipals().remove(userPrincipal); // remove JAASPrincipal from subject subject.getPrincipals().removeAll(rolePrincipals); // reset state variables resetStateData(); return true; }
public void handleMessage(Message message) throws Fault { SecurityContext context = message.get(SecurityContext.class); if (context == null) { return; } Principal principal = context.getUserPrincipal(); UsernameToken usernameToken = (UsernameToken) message.get(SecurityToken.class); if (principal == null || usernameToken == null || !principal.getName().equals(usernameToken.getName())) { return; } // Read the user from Syncope and get the roles WebClient client = WebClient.create(address, Collections.singletonList(new JacksonJsonProvider())); String authorizationHeader = "Basic " + Base64Utility.encode( (usernameToken.getName() + ":" + usernameToken.getPassword()).getBytes()); client.header("Authorization", authorizationHeader); client = client.path("users/self"); UserTO user = null; try { user = client.get(UserTO.class); if (user == null) { Exception exception = new Exception("Authentication failed"); throw new Fault(exception); } } catch (RuntimeException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new Fault(ex); } // Now get the roles List<MembershipTO> membershipList = user.getMemberships(); Subject subject = new Subject(); subject.getPrincipals().add(principal); for (MembershipTO membership : membershipList) { String roleName = membership.getRoleName(); subject.getPrincipals().add(new SimpleGroup(roleName, usernameToken.getName())); } subject.setReadOnly(); message.put(SecurityContext.class, new DefaultSecurityContext(principal, subject)); }
/** * Commit the authentication (second phase). * * <p>This method is called if the LoginContext's overall authentication succeeded (the relevant * REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded). * * <p>If this LoginModule's own authentication attempt succeeded (the importing of the Unix * authentication information succeeded), then this method associates the Unix Principals with the * {@code Subject} currently tied to the {@code LoginModule}. If this LoginModule's authentication * attempted failed, then this method removes any state that was originally saved. * * @exception LoginException if the commit fails * @return true if this LoginModule's own login and commit attempts succeeded, or false otherwise. */ public boolean commit() throws LoginException { if (succeeded == false) { if (debug) { System.out.println( "\t\t[UnixLoginModule]: " + "did not add any Principals to Subject " + "because own authentication failed."); } return false; } else { if (subject.isReadOnly()) { throw new LoginException("commit Failed: Subject is Readonly"); } if (!subject.getPrincipals().contains(userPrincipal)) subject.getPrincipals().add(userPrincipal); if (!subject.getPrincipals().contains(UIDPrincipal)) subject.getPrincipals().add(UIDPrincipal); if (!subject.getPrincipals().contains(GIDPrincipal)) subject.getPrincipals().add(GIDPrincipal); for (int i = 0; i < supplementaryGroups.size(); i++) { if (!subject.getPrincipals().contains(supplementaryGroups.get(i))) subject.getPrincipals().add(supplementaryGroups.get(i)); } if (debug) { System.out.println("\t\t[UnixLoginModule]: " + "added UnixPrincipal,"); System.out.println("\t\t\t\tUnixNumericUserPrincipal,"); System.out.println("\t\t\t\tUnixNumericGroupPrincipal(s),"); System.out.println("\t\t\t to Subject"); } commitSucceeded = true; return true; } }
/** * Logout the user. * * <p>This method removes the SSO User and Role Principals from the Subject that were added by the * commit() method. * * @exception javax.security.auth.login.LoginException if the logout fails. * @return true in all cases since this LoginModule should not be ignored. */ public boolean logout() throws LoginException { _subject.getPrincipals().remove(_ssoUserPrincipal); logger.debug("Removed SSOUser Principal from Subject : " + _ssoUserPrincipal); // Remove all the SSORole Principals from the Subject. for (int i = 0; i < _ssoRolePrincipals.length; i++) { _subject.getPrincipals().remove(_ssoRolePrincipals[i]); logger.debug("Removed SSORole Principal from Subject : " + _ssoRolePrincipals[i]); } _succeeded = commitSucceeded; clearCredentials(); return true; }
@Override public boolean commit() throws LoginException { subject .getPrincipals() .add( new Principal() { @Override public String getName() { return "AUTHORIZED"; } }); subject.getPrincipals().add(userPrincipal); return true; }
/** * Put user into realm. * * @param userName The user to add * @param credential The users Credentials * @param roles The users roles * @return UserIdentity */ public synchronized UserIdentity putUser(String userName, Credential credential, String[] roles) { Principal userPrincipal = new KnownUser(userName, credential); Subject subject = new Subject(); subject.getPrincipals().add(userPrincipal); subject.getPrivateCredentials().add(credential); if (roles != null) for (String role : roles) subject.getPrincipals().add(new RolePrincipal(role)); subject.setReadOnly(); UserIdentity identity = _identityService.newUserIdentity(subject, userPrincipal, roles); _users.put(userName, identity); return identity; }
/** * Commits the authentication (second phase). * * <p>This method is called if the LoginContext's overall authentication succeeded. The * implementation first checks if there is already Tachyon user in the subject. If not, it adds * the previously logged in Tachyon user into the subject. * * @return true if a Tachyon user if found or created. * @throws LoginException not Tachyon user is found or created. */ @Override public boolean commit() throws LoginException { // if there is already a Tachyon user, it's done. if (!mSubject.getPrincipals(User.class).isEmpty()) { return true; } // add the logged in user into subject if (mUser != null) { mSubject.getPrincipals().add(mUser); return true; } // throw exception if no Tachyon user is found or created. throw new LoginException("Cannot find a user"); }
public void generate() throws SAXException, ProcessingException { if (log.isDebugEnabled()) log.debug("begin generate"); contentHandler.startDocument(); Document doc = XercesHelper.getNewDocument(); Element root = doc.createElement("authentication"); doc.appendChild(root); try { LoginContext lc = new LoginContext(jaasRealm, new InternalCallbackHandler()); lc.login(); Subject s = lc.getSubject(); if (log.isDebugEnabled()) log.debug("Subject is: " + s.getPrincipals().toString()); Element idElement = doc.createElement("ID"); root.appendChild(idElement); Iterator it = s.getPrincipals(java.security.Principal.class).iterator(); while (it.hasNext()) { Principal prp = (Principal) it.next(); if (prp.getName().equalsIgnoreCase("Roles")) { Element roles = doc.createElement("roles"); root.appendChild(roles); Group grp = (Group) prp; Enumeration member = grp.members(); while (member.hasMoreElements()) { Principal sg = (Principal) member.nextElement(); Element role = doc.createElement("role"); roles.appendChild(role); Text txt = doc.createTextNode(sg.getName()); role.appendChild(txt); } } else { Node nde = doc.createTextNode(prp.getName()); idElement.appendChild(nde); } } lc.logout(); } catch (Exception exe) { log.warn("Could not login user \"" + userid + "\""); } finally { try { DOMStreamer ds = new DOMStreamer(contentHandler); ds.stream(doc.getDocumentElement()); contentHandler.endDocument(); } catch (Exception exe) { log.error("Error streaming to dom", exe); } if (log.isDebugEnabled()) log.debug("end generate"); } }
@Test public void shouldValidateRequestWhenUsernameHeaderIsEmptyString() throws AuthException { // Given MessageInfoContext messageInfo = mock(MessageInfoContext.class); Subject clientSubject = new Subject(); Subject serviceSubject = new Subject(); Request request = new Request(); given(messageInfo.getRequest()).willReturn(request); request.getHeaders().put("X-OpenIDM-Username", ""); request.getHeaders().put("X-OpenIDM-Password", "PASSWORD"); // When AuthStatus authStatus = module .validateRequest(messageInfo, clientSubject, serviceSubject) .getOrThrowUninterruptibly(); // Then verifyZeroInteractions(authenticator); assertTrue(clientSubject.getPrincipals().isEmpty()); assertEquals(authStatus, AuthStatus.SEND_FAILURE); }
@Test(enabled = true) public void shouldValidateRequestWhenAuthenticationFailed() throws ResourceException, AuthException { // Given MessageInfoContext messageInfo = mock(MessageInfoContext.class); AuthenticatorResult authResult = mock(AuthenticatorResult.class); Subject clientSubject = new Subject(); Subject serviceSubject = new Subject(); Map<String, Object> messageInfoMap = new HashMap<String, Object>(); Map<String, Object> auditInfoMap = new HashMap<String, Object>(); Request request = new Request(); given(messageInfo.getRequest()).willReturn(request); request.getHeaders().put("X-OpenIDM-Username", "USERNAME"); request.getHeaders().put("X-OpenIDM-Password", "PASSWORD"); given(messageInfo.getRequestContextMap()).willReturn(messageInfoMap); messageInfoMap.put(AuditTrail.AUDIT_INFO_KEY, auditInfoMap); given(authResult.isAuthenticated()).willReturn(false); given(authenticator.authenticate(eq("USERNAME"), eq("PASSWORD"), Matchers.<Context>anyObject())) .willReturn(authResult); // When AuthStatus authStatus = module .validateRequest(messageInfo, clientSubject, serviceSubject) .getOrThrowUninterruptibly(); // Then assertTrue(clientSubject.getPrincipals().isEmpty()); assertEquals(authStatus, AuthStatus.SEND_FAILURE); }
/** @return the {@link UserGroupInformation} for the current thread */ public static UserGroupInformation getCurrentUGI() { Subject user = getCurrentUser(); if (user == null) { user = currentUser.get(); if (user == null) { return null; } } Set<UserGroupInformation> ugiPrincipals = user.getPrincipals(UserGroupInformation.class); UserGroupInformation ugi = null; if (ugiPrincipals != null && ugiPrincipals.size() == 1) { ugi = ugiPrincipals.iterator().next(); if (ugi == null) { throw new RuntimeException("Cannot find _current user_ UGI in the Subject!"); } } else { throw new RuntimeException( "Cannot resolve current user from subject, " + "which had " + ugiPrincipals.size() + " UGI principals!"); } return ugi; }
/** * Logout a user. * * <p>This method removes the Principals that were added by the <code>commit</code> method. * * @exception LoginException if the logout fails. * @return true in all cases since this <code>LoginModule</code> should not be ignored. */ public boolean logout() throws LoginException { if (subject.isReadOnly()) { cleanState(); throw new LoginException("Subject is read-only"); } Set principals = subject.getPrincipals(); principals.remove(ldapPrincipal); principals.remove(userPrincipal); if (authzIdentity != null) { principals.remove(authzPrincipal); } // clean out state cleanState(); succeeded = false; commitSucceeded = false; ldapPrincipal = null; userPrincipal = null; authzPrincipal = null; if (debug) { System.out.println("\t\t[LdapLoginModule] logged out Subject"); } return true; }
/* */ private static synchronized String makeConnectionId( String paramString, Subject paramSubject) /* */ { /* 472 */ connectionIdNumber += 1; /* */ /* 474 */ String str1 = ""; /* */ try { /* 476 */ str1 = RemoteServer.getClientHost(); /* */ } catch (ServerNotActiveException localServerNotActiveException) { /* 478 */ logger.trace("makeConnectionId", "getClientHost", localServerNotActiveException); /* */ } /* */ /* 481 */ StringBuilder localStringBuilder = new StringBuilder(); /* 482 */ localStringBuilder.append(paramString).append(":"); /* 483 */ if (str1.length() > 0) /* 484 */ localStringBuilder.append("//").append(str1); /* 485 */ localStringBuilder.append(" "); /* */ String str2; /* */ Iterator localIterator; /* 486 */ if (paramSubject != null) { /* 487 */ Set localSet = paramSubject.getPrincipals(); /* 488 */ str2 = ""; /* 489 */ for (localIterator = localSet.iterator(); localIterator.hasNext(); ) { /* 490 */ Principal localPrincipal = (Principal) localIterator.next(); /* 491 */ String str3 = localPrincipal.getName().replace(' ', '_').replace(';', ':'); /* 492 */ localStringBuilder.append(str2).append(str3); /* 493 */ str2 = ";"; /* */ } /* */ } /* 496 */ localStringBuilder.append(" ").append(connectionIdNumber); /* 497 */ if (logger.traceOn()) /* 498 */ logger.trace("newConnectionId", "connectionId=" + localStringBuilder); /* 499 */ return localStringBuilder.toString(); /* */ }
@Override public boolean authenticate(HttpServletRequest request, Subject subject) throws LoginException, ServletException { String authorization = request.getHeader("Authorization"); if (authorization != null) { String authBase64 = authorization.substring(authorization.indexOf(' ') + 1); String[] credentials = new String(Base64.decode(authBase64)).split(":"); if (credentials.length == 0) { return false; } String userName = credentials[0]; String password; if (credentials.length > 1) { password = credentials[1]; } else { password = ""; } try { if (authenticationService.authenticateUser(userName, password)) { subject.getPrincipals().remove(UserUtil.ANONYMOUS); subject.getPrincipals().add(new PrincipalImpl(userName)); return true; } else { throw new LoginException(LoginException.PASSWORD_NOT_MATCHING); } } catch (NoSuchAgent ex) { throw new LoginException(LoginException.USER_NOT_EXISTING); } } else { return false; } }
protected void validateSubject(Subject subject, String userIdString) { Assert.assertNotNull(subject); Set<Principal> userPrincipals = subject.getPrincipals(); Assert.assertNotNull(userPrincipals); Iterator<Principal> iterator = userPrincipals.iterator(); Assert.assertTrue(iterator.hasNext()); while (iterator.hasNext()) { Principal principal = iterator.next(); if (principal instanceof PortalRole) { PortalRole portalRole = (PortalRole) principal; Assert.assertEquals("users", portalRole.getName()); } else { PortalPrincipal portalPrincipal = (PortalPrincipal) principal; Assert.assertEquals(userIdString, portalPrincipal.getName()); } } }
public SessionTerminal() throws IOException { try { this.terminal = new Terminal(TERM_WIDTH, TERM_HEIGHT); terminal.write("\u001b\u005B20\u0068"); // set newline mode on in = new PipedOutputStream(); out = new PipedInputStream(); PrintStream pipedOut = new PrintStream(new PipedOutputStream(out), true); final Subject subject = new Subject(); subject.getPrincipals().add(new UserPrincipal("karaf")); Console console = consoleFactory.create( commandProcessor, new PipedInputStream(in), pipedOut, pipedOut, new WebTerminal(TERM_WIDTH, TERM_HEIGHT), null); consoleFactory.startConsoleAs(console, subject); } catch (IOException e) { e.printStackTrace(); throw e; } catch (Exception e) { e.printStackTrace(); throw (IOException) new IOException().initCause(e); } new Thread(this).start(); }
/** * Retrieves the ExecutionContext in which the current thread executes. * * @return the ExecutionContext in which the current thread executes. */ private static ExecutionContext getExecutionContext() { ExecutionContext ec = null; final AccessControlContext acc = AccessController.getContext(); Subject subj = (Subject) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { Subject subj = Subject.getSubject(acc); return subj; } }); if (subj != null) { Iterator it = subj.getPrincipals().iterator(); Principal p = null; while (it.hasNext()) { p = (Principal) it.next(); if (p instanceof ExecutionPrincipal) { ec = ((ExecutionPrincipal) p).getExecutionContext(); break; } } } return ec; }
/** Test the expected security context exists via the SecurityAssociation accessors */ public void testSecurityContext() { authPrincipal = new SimplePrincipal("jduke"); authSubject = new Subject(); authSubject.getPrincipals().add(authPrincipal); SecurityAssociation.pushSubjectContext(authSubject, authPrincipal, "theduke"); validateSettings(false); }
public static boolean isImpersonating(Subject subject) { boolean impersonating = false; impersonating = (subject.getPrincipals(ImpersonatedPrincipal.class).size() > 0); return impersonating; }