org.eclipse.jetty.util.B64Code Java Examples

The following examples show how to use org.eclipse.jetty.util.B64Code. 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: Resource.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
public String getWeakETag()
{
    try
    {
        StringBuilder b = new StringBuilder(32);
        b.append("W/\"");
        
        String name=getName();
        int length=name.length();
        long lhash=0;
        for (int i=0; i<length;i++)
            lhash=31*lhash+name.charAt(i);
        
        B64Code.encode(lastModified()^lhash,b);
        B64Code.encode(length()^lhash,b);
        b.append('"');
        return b.toString();
    } 
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: SecurityCheckFactory.java    From commafeed with Apache License 2.0 6 votes vote down vote up
private Optional<User> basicAuthenticationLogin() {
	String header = request.getHeader(HttpHeaders.AUTHORIZATION);
	if (header != null) {
		int space = header.indexOf(' ');
		if (space > 0) {
			String method = header.substring(0, space);
			if (PREFIX.equalsIgnoreCase(method)) {
				String decoded = B64Code.decode(header.substring(space + 1), StringUtil.__ISO_8859_1);
				int i = decoded.indexOf(':');
				if (i > 0) {
					String username = decoded.substring(0, i);
					String password = decoded.substring(i + 1);
					return userService.login(username, password);
				}
			}
		}
	}
	return Optional.empty();
}
 
Example #3
Source File: MultipartContentProvider.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void addPart(String name, byte[] data, String mimetype) {
	try {
		m_writer.write("\n--" + m_boundary + "\n");
		m_writer.write("Content-Disposition: form-data;");
		m_writer.write(" name=\"" + name + "\"\n");
		m_writer.write("Content-Type: " + mimetype +"\n");
		m_writer.write("Content-Transfer-Encoding: base64\n\n");
		
		m_writer.write(B64Code.encode(data));
		m_writer.write("\n");
		
		m_writer.flush();
	} catch (IOException e) {
		throw new RuntimeException("Unexpected", e);
	}
}
 
Example #4
Source File: Resource.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
public String getWeakETag()
{
    try
    {
        StringBuilder b = new StringBuilder(32);
        b.append("W/\"");
        
        String name=getName();
        int length=name.length();
        long lhash=0;
        for (int i=0; i<length;i++)
            lhash=31*lhash+name.charAt(i);
        
        B64Code.encode(lastModified()^lhash,b);
        B64Code.encode(length()^lhash,b);
        b.append('"');
        return b.toString();
    } 
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: ProxyServletServiceTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaybeAppendAuthHeaderWithFullCredentials() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://testuser:[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:testpassword", StringUtil.__ISO_8859_1));
}
 
Example #6
Source File: ProxyServletServiceTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaybeAppendAuthHeaderWithoutPassword() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:", StringUtil.__ISO_8859_1));
}
 
Example #7
Source File: WebSocketConnectionRFC6455.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public static String hashKey(String key)
{
    try
    {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(key.getBytes("UTF-8"));
        md.update(MAGIC);
        return new String(B64Code.encode(md.digest()));
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: WebSocketConnectionRFC6455.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public static String hashKey(String key)
{
    try
    {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(key.getBytes("UTF-8"));
        md.update(MAGIC);
        return new String(B64Code.encode(md.digest()));
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: ProxyServletService.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If the URI contains user info in the form <code>user[:pass]@</code>, attempt to preempt the server
 * returning a 401 by providing Basic Authentication support in the initial request to the server.
 *
 * @param uri the URI which may contain user info
 * @param request the outgoing request to which an authorization header may be added
 */
void maybeAppendAuthHeader(URI uri, Request request) {
    if (uri != null && uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");

        if (userInfo.length >= 1) {
            String user = userInfo[0];
            String password = userInfo.length >= 2 ? userInfo[1] : null;
            String authString = password != null ? user + ":" + password : user + ":";

            String basicAuthentication = "Basic " + B64Code.encode(authString, StringUtil.__ISO_8859_1);
            request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
        }
    }
}
 
Example #10
Source File: ProxyServletService.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If the URI contains user info in the form <code>user[:pass]@</code>, attempt to preempt the server
 * returning a 401 by providing Basic Authentication support in the initial request to the server.
 *
 * @param uri the URI which may contain user info
 * @param request the outgoing request to which an authorization header may be added
 */
void maybeAppendAuthHeader(URI uri, Request request) {
    if (uri != null && uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");

        if (userInfo.length >= 1) {
            String user = userInfo[0];
            String password = userInfo.length >= 2 ? userInfo[1] : null;
            String authString = password != null ? user + ":" + password : user + ":";

            String basicAuthentication = "Basic " + B64Code.encode(authString, StringUtil.__ISO_8859_1);
            request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
        }
    }
}
 
Example #11
Source File: ProxyServletServiceTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaybeAppendAuthHeaderWithFullCredentials() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://testuser:[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:testpassword", StringUtil.__ISO_8859_1));
}
 
Example #12
Source File: ProxyServletServiceTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMaybeAppendAuthHeaderWithoutPassword() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:", StringUtil.__ISO_8859_1));
}
 
Example #13
Source File: WebSocketClientFactory.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
public HandshakeConnection(AsyncEndPoint endpoint, WebSocketClient.WebSocketFuture future)
{
    super(endpoint, System.currentTimeMillis());
    _endp = endpoint;
    _future = future;

    byte[] bytes = new byte[16];
    new Random().nextBytes(bytes);
    _key = new String(B64Code.encode(bytes));

    Buffers buffers = new SimpleBuffers(_buffers.getBuffer(), null);
    _parser = new HttpParser(buffers, _endp, new HttpParser.EventHandler()
    {
        @Override
        public void startResponse(Buffer version, int status, Buffer reason) throws IOException
        {
            if (status != 101)
            {
                _error = "Bad response status " + status + " " + reason;
                _endp.close();
            }
        }

        @Override
        public void parsedHeader(Buffer name, Buffer value) throws IOException
        {
            if (__ACCEPT.equals(name))
                _accept = value.toString();
        }

        @Override // TODO simone says shouldn't be needed
        public void startRequest(Buffer method, Buffer url, Buffer version) throws IOException
        {
            if (_error == null)
                _error = "Bad response: " + method + " " + url + " " + version;
            _endp.close();
        }

        @Override // TODO simone says shouldn't be needed
        public void content(Buffer ref) throws IOException
        {
            if (_error == null)
                _error = "Bad response. " + ref.length() + "B of content?";
            _endp.close();
        }
    });
}
 
Example #14
Source File: DrillSpnegoLoginService.java    From Bats with Apache License 2.0 4 votes vote down vote up
private UserIdentity spnegoLogin(Object credentials) {

    String encodedAuthToken = (String) credentials;
    byte[] authToken = B64Code.decode(encodedAuthToken);
    GSSManager manager = GSSManager.getInstance();

    try {
      // Providing both OID's is required here. If we provide only one,
      // we're requiring that clients provide us the SPNEGO OID to authenticate via Kerberos.
      Oid[] knownOids = new Oid[2];
      knownOids[0] = new Oid("1.3.6.1.5.5.2"); // spnego
      knownOids[1] = new Oid("1.2.840.113554.1.2.2"); // kerberos

      GSSName gssName = manager.createName(spnegoConfig.getSpnegoPrincipal(), null);
      GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME,
          knownOids, GSSCredential.ACCEPT_ONLY);
      GSSContext gContext = manager.createContext(serverCreds);

      if (gContext == null) {
        logger.debug("SPNEGOUserRealm: failed to establish GSSContext");
      } else {
        while (!gContext.isEstablished()) {
          authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
        }

        if (gContext.isEstablished()) {
          final String clientName = gContext.getSrcName().toString();
          final String realm = clientName.substring(clientName.indexOf(64) + 1);

          // Get the client user short name
          final String userShortName = new HadoopKerberosName(clientName).getShortName();

          logger.debug("Client Name: {}, realm: {} and shortName: {}", clientName, realm, userShortName);
          final SystemOptionManager sysOptions = drillContext.getOptionManager();
          final boolean isAdmin = ImpersonationUtil.hasAdminPrivileges(userShortName,
              ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(sysOptions),
              ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(sysOptions));

          final Principal user = new DrillUserPrincipal(userShortName, isAdmin);
          final Subject subject = new Subject();
          subject.getPrincipals().add(user);

          if (isAdmin) {
            return this._identityService.newUserIdentity(subject, user, DrillUserPrincipal.ADMIN_USER_ROLES);
          } else {
            return this._identityService.newUserIdentity(subject, user, DrillUserPrincipal.NON_ADMIN_USER_ROLES);
          }
        }
      }
    } catch (GSSException gsse) {
      logger.warn("Caught GSSException trying to authenticate the client", gsse);
    } catch (IOException ex) {
      logger.warn("Caught IOException trying to get shortName of client user", ex);
    }
    return null;
  }
 
Example #15
Source File: WebSocketClientFactory.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
public HandshakeConnection(AsyncEndPoint endpoint, WebSocketClient.WebSocketFuture future)
{
    super(endpoint, System.currentTimeMillis());
    _endp = endpoint;
    _future = future;

    byte[] bytes = new byte[16];
    new Random().nextBytes(bytes);
    _key = new String(B64Code.encode(bytes));

    Buffers buffers = new SimpleBuffers(_buffers.getBuffer(), null);
    _parser = new HttpParser(buffers, _endp, new HttpParser.EventHandler()
    {
        @Override
        public void startResponse(Buffer version, int status, Buffer reason) throws IOException
        {
            if (status != 101)
            {
                _error = "Bad response status " + status + " " + reason;
                _endp.close();
            }
        }

        @Override
        public void parsedHeader(Buffer name, Buffer value) throws IOException
        {
            if (__ACCEPT.equals(name))
                _accept = value.toString();
        }

        @Override // TODO simone says shouldn't be needed
        public void startRequest(Buffer method, Buffer url, Buffer version) throws IOException
        {
            if (_error == null)
                _error = "Bad response: " + method + " " + url + " " + version;
            _endp.close();
        }

        @Override // TODO simone says shouldn't be needed
        public void content(Buffer ref) throws IOException
        {
            if (_error == null)
                _error = "Bad response. " + ref.length() + "B of content?";
            _endp.close();
        }
    });
}
 
Example #16
Source File: SolrBasicAuthentication.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public SolrBasicAuthentication(String user, String password) {
  this.value = "Basic " + B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
}
 
Example #17
Source File: PropertyBasedSpnegoLoginService.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
@Override public UserIdentity login(String username, Object credentials,
    ServletRequest request) {
  String encodedAuthToken = (String) credentials;
  byte[] authToken = B64Code.decode(encodedAuthToken);

  GSSManager manager = GSSManager.getInstance();
  try {
    // http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/jgss-features.html
    Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
    Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssName = manager.createName(serverPrincipal, null);
    // CALCITE-1922 Providing both OIDs is the bug in Jetty we're working around. By specifying
    // only one, we're requiring that clients *must* provide us the SPNEGO OID to authenticate
    // via Kerberos which is wrong. Best as I can tell, the SPNEGO OID is meant as another
    // layer of indirection (essentially is equivalent to setting the Kerberos OID).
    GSSCredential serverCreds = manager.createCredential(gssName,
        GSSCredential.INDEFINITE_LIFETIME, new Oid[] {krb5Oid, spnegoOid},
        GSSCredential.ACCEPT_ONLY);
    GSSContext gContext = manager.createContext(serverCreds);

    if (gContext == null) {
      LOG.debug("SpnegoUserRealm: failed to establish GSSContext");
    } else {
      while (!gContext.isEstablished()) {
        authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
      }
      if (gContext.isEstablished()) {
        String clientName = gContext.getSrcName().toString();
        String role = clientName.substring(clientName.indexOf('@') + 1);

        LOG.debug("SpnegoUserRealm: established a security context");
        LOG.debug("Client Principal is: {}", gContext.getSrcName());
        LOG.debug("Server Principal is: {}", gContext.getTargName());
        LOG.debug("Client Default Role: {}", role);

        SpnegoUserPrincipal user = new SpnegoUserPrincipal(clientName, authToken);

        Subject subject = new Subject();
        subject.getPrincipals().add(user);

        return _identityService.newUserIdentity(subject, user, new String[]{role});
      }
    }
  } catch (GSSException gsse) {
    LOG.warn("Caught GSSException trying to authenticate the client", gsse);
  }

  return null;
}