List of usage examples for javax.security.auth Subject doAs
public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action) throws java.security.PrivilegedActionException
From source file:org.apache.ranger.biz.KmsKeyMgr.java
public VXKmsKey getKeyFromUri(String provider, String name, boolean isKerberos, String repoName) throws Exception { Client c = getClient();/*from w w w . ja va 2s . com*/ String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String uri = provider + (provider.endsWith("/") ? keyRest : ("/" + keyRest)); if (!isKerberos) { uri = uri.concat("?user.name=" + currentUserLoginId); } else { uri = uri.concat("?doAs=" + currentUserLoginId); } final WebResource r = c.resource(uri); String response = null; if (!isKerberos) { response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .get(String.class); } else { Subject sub = getSubjectForKerberos(repoName); response = Subject.doAs(sub, new PrivilegedAction<String>() { @Override public String run() { return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .get(String.class); } }); } Gson gson = new GsonBuilder().create(); logger.debug("RESPONSE: [" + response + "]"); VXKmsKey key = gson.fromJson(response, VXKmsKey.class); return key; }
From source file:org.apache.hadoop.hive.shims.Hadoop20Shims.java
@Override public <T> T doAs(UserGroupInformation ugi, PrivilegedExceptionAction<T> pvea) throws IOException, InterruptedException { try {//from w ww .ja v a 2 s . c o m return Subject.doAs(SecurityUtil.getSubject(ugi), pvea); } catch (PrivilegedActionException e) { throw new IOException(e); } }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java
public Object doAs(PrivilegedAction<?> action) throws UserDatabaseException { Object result = null;//from w ww.j av a 2 s .com if (isServiceAuthenticationGssApi()) { try { LoginContext context = getServiceAccountLoginContext(); result = Subject.doAs(context.getSubject(), action); logoutContext(context); } catch (Exception e) { logger.error("Failure to create Login Context", e); throw new UserDatabaseException("", e); } } else { result = action.run(); } if (result instanceof Throwable) { Throwable e = (Throwable) result; logger.error("Failure to doAs", e); throw new UserDatabaseException("", e); } return result; }
From source file:org.jboss.as.test.integration.security.common.Utils.java
/** * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the * given user is authenticated against Kerberos and a new request is executed under the new subject. * * @param uri URI to which the request should be made * @param user Username//from w ww .j a v a2s. c o m * @param pass Password * @param expectedStatusCode expected status code returned from the requested server * @return HTTP response body * @throws IOException * @throws URISyntaxException * @throws PrivilegedActionException * @throws LoginException */ public static String makeCallWithKerberosAuthn(final URI uri, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException { LOGGER.trace("Requesting URI: " + uri); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials()); final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration()); try (final CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider) .build()) { final HttpGet httpGet = new HttpGet(uri); final HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) { assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } final HttpEntity entity = response.getEntity(); final Header[] authnHeaders = response.getHeaders("WWW-Authenticate"); assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0); final Set<String> authnHeaderValues = new HashSet<String>(); for (final Header header : authnHeaders) { authnHeaderValues.add(header.getValue()); } assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate")); if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user); } if (entity != null) EntityUtils.consume(entity); // Use our custom configuration to avoid reliance on external config Configuration.setConfiguration(krb5Configuration); // 1. Authenticate to Kerberos. final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass); // 2. Perform the work as authenticated Subject. final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() { public String run() throws Exception { final HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } }); lc.logout(); return responseBody; } finally { krb5Configuration.resetConfiguration(); } }
From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java
/** * It enforces the the Kerberos SPNEGO authentication sequence returning an * {@link AuthenticationToken} only after the Kerberos SPNEGO sequence has * completed successfully.//from w w w. jav a 2 s .co m * * @param request the HTTP client request. * @param response the HTTP client response. * @return an authentication token if the Kerberos SPNEGO sequence is complete * and valid, <code>null</code> if it is in progress (in this case the handler * handles the response to the client). * @throws IOException thrown if an IO error occurred. * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed. */ public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) { response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (authorization == null) { LOG.trace("SPNEGO starting for url: {}", request.getRequestURL()); } else { LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' : {}", authorization); } } else { authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); try { final String serverPrincipal = KerberosUtil.getTokenServerName(clientToken); if (!serverPrincipal.startsWith("HTTP/")) { throw new IllegalArgumentException( "Invalid server principal " + serverPrincipal + "decoded from client request"); } token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { return runWithPrincipal(serverPrincipal, clientToken, base64, response); } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } catch (Exception ex) { throw new AuthenticationException(ex); } } return token; }
From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java
public static <T> T doAsKerberosUser(String principal, String keytab, final Callable<T> callable) throws Exception { LoginContext loginContext = null; try {//from ww w.jav a 2s . c o m Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal, keytab)); loginContext.login(); subject = loginContext.getSubject(); return Subject.doAs(subject, new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { return callable.call(); } }); } catch (PrivilegedActionException ex) { throw ex.getException(); } finally { if (loginContext != null) { loginContext.logout(); } } }
From source file:org.jboss.as.test.integration.security.common.Utils.java
/** * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails, * FORM is used.//from ww w . j av a2s . c o m * * @param contextUrl * @param page * @param user * @param pass * @param expectedStatusCode * @return * @throws IOException * @throws URISyntaxException * @throws PrivilegedActionException * @throws LoginException */ public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException { final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/"); final String url = strippedContextUrl + page; LOGGER.trace("Requesting URL: " + url); String unauthorizedPageBody = null; final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration()); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials()); final CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider) .setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager()) .build(); try { final HttpGet httpGet = new HttpGet(url); final HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) { assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } final Header[] authnHeaders = response.getHeaders("WWW-Authenticate"); assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0); final Set<String> authnHeaderValues = new HashSet<String>(); for (final Header header : authnHeaders) { authnHeaderValues.add(header.getValue()); } assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate")); LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user); unauthorizedPageBody = EntityUtils.toString(response.getEntity()); // Use our custom configuration to avoid reliance on external config Configuration.setConfiguration(krb5Configuration); // 1. Authenticate to Kerberos. final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass); // 2. Perform the work as authenticated Subject. final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() { public String run() throws Exception { final HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } }); lc.logout(); return responseBody; } catch (LoginException e) { assertNotNull(unauthorizedPageBody); assertTrue(unauthorizedPageBody.contains("j_security_check")); HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("j_username", user)); nameValuePairs.add(new BasicNameValuePair("j_password", pass)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); final HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpClient.close(); // reset login configuration krb5Configuration.resetConfiguration(); } }
From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java
/** * Authenticate a received service request. * <p/>// w ww . j a va2 s . com * This method is called to transform the mechanism-specific request message * acquired by calling getRequestMessage (on messageInfo) into the validated * application message to be returned to the message processing runtime. If * the received message is a (mechanism-specific) meta-message, the method * implementation must attempt to transform the meta-message into a * corresponding mechanism-specific response message, or to the validated * application request message. The runtime will bind a validated * application message into the the corresponding service invocation. * <p> * This method conveys the outcome of its message processing either by * returning an AuthStatus value or by throwing an AuthException. * <p/> * From a performance point of view this method will be called twice for * each resource with a security constraint on it. Resources with no * security constraint do not result in a call to this method. * * @param messageInfo * A contextual object that encapsulates the client request and * server response objects, and that may be used to save state * across a sequence of calls made to the methods of this * interface for the purpose of completing a secure message * exchange. * @param clientSubject * A Subject that represents the source of the service request. * It is used by the method implementation to store Principals * and credentials validated in the request. * @param serviceSubject * A Subject that represents the recipient of the service * request, or null. It may be used by the method implementation * as the source of Principals or credentials to be used to * validate the request. If the Subject is not null, the method * implementation may add additional Principals or credentials * (pertaining to the recipient of the service request) to the * Subject. * @return An AuthStatus object representing the completion status of the * processing performed by the method. The AuthStatus values that * may be returned by this method are defined as follows: * <p/> * <ul> * <li>AuthStatus.SUCCESS when the application request message was * successfully validated. The validated request message is * available by calling getRequestMessage on messageInfo. * <p/> * <li>AuthStatus.SEND_SUCCESS to indicate that * validation/processing of the request message successfully * produced the secured application response message (in * messageInfo). The secured response message is available by * calling getResponseMessage on messageInfo. * <p/> * <li>AuthStatus.SEND_CONTINUE to indicate that message validation * is incomplete, and that a preliminary response was returned as * the response message in messageInfo. * <p/> * When this status value is returned to challenge an application * request message, the challenged request must be saved by the * authentication module such that it can be recovered when the * module's validateRequest message is called to process the request * returned for the challenge. * <p/> * <li>AuthStatus.SEND_FAILURE to indicate that message validation * failed and that an appropriate failure response message is * available by calling getResponseMessage on messageInfo. * </ul> * @throws AuthException When the message processing failed without * establishing a failure response message (in messageInfo). */ @SuppressWarnings("unchecked") public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { // Extra check (disabled withour -ea) if mandatory value is consistent // with initialize phase assert messageInfo.getMap().containsKey(IS_MANDATORY_INFO_KEY) == this.mandatory; // Get the servlet context final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage(); // Invalidate any existing session to prevent session fixture attempt HttpSession session = request.getSession(false); if (session != null) { final SessionState state = (SessionState) session.getAttribute(MAGIC_SESSION_STATE_KEY); if (state == null) { // Session was not created by us, we will invalidate an existing // session that was not created by us session.invalidate(); LOG.warning( "An existing session was invalidated. This might be a session fixture attempt, so failing the authentication."); return AuthStatus.SEND_FAILURE; } else if (SessionState.ESTABLISHED.equals(state)) { // The context was already fully established once within this // session. return AuthStatus.SUCCESS; } } debugRequest(request); // should specify encoder final String authorization = request.getHeader(AUTHORIZATION_HEADER); if (authorization != null && authorization.startsWith(NEGOTIATE)) { final String negotiateString = authorization.substring(NEGOTIATE.length() + 1); final byte[] requestToken = Base64.decodeBase64(negotiateString); if (serviceSubject == null) { // If no service subject was provided by the container then set // a service subject // from the global context. serviceSubject = this.serviceSubject; } try { // Create a validation action byte[] gssToken = null; final KerberosValidateAction kva = new KerberosValidateAction(this.servicePrincipal, requestToken, serviceSubject); try { // Validate using the service (server) Subject gssToken = Subject.doAs(this.serviceSubject, kva); } catch (final PrivilegedActionException e) { final GSSException gex = new GSSException(GSSException.DEFECTIVE_TOKEN); gex.initCause(e); gex.setMinor(GSSException.UNAVAILABLE, "Unable to perform Kerberos validation"); throw gex; } if (kva.getContext() != null) { final String responseToken = Base64.encodeBase64String(gssToken); response.setHeader(AUTHENTICATION_HEADER, "Negotiate " + responseToken); debugToken("GSS Response token set to {0}", gssToken); } if (!kva.isEstablished()) { debug("GSS Dialog must continue to succeed"); session.setAttribute(MAGIC_SESSION_STATE_KEY, SessionState.IN_PROGRESS); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return AuthStatus.SEND_CONTINUE; } else { final Oid mechId = kva.getMech(); final GSSName name = kva.getSrcName(); if (!authorizeCaller(request, requestToken, name, clientSubject)) { return sendFailureMessage(response, "Failed to authorize the caller/client"); } // As no valid session should exist anymore, simply create a // new one session = request.getSession(true); final Principal clientPrincipal = new KerberosPrincipal( name.canonicalize(GSS_KRB5_MECH_OID).toString()); updateSessionAndHeader(request, session, clientPrincipal); session.setAttribute(MAGIC_SESSION_STATE_KEY, SessionState.ESTABLISHED); /* * Store the mechId in the MessageInfo to indicate which * authentication mechanism was used successfully (JASPIC * Requirement) */ messageInfo.getMap().put(AUTH_TYPE_INFO_KEY, mechId != null ? mechId.toString() : "Undefined GSS Mechanism"); debug("GSS Dialog is complete"); } } catch (final GSSException gsse) { debug("GSS Dialog has failed : {0}", gsse); if (requestToken != null) { debug("Bad token detected {0}", gsse); debugToken("Bad token was {0}", requestToken); if (isNTLMToken(requestToken)) { // There is a high probability it was a NTLM SPNEGO // token return sendFailureMessage(response, "No support for NTLM"); } } // for other errors throw an AuthException final AuthException ae = new AuthException(); ae.initCause(gsse); throw ae; } } else if (this.mandatory) { response.setHeader(AUTHENTICATION_HEADER, NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); debug("Negotiate was added to the HTTP header : {0}", NEGOTIATE); return AuthStatus.SEND_CONTINUE; } else if (authorization != null) { LOG.warning("An authorization header was ignored."); } return AuthStatus.SUCCESS; }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
private byte[] prepareKerberosLogin() { try {/*from www . j av a2 s. co m*/ Path outputFile = Controller.getTempFilesLocation().resolve("login.conf"); if (Files.notExists(outputFile)) { InputStream configFile = Thread.currentThread().getContextClassLoader() .getResourceAsStream("kerberos/login.conf"); PathUtils.copyFromStreamToFile(configFile, outputFile); } System.setProperty("java.security.auth.login.config", outputFile.toAbsolutePath().toString()); System.setProperty("java.security.krb5.realm", ConfigurationEntry.KERBEROS_SSO_REALM.getValue(getController())); String kdc = ConfigurationEntry.KERBEROS_SSO_KDC.getValue(getController()); System.setProperty("java.security.krb5.kdc", kdc); LoginContext lc = new LoginContext("SignedOnUserLoginContext", new TextCallbackHandler()); lc.login(); Subject clientSubject = lc.getSubject(); username = clientSubject.getPrincipals().iterator().next().getName(); return Subject.doAs(clientSubject, new ServiceTicketGenerator()); } catch (Exception e) { logWarning("Unable to login: " + e); return null; } finally { loggingIn.set(false); } }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Run the given action as the user.// ww w. jav a 2 s . co m * @param <T> the return type of the run method * @param action the method to execute * @return the value from the run method */ public <T> T doAs(PrivilegedAction<T> action) { logPriviledgedAction(subject, action); return Subject.doAs(subject, action); }