List of usage examples for java.security AccessController getContext
public static AccessControlContext getContext()
From source file:org.elasticsearch.xpack.security.authc.kerberos.SpnegoHttpClientConfigCallbackHandler.java
private void setupSpnegoAuthSchemeSupport(HttpAsyncClientBuilder httpClientBuilder) { final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build(); final GSSManager gssManager = GSSManager.getInstance(); try {/*from w w w. j a va 2 s . c o m*/ final GSSName gssUserPrincipalName = gssManager.createName(userPrincipalName, GSSName.NT_USER_NAME); login(); final AccessControlContext acc = AccessController.getContext(); final GSSCredential credential = doAsPrivilegedWrapper(loginContext.getSubject(), (PrivilegedExceptionAction<GSSCredential>) () -> gssManager.createCredential( gssUserPrincipalName, GSSCredential.DEFAULT_LIFETIME, SPNEGO_OID, GSSCredential.INITIATE_ONLY), acc); final KerberosCredentialsProvider credentialsProvider = new KerberosCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthSchemes.SPNEGO), new KerberosCredentials(credential)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } catch (GSSException e) { throw new RuntimeException(e); } catch (PrivilegedActionException e) { throw new RuntimeException(e.getCause()); } httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); }
From source file:com.dragome.callbackevictor.serverside.DragomeContinuationClassLoader.java
/** * Creates a classloader by using the classpath given. * * @param urls/* w w w .ja va2 s . c o m*/ * The URLs from which to load classes and resources * @param parent * The parent classloader to which unsatisfied loading * attempts are delegated. May be <code>null</code>, * in which case the {@link ClassLoader#getSystemClassLoader() system classloader} * is used as the parent. * @param transformer * This transformer is used to perform the byte-code enhancement. * May not be null. */ public DragomeContinuationClassLoader(URL[] urls, ClassLoader parent, ResourceTransformer transformer) { super(urls, fixNullParent(parent)); if (transformer == null) throw new IllegalArgumentException(); this.transformer = transformer; acc = AccessController.getContext(); }
From source file:org.elasticsearch.xpack.security.authc.kerberos.KerberosAuthenticationIT.java
private void executeRequestAndVerifyResponse(final String userPrincipalName, final SpnegoHttpClientConfigCallbackHandler callbackHandler) throws PrivilegedActionException, IOException { final Request request = new Request("GET", "/_xpack/security/_authenticate"); try (RestClient restClient = buildRestClientForKerberos(callbackHandler)) { final AccessControlContext accessControlContext = AccessController.getContext(); final LoginContext lc = callbackHandler.login(); Response response = SpnegoHttpClientConfigCallbackHandler.doAsPrivilegedWrapper(lc.getSubject(), (PrivilegedExceptionAction<Response>) () -> { return restClient.performRequest(request); }, accessControlContext); assertOK(response);// w w w.j av a 2s . com final Map<String, Object> map = parseResponseAsMap(response.getEntity()); assertThat(map.get("username"), equalTo(userPrincipalName)); assertThat(map.get("roles"), instanceOf(List.class)); assertThat(((List<?>) map.get("roles")), contains("kerb_test")); } }
From source file:com.cloudera.alfredo.client.KerberosAuthenticator.java
/** * Implements the SPNEGO authentication sequence interaction using the current default principal * in the Kerberos cache (normally set via kinit). * * @param token the authencation token being used for the user. * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication error occurred. *///w w w . j av a 2s . c om private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException { try { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null) { subject = new Subject(); LoginContext login = new LoginContext("", subject); login.login(); } Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); String servicePrincipal = "HTTP/" + KerberosAuthenticator.this.url.getHost(); GSSName serviceName = gssManager.createName(servicePrincipal, GSSUtil.NT_GSS_KRB5_PRINCIPAL); gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_OID, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; boolean established = false; // Loop while the context is still not established while (!established) { outToken = gssContext.initSecContext(inToken, 0, inToken.length); if (outToken != null) { sendToken(outToken); } if (!gssContext.isEstablished()) { inToken = readToken(); } else { established = true; } } } finally { if (gssContext != null) { gssContext.dispose(); } } return null; } }); } catch (PrivilegedActionException ex) { throw new AuthenticationException(ex.getException()); } catch (LoginException ex) { throw new AuthenticationException(ex); } AuthenticatedURL.extractToken(conn, token); }
From source file:graphql.servlet.GraphQLServlet.java
private void query(String query, String operationName, Map<String, Object> variables, GraphQLSchema schema, HttpServletRequest req, HttpServletResponse resp, GraphQLContext context) throws IOException { if (Subject.getSubject(AccessController.getContext()) == null && context.getSubject().isPresent()) { Subject.doAs(context.getSubject().get(), new PrivilegedAction<Void>() { @Override/* w w w. j av a 2 s . c o m*/ @SneakyThrows public Void run() { query(query, operationName, variables, schema, req, resp, context); return null; } }); } else { Map<String, Object> vars = transformVariables(schema, query, variables); operationListeners.forEach(l -> l.beforeGraphQLOperation(context, operationName, query, vars)); ExecutionResult result = new GraphQL(schema, getExecutionStrategy()).execute(query, operationName, context, vars); resp.setContentType("application/json;charset=utf-8"); if (result.getErrors().isEmpty()) { Map<String, Object> dict = new HashMap<>(); dict.put("data", result.getData()); resp.getWriter().write(new ObjectMapper().writeValueAsString(dict)); operationListeners.forEach( l -> l.onSuccessfulGraphQLOperation(context, operationName, query, vars, result.getData())); } else { resp.setStatus(500); List<GraphQLError> errors = getGraphQLErrors(result); Map<String, Object> dict = new HashMap<>(); dict.put("errors", errors); resp.getWriter().write(new ObjectMapper().writeValueAsString(dict)); operationListeners.forEach( l -> l.onFailedGraphQLOperation(context, operationName, query, vars, result.getErrors())); } } }
From source file:com.lucidworks.security.authentication.client.KerberosAuthenticator.java
/** * Implements the SPNEGO authentication sequence interaction using the current default principal * in the Kerberos cache (normally set via kinit). * * @param token the authentication token being used for the user. * * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication error occurred. *//*from w w w . j a v a2s. co m*/ private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException { try { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null) { LOG.debug("No subject in context, logging in"); subject = new Subject(); LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration()); login.login(); } if (LOG.isDebugEnabled()) { LOG.debug("Using subject: " + subject); } Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", KerberosAuthenticator.this.url.getHost()); Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL"); GSSName serviceName = gssManager.createName(servicePrincipal, oid); oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID"); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; boolean established = false; // Loop while the context is still not established while (!established) { outToken = gssContext.initSecContext(inToken, 0, inToken.length); if (outToken != null) { sendToken(outToken); } if (!gssContext.isEstablished()) { inToken = readToken(); } else { established = true; } } } finally { if (gssContext != null) { gssContext.dispose(); gssContext = null; } } return null; } }); } catch (PrivilegedActionException ex) { throw new AuthenticationException(ex.getException()); } catch (LoginException ex) { throw new AuthenticationException(ex); } AuthenticatedURL.extractToken(conn, token); }
From source file:com.srotya.collectd.storm.StormNimbusMetrics.java
@Override public int config(OConfigItem config) { nimbusAddresses = new ArrayList<>(); String jaasPath = "jaas.conf"; List<OConfigItem> children = config.getChildren(); for (OConfigItem child : children) { switch (child.getKey().toLowerCase()) { case "address": for (OConfigValue nimbus : child.getValues()) { try { new URI(nimbus.toString()); } catch (Exception e) { Collectd.logError("Bad URI " + nimbus + " for Nimbus, error:" + e.getMessage()); return -1; }/*from w w w . j a va 2 s .co m*/ nimbusAddresses.add(nimbus.getString()); } break; case "kerberos": kerberos = child.getValues().get(0).getBoolean(); break; case "jaas": jaasPath = child.getValues().get(0).getString(); break; } } Collectd.logInfo("Storm Nimbus Plugin: using following Nimbuses:" + nimbusAddresses); Collectd.logInfo("Storm Nimbus Plugin: using kerberos:" + kerberos); builder = HttpClientBuilder.create(); context = HttpClientContext.create(); if (kerberos) { System.setProperty("java.security.auth.login.config", jaasPath); System.setProperty("java.security.krb5.conf", "/etc/krb5.conf"); System.setProperty("javax.security.auth.useSubjectCredsOnly", "true"); login(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // This may seem odd, but specifying 'null' as principal tells java // to // use the logged in user's credentials Credentials useJaasCreds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds); context.setCredentialsProvider(credentialsProvider); } else { subject = Subject.getSubject(AccessController.getContext()); } return 0; }
From source file:com.ikon.module.jcr.stuff.JCRUtils.java
/** * Get JCR Session//from ww w .ja v a 2s . c o m */ public static Session getSession() throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException { Subject subject = null; Object obj = null; // Resolve subject // Subject userSubject=(Subject)PolicyContext.getContext("javax.security.auth.Subject.container"); if (EnvironmentDetector.isServerJBoss()) { try { InitialContext ctx = new InitialContext(); subject = (Subject) ctx.lookup("java:/comp/env/security/subject"); ctx.close(); } catch (NamingException e) { throw new javax.jcr.LoginException(e.getMessage()); } } else if (EnvironmentDetector.isServerTomcat()) { subject = Subject.getSubject(AccessController.getContext()); } // Obtain JCR session if (subject != null) { obj = Subject.doAs(subject, new PrivilegedAction<Object>() { public Object run() { Session s = null; try { s = JcrRepositoryModule.getRepository().login(); } catch (javax.jcr.LoginException e) { return e; } catch (javax.jcr.RepositoryException e) { return e; } return s; } }); } // Validate JCR session if (obj instanceof javax.jcr.LoginException) { throw (javax.jcr.LoginException) obj; } else if (obj instanceof javax.jcr.RepositoryException) { throw (javax.jcr.RepositoryException) obj; } else if (obj instanceof javax.jcr.Session) { Session session = (javax.jcr.Session) obj; log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions, session, StackTraceUtils.whoCalledMe() }); JcrAuthModule.loadUserData(session); return session; } else { return null; } }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Return the current user, including any doAs in the current stack. * * @return the current user//ww w . j a va 2s .c om * * @throws IOException if login fails */ public synchronized static UserGroupInformation getCurrentUser() throws IOException { AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null || subject.getPrincipals(User.class).isEmpty()) { return getLoginUser(); } else { return new UserGroupInformation(subject); } }
From source file:ca.nrc.cadc.uws.server.JobDAO.java
/** * Iterate over the jobs owned by the user in the subject contained in the * access control context.// w w w .java 2 s . c om * * @param phases Show only these phases * @param after Only show jobs after this time * @param last Show the last <i>last</i> jobs, ordererd by startTime ascending * @return job iterator * @throws JobPersistenceException * @throws TransientException */ public Iterator<JobRef> iterator(String appname, List<ExecutionPhase> phases, Date after, Integer last) throws TransientException, JobPersistenceException { AccessControlContext acContext = AccessController.getContext(); Subject subject = Subject.getSubject(acContext); return iterator(subject, appname, phases, after, last); }