Java Code Examples for javax.security.auth.Subject#doAs()
The following examples show how to use
javax.security.auth.Subject#doAs() .
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: IdentityManagerImpl.java From peer-os with Apache License 2.0 | 6 votes |
@PermitAll @Override public void runAs( Session userSession, final Callable action ) { if ( userSession != null ) { Subject.doAs( userSession.getSubject(), new PrivilegedAction<Void>() { @Override public Void run() { try { action.call(); } catch ( Exception ex ) { LOGGER.error( "**** Error!! Error running privileged action.", ex ); } return null; } } ); } }
Example 2
Source File: GssClient.java From ats-framework with Apache License 2.0 | 6 votes |
/** * Called when SPNEGO client-service authentication is taking place. * * @param context * @param negotiationToken * @return * @throws GSSException */ public byte[] negotiate( GSSContext context, byte[] negotiationToken ) throws GSSException { if (subject == null) { loginViaJAAS(); // throw GSSException if fail to login } // If we do not have the service ticket it will be retrieved // from the TGS on a call to initSecContext(). NegotiateContextAction negotiationAction = new NegotiateContextAction(context, negotiationToken); // Run the negotiation as the initiator // The service ticket will then be cached in the Subject's // private credentials, as the subject. negotiationToken = (byte[]) Subject.doAs(subject, negotiationAction); if (negotiationAction.getGSSException() != null) { throw negotiationAction.getGSSException(); } return negotiationToken; }
Example 3
Source File: MLModelRegistryClient.java From streamline with Apache License 2.0 | 6 votes |
public String getMLModelContents(String modelName) { try { Response response = Subject.doAs(subject, new PrivilegedAction<Response>() { @Override public Response run() { return client.target(String.format("%s/%s/%s", modelRegistryURL, "pmml", modelName)).request().get(); } }); if(response.getStatus() != OK.getStatusCode()) { throw new RuntimeException( String.format("Error occurred while getting the response %s", response.getStatus())); } else { return response.readEntity(String.class); } } catch (Exception exception) { LOG.error(String.format("An error was thrown while reading the pmml file contents for %s", modelName), exception); throw new RuntimeException(exception); } }
Example 4
Source File: SimpleLDAPAuthenticationManagerImpl.java From qpid-broker-j with Apache License 2.0 | 6 votes |
private <T> T invokeContextOperationAs(final Subject identity, final PrivilegedExceptionAction<T> action) throws NamingException { try { return Subject.doAs(identity, action); } catch (PrivilegedActionException e) { final Exception exception = e.getException(); if (exception instanceof NamingException) { throw (NamingException) exception; } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new ServerScopedRuntimeException(exception); } } }
Example 5
Source File: LoginContextInvocationHandler.java From pentaho-kettle with Apache License 2.0 | 6 votes |
@Override public Object invoke( Object proxy, final Method method, final Object[] args ) throws Throwable { try { return Subject.doAs( loginContext.getSubject(), new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { Object result = method.invoke( delegate, args ); if ( result != null ) { for ( Class<?> iface : result.getClass().getInterfaces() ) { if ( interfacesToDelegate.contains( iface ) ) { result = forObject( result, loginContext, interfacesToDelegate ); break; } } } return result; } } ); } catch ( PrivilegedActionException e ) { if ( e.getCause() instanceof InvocationTargetException ) { throw ( (InvocationTargetException) e.getCause() ).getCause(); } throw e; } }
Example 6
Source File: Context.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * 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 7
Source File: Synch.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
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: ServiceCredsCombination.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Checks the correct bound * @param a get a creds for this principal, null for default one * @param b expected name, null for still unbound, "NOCRED" for no creds * @param objs princs, keys and keytabs in the subject */ private static void check(final String a, String b, Object... objs) throws Exception { Subject subj = new Subject(); for (Object obj: objs) { if (obj instanceof KerberosPrincipal) { subj.getPrincipals().add((KerberosPrincipal)obj); } else if (obj instanceof KerberosKey || obj instanceof KeyTab) { subj.getPrivateCredentials().add(obj); } } final GSSManager man = GSSManager.getInstance(); try { String result = Subject.doAs( subj, new PrivilegedExceptionAction<String>() { @Override public String run() throws GSSException { GSSCredential cred = man.createCredential( a == null ? null : man.createName(r(a), null), GSSCredential.INDEFINITE_LIFETIME, GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY); GSSName name = cred.getName(); return name == null ? null : name.toString(); } }); if (!Objects.equals(result, r(b))) { throw new Exception("Check failed: getInstance(" + a + ") has name " + result + ", not " + b); } } catch (PrivilegedActionException e) { if (!"NOCRED".equals(b)) { throw new Exception("Check failed: getInstance(" + a + ") is null " + ", but not one with name " + b); } } }
Example 9
Source File: NestedActions.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) { Subject subject = new Subject(); subject.getPrincipals().add(new X500Principal("CN=Duke")); Subject anotherSubject = new Subject(); anotherSubject.getPrincipals().add(new X500Principal("CN=Java")); ReadFromFileAction readFromFile = new ReadFromFileAction(NestedActions.file, anotherSubject); WriteToFileAction writeToFile = new WriteToFileAction(NestedActions.file, readFromFile); Subject.doAs(subject, writeToFile); }
Example 10
Source File: PrestoClient.java From ranger with Apache License 2.0 | 5 votes |
private void init() throws Exception { Subject.doAs(getLoginSubject(), new PrivilegedAction<Void>() { public Void run() { initConnection(); return null; } }); }
Example 11
Source File: AMQPConnectionActorTest.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private String sendLogMessage() { final String message = "test logging"; Subject subject = new Subject(false, Collections.singleton(new ConnectionPrincipal(getConnection())), Collections.emptySet(), Collections.emptySet()); Subject.doAs(subject, new PrivilegedAction<Object>() { @Override public Object run() { getEventLogger().message(new LogSubject() { @Override public String toLogString() { return "[AMQPActorTest]"; } }, new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return "test.hierarchy"; } } ); return null; } }); return message; }
Example 12
Source File: Context.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
/** * 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 13
Source File: RestUserPreferenceHandlerTest.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@Test public void testPutWithVisibilityList_InvalidGroup() throws Exception { final RequestInfo requestInfo = RequestInfo.createPreferencesRequestInfo(Collections.<String>emptyList(), Arrays.asList("X-testtype", "myprefname") ); final Map<String, Object> pref = new HashMap<>(); pref.put(Preference.VALUE_ATTRIBUTE, Collections.emptyMap()); pref.put(Preference.VISIBILITY_LIST_ATTRIBUTE, Collections.singletonList("Invalid Group")); Subject.doAs(_subject, new PrivilegedAction<Void>() { @Override public Void run() { try { _handler.handlePUT(_configuredObject, requestInfo, pref); fail("Expected exception not thrown"); } catch (IllegalArgumentException e) { // pass } return null; } } ); }
Example 14
Source File: AuthenticationCheckFilter.java From qpid-broker-j with Apache License 2.0 | 4 votes |
private void doFilterChainAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, final Subject subject) throws IOException, ServletException { try { Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws IOException, ServletException { chain.doFilter(request, response); return null; } }); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof ServletException) { throw (ServletException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new ConnectionScopedRuntimeException(e.getCause()); } }
Example 15
Source File: NettyConnector.java From activemq-artemis with Apache License 2.0 | 4 votes |
private SSLEngine loadOpenSslEngine(ByteBufAllocator alloc, String keystoreProvider, String keystorePath, String keystorePassword, String truststoreProvider, String truststorePath, String truststorePassword) throws Exception { SslContext context = new SSLSupport() .setKeystoreProvider(keystoreProvider) .setKeystorePath(keystorePath) .setKeystorePassword(keystorePassword) .setTruststoreProvider(truststoreProvider) .setTruststorePath(truststorePath) .setTruststorePassword(truststorePassword) .setSslProvider(sslProvider) .setTrustAll(trustAll) .setTrustManagerFactoryPlugin(trustManagerFactoryPlugin) .createNettyClientContext(); Subject subject = null; if (kerb5Config != null) { LoginContext loginContext = new LoginContext(kerb5Config); loginContext.login(); subject = loginContext.getSubject(); verifyHost = true; } SSLEngine engine = Subject.doAs(subject, new PrivilegedExceptionAction<SSLEngine>() { @Override public SSLEngine run() { if (host != null && port != -1) { return context.newEngine(alloc, host, port); } else { return context.newEngine(alloc); } } }); return engine; }
Example 16
Source File: JAASLoginInterceptor.java From cxf with Apache License 2.0 | 4 votes |
public void handleMessage(final Message message) { if (allowNamedPrincipals) { SecurityContext sc = message.get(SecurityContext.class); if (sc != null && sc.getUserPrincipal() != null && sc.getUserPrincipal().getName() != null) { return; } } CallbackHandler handler = getFirstCallbackHandler(message); if (handler == null && !allowAnonymous) { throw new AuthenticationException("Authentication required but no authentication information was supplied"); } try { LoginContext ctx = new LoginContext(getContextName(), null, handler, loginConfig); ctx.login(); Subject subject = ctx.getSubject(); String name = getUsername(handler); message.put(SecurityContext.class, createSecurityContext(name, subject)); // Run the further chain in the context of this subject. // This allows other code to retrieve the subject using pure JAAS if (useDoAs) { Subject.doAs(subject, new PrivilegedAction<Void>() { @Override public Void run() { InterceptorChain chain = message.getInterceptorChain(); if (chain != null) { message.put("suspend.chain.on.current.interceptor", Boolean.TRUE); chain.doIntercept(message); } return null; } }); } } catch (LoginException ex) { String errorMessage = "Authentication failed: " + ex.getMessage(); LOG.log(Level.FINE, errorMessage, ex); if (reportFault) { AuthenticationException aex = new AuthenticationException(errorMessage); aex.initCause(ex); throw aex; } throw new AuthenticationException("Authentication failed (details can be found in server log)"); } }
Example 17
Source File: KerberosToken.java From athenz with Apache License 2.0 | 4 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) public boolean validate(Subject serviceSubject, StringBuilder errMsg) { PrivilegedExceptionAction<String> privExcAction; try { byte[] kerberosTicket = Base64.decode(unsignedToken.getBytes(StandardCharsets.UTF_8)); if (krbPrivActionClass == null) { privExcAction = new KerberosValidateAction(kerberosTicket); } else { Class privActionClass = Class.forName(krbPrivActionClass); privExcAction = (PrivilegedExceptionAction<String>) privActionClass.getConstructor(byte[].class).newInstance((Object) kerberosTicket); } userName = Subject.doAs(serviceSubject, privExcAction); int index = userName.indexOf('@'); ///CLOVER:OFF if (index != -1) { ///CLOVER:ON if (userName.indexOf(KRB_USER_REALM, index) == -1) { if (userName.indexOf(USER_REALM, index) != -1) { domain = USER_DOMAIN; } else { throw new Exception("KerberosToken:validate: invalid Kerberos Realm: " + userName); } } userName = userName.substring(0, index); } return true; } catch (PrivilegedActionException paexc) { if (errMsg == null) { errMsg = new StringBuilder(512); } errMsg.append("KerberosToken:validate: token=").append(unsignedToken). append(" : privilege exc=").append(paexc); LOG.error(errMsg.toString()); } catch (Exception exc) { if (errMsg == null) { errMsg = new StringBuilder(512); } errMsg.append("KerberosToken:validate: token=").append(unsignedToken). append(" : unknown exc=").append(exc); LOG.error(errMsg.toString()); } return false; }
Example 18
Source File: NestedActions.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void main(String args[]) { Subject subject = new Subject(); subject.getPrincipals().add(new X500Principal("CN=Duke")); try { WriteToFileExceptionAction writeToFile = new WriteToFileExceptionAction(NestedActions.file); Subject.doAs(subject, writeToFile); throw new RuntimeException( "Test failed: no PrivilegedActionException thrown"); } catch (PrivilegedActionException pae) { System.out.println( "PrivilegedActionException thrown as expected: " + pae); // check if AccessControlException caused PrivilegedActionException Throwable exception = pae.getException(); do { if (!(exception instanceof PrivilegedActionException)) { break; } exception = ((PrivilegedActionException) exception). getException(); } while (true); if (!(exception instanceof ReadPropertyException)) { throw new RuntimeException( "Test failed: PrivilegedActionException " + "was not caused by ReadPropertyException"); } exception = exception.getCause(); if (!(exception instanceof AccessControlException)) { throw new RuntimeException( "Test failed: PrivilegedActionException " + "was not caused by ReadPropertyException"); } System.out.println( "Test passed: PrivilegedActionException " + "was caused by AccessControlException"); } }
Example 19
Source File: PreferencesTest.java From qpid-broker-j with Apache License 2.0 | 4 votes |
@Test public void testDeleteByTypeAndId() throws Exception { final String deleteType = "X-type-1"; final Preference deletePreference = PreferenceFactory.fromAttributes(_testObject, PreferenceTestHelper.createPreferenceAttributes( null, null, deleteType, "propName", null, TEST_PRINCIPAL_SERIALIZATION, null, Collections.<String, Object>emptyMap())); final Preference unaffectedPreference1 = PreferenceFactory.fromAttributes(_testObject, PreferenceTestHelper.createPreferenceAttributes( null, null, deleteType, "propName2", null, TEST_PRINCIPAL_SERIALIZATION, null, Collections.<String, Object>emptyMap())); String unaffectedType = "X-type-2"; final Preference unaffectedPreference2 = PreferenceFactory.fromAttributes(_testObject, PreferenceTestHelper.createPreferenceAttributes( null, null, unaffectedType, "propName", null, TEST_PRINCIPAL_SERIALIZATION, null, Collections.<String, Object>emptyMap())); updateOrAppendAs(_testSubject, deletePreference, unaffectedPreference1, unaffectedPreference2); Subject.doAs(_testSubject, new PrivilegedAction<Void>() { @Override public Void run() { awaitPreferenceFuture(_testObject.getUserPreferences().delete(deleteType, null, deletePreference.getId())); return null; } }); assertPreferences(_testSubject, unaffectedPreference1, unaffectedPreference2); }
Example 20
Source File: PreferencesTest.java From qpid-broker-j with Apache License 2.0 | 4 votes |
@Test public void testDeleteViaReplace() { final String preferenceType = "X-testType"; Subject testSubject2 = TestPrincipalUtils.createTestSubject(TEST_USERNAME2); final Preference unaffectedPreference = PreferenceFactory.fromAttributes(_testObject, PreferenceTestHelper.createPreferenceAttributes( null, null, preferenceType, "propName", null, TEST_PRINCIPAL2_SERIALIZATION, null, Collections.<String, Object>emptyMap())); updateOrAppendAs(testSubject2, unaffectedPreference); final Preference p1 = PreferenceFactory.fromAttributes(_testObject, PreferenceTestHelper.createPreferenceAttributes( null, null, preferenceType, "propName", null, TEST_PRINCIPAL_SERIALIZATION, null, Collections.<String, Object>emptyMap())); updateOrAppendAs(_testSubject, p1); Subject.doAs(_testSubject, new PrivilegedAction<Void>() { @Override public Void run() { awaitPreferenceFuture(_testObject.getUserPreferences().replace(Collections.<Preference>emptySet())); return null; } }); assertPreferences(_testSubject); assertPreferences(testSubject2, unaffectedPreference); }