Java Code Examples for org.glassfish.jersey.client.authentication.HttpAuthenticationFeature#basic()

The following examples show how to use org.glassfish.jersey.client.authentication.HttpAuthenticationFeature#basic() . 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: LDAPAuthenticationFallbackIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdapAuthentication(){
  String userInfoURI = sdcURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();

  if (!result) {
    Assert.assertEquals(401, response.getStatus());
  } else{
    Assert.assertEquals(200, response.getStatus());
    Map userInfo = response.readEntity(Map.class);
    Assert.assertTrue(userInfo.containsKey("user"));
    Assert.assertEquals(username, userInfo.get("user"));
    Assert.assertTrue(userInfo.containsKey("roles"));
    List<String> roles = (List<String>) userInfo.get("roles");
    Assert.assertEquals(role.size(), roles.size());
    for(int i = 0; i < roles.size(); i++) {
      Assert.assertEquals(role.get(i), roles.get(i));
    }
  }
}
 
Example 2
Source File: LdapAuthenticationIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Assert authentication result using ldap-login.conf with given username and password.
 * All user for this test is configured so that role "admin" will be found and successfully authenticated.
 * @param ldapConf  The configuration for ldap-login.conf
 * @param username  username to login
 * @param password  password to login
 * @throws Exception
 */
public static void assertAuthenticationSuccess(String ldapConf, String username, String password) throws Exception{
  startSDCServer(ldapConf);

  String userInfoURI = sdcURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();

  Assert.assertEquals(200, response.getStatus());
  Map userInfo = response.readEntity(Map.class);
  Assert.assertTrue(userInfo.containsKey("user"));
  Assert.assertEquals(username, userInfo.get("user"));
  Assert.assertTrue(userInfo.containsKey("roles"));
  Assert.assertEquals(1, ((List)userInfo.get("roles")).size());
  Assert.assertEquals("admin", ((List)userInfo.get("roles")).get(0));
  stopSDCServer();
}
 
Example 3
Source File: TestHttpAccessControl.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void testCORSGetRequest(String userInfoURI) throws Exception {
  HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basic("admin", "admin");
  Response response = ClientBuilder.newClient()
      .target(userInfoURI)
      .register(authenticationFeature)
      .request()
      .header("Origin", "http://example.com")
      .header("Access-Control-Request-Method", "GET")
      .get();

  Assert.assertEquals(200, response.getStatus());

  MultivaluedMap<String, Object> responseHeader = response.getHeaders();

  List<Object> allowOriginHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER);
  Assert.assertNotNull(allowOriginHeader);
  Assert.assertEquals(1, allowOriginHeader.size());
  Assert.assertEquals("http://example.com", allowOriginHeader.get(0));
}
 
Example 4
Source File: RestClient.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor to verify the certificate and connect to the rest endpoint
 */
public RestClient(String username, String password) {
    SslConfigurator sslConfig = SslConfigurator.newInstance().trustStoreFile(Constants.CERTIFICATE_PATH)
            .trustStorePassword(Constants.CERTIFICATE_PASSWORD).keyStoreFile(Constants.CERTIFICATE_PATH)
            .keyPassword(Constants.CERTIFICATE_PASSWORD);
    SSLContext sslContext = sslConfig.createSSLContext();
    client = ClientBuilder.newBuilder().sslContext(sslContext).build();
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
    client.register(feature);
}
 
Example 5
Source File: KsqlRestClient.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
public void setupAuthenticationCredentials(String userName, String password) {
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(
      Objects.requireNonNull(userName),
      Objects.requireNonNull(password)
  );
  client.register(feature);
  hasUserCredentials = true;
}
 
Example 6
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response basicAuthenticationAtClientLevel(String username, String password) {
    //To simplify we removed de SSL/TLS protection, but it's required to have an encryption
    // when using basic authentication schema as it's send only on Base64 encoding
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .request()
            .get();
}
 
Example 7
Source File: AbstractProxy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
public Client getJerseyClient() {

        if(jerseyClient == null){
            jerseyClient = ClientBuilder.newClient();

            if(user != null && password != null){
                HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(getUser(),  getPassword());
                jerseyClient.register(feature);
            }
        }

        return jerseyClient;
    }
 
Example 8
Source File: LdapAuthenticationIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * Test using search filter. If roleSearchFilter is provided and has {dn}, then
 * we apply the filter by replacing {dn} with user's full DN.
 * @throws Exception
 */
@Test
public void testEmptyPassword() throws Exception {
  String memberFilter = "ldap {\n" + // information for server 1
      "  com.streamsets.datacollector.http.LdapLoginModule required\n" +
      "  debug=\"false\"\n" +
      "  useLdaps=\"false\"\n" +
      "  contextFactory=\"com.sun.jndi.ldap.LdapCtxFactory\"\n" +
      "  hostname=\"" + server.getContainerIpAddress()+ "\"\n" +
      "  port=\"" + server.getMappedPort(LDAP_PORT) + "\"\n" +
      "  bindDn=\"" + BIND_DN + "\"\n" +
      "  bindPassword=\"" + BIND_PWD + "\"\n" +
      "  authenticationMethod=\"simple\"\n" +
      "  forceBindingLogin=\"false\"\n" +
      "  userBaseDn=\"ou=employees,dc=example,dc=org\"\n" +
      "  userRdnAttribute=\"uid\"\n" +
      "  userIdAttribute=\"uid\"\n" +
      "  userPasswordAttribute=\"userPassword\"\n" +
      "  userObjectClass=\"inetOrgPerson\"\n" +
      "  roleBaseDn=\"ou=departments,dc=example,dc=org\"\n" +
      "  roleNameAttribute=\"cn\"\n" +
      "  roleMemberAttribute=\"member\"\n" +
      "  roleObjectClass=\"groupOfNames\"\n" +
      "  roleFilter=\"member={dn}\";\n" +   // {} is invalid. Default(search by full DN) should be applied
      "};";

  startSDCServer(memberFilter);

  String userInfoURI = sdcURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("user4", "");
  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();

  Assert.assertEquals(401, response.getStatus());
}
 
Example 9
Source File: TestLDAPAuthentication.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void testAuthenticationAndRoleMapping(String baseURL, String  authType, String username, String password,
                                              String role) {
  String userInfoURI = baseURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = null;

  switch(authType) {
    case "basic":
    case "form":
      feature = HttpAuthenticationFeature.basic(username, password);
      break;
    case "digest":
      feature = HttpAuthenticationFeature.digest(username, password);
      break;
  }

  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();
  Assert.assertEquals(200, response.getStatus());
  Map userInfo = response.readEntity(Map.class);
  Assert.assertTrue(userInfo.containsKey("user"));
  Assert.assertEquals(username, userInfo.get("user"));
  Assert.assertTrue(userInfo.containsKey("roles"));
  List<String> roles = (List<String>)userInfo.get("roles");
  Assert.assertEquals(1, roles.size());
  Assert.assertEquals(role, roles.get(0));
}
 
Example 10
Source File: ControllerRestApiTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
public ControllerRestApiTest() {

        org.glassfish.jersey.client.ClientConfig clientConfig = new org.glassfish.jersey.client.ClientConfig();
        clientConfig.register(JacksonJsonProvider.class);
        clientConfig.property("sun.net.http.allowRestrictedHeaders", "true");

        if (Utils.AUTH_ENABLED) {
            HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("admin", "1111_aaaa");
            clientConfig.register(feature);
        }

        client = ClientBuilder.newClient(clientConfig);
    }
 
Example 11
Source File: RestClientTest.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
 
     try {
         //Client client = Client.create();
         // Accept self-signed certificates
         Client client = createClient();

         String username = "user";
         String password = "password";
         //client.addFilter(new HTTPBasicAuthFilter(username, password));
         HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
         client.register(feature);
         
         WebTarget webResource = client.target("https://localhost:8443");
         WebTarget webResourceWithPath = webResource.path("ss7fw_api/1.0/eval_sccp_message_in_ids");
         WebTarget webResourceWithQueryParam = webResourceWithPath.matrixParam("sccp_raw", "12345");
         
         System.out.println(webResourceWithQueryParam);
         
         //ClientResponse response = webResourceWithQueryParam.accept("text/plain").get(ClientResponse.class);
         Response response = webResourceWithQueryParam.request("text/plain").get();
         
         if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
         }

         String output = response.readEntity(String.class);

         System.out.println("Output from Server .... \n");
         System.out.println(output);

} catch (Exception e) {
           e.printStackTrace();
}
     
 }
 
Example 12
Source File: ConnectorIDSModuleRest.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add IDS server
 * 
 * @param url url address of IDS server
 * @param username username for IDS server
 * @param password password for IDS server
 * @return true if successful
 */
public boolean addServer(String url, String username, String password) {
    Client client = createClient();
    serverList.add(client);

    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
    client.register(feature);
    
    //WebTarget target = client.target(url).path("ss7fw_api/1.0/eval_sccp_message_in_ids");
    WebTarget target = client.target(url);
    serverTargetsList.add(target);
    
    return true;
}
 
Example 13
Source File: ConnectorMThreatModuleRest.java    From SigFW with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean addServer(String url, String username, String password) {
    Client client = createClient();
    serverList.add(client);

    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
    client.register(feature);
    
    WebTarget target = client.target(url);
    serverTargetsList.add(target);
    
    return true;
}
 
Example 14
Source File: HttpBasicAuth.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public void setFilter(WebTarget webTarget) {
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
  webTarget.register(feature);
}
 
Example 15
Source File: ElasticsearchAuthentication.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public HttpAuthenticationFeature getHttpAuthenticationFeature() {
  if (username == null) {
    return null;
  }
  return HttpAuthenticationFeature.basic(username, password);
}
 
Example 16
Source File: TestUserGroupManager.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testFormAuthentication() throws Exception {
  String usersListURI =  startServer("form") + "/rest/v1/system/users";
  HttpAuthenticationFeature loginFeature = HttpAuthenticationFeature.basic("admin", "admin");
  testGetUsers(usersListURI, loginFeature);
}
 
Example 17
Source File: TestUserGroupManager.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicAuthentication() throws Exception {
  String usersListURI =  startServer("basic") + "/rest/v1/system/users";
  HttpAuthenticationFeature loginFeature = HttpAuthenticationFeature.basic("admin", "admin");
  testGetUsers(usersListURI, loginFeature);
}
 
Example 18
Source File: DatabricksJobExecutor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public List<Stage.ConfigIssue> init() {
  List<Stage.ConfigIssue> issues = new ArrayList<>();

  Optional
      .ofNullable(databricksConfigBean.init(getContext(), PREFIX))
      .ifPresent(issues::addAll);

  baseUrl = databricksConfigBean.baseUrl.endsWith("/") ?
      databricksConfigBean.baseUrl.substring(0, databricksConfigBean.baseUrl.length() - 1) :
      databricksConfigBean.baseUrl;

  HttpProxyConfigBean proxyConf = databricksConfigBean.proxyConfigBean;
  String proxyUsername = null;
  String proxyPassword = null;
  if(databricksConfigBean.useProxy) {
    proxyUsername = proxyConf.resolveUsername(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
    proxyPassword = proxyConf.resolvePassword(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
  }

  if(issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, 1)
        .property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    if (databricksConfigBean.useProxy) {
      clientConfig = clientConfig.connectorProvider(new GrizzlyConnectorProvider(new GrizzlyClientCustomizer(
          true,
          proxyUsername,
          proxyPassword
      )));
    }

    ClientBuilder builder = getClientBuilder()
        .withConfig(clientConfig)
        .register(JacksonJsonProvider.class);
    HttpAuthenticationFeature auth = null;
    if (databricksConfigBean.credentialsConfigBean.credentialType == CredentialType.PASSWORD) {
      String username = databricksConfigBean.credentialsConfigBean.resolveUsername(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      String password = databricksConfigBean.credentialsConfigBean.resolvePassword(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      auth = HttpAuthenticationFeature.basic(username, password);
      builder.register(auth);
    } else {
      String token = databricksConfigBean.credentialsConfigBean.resolveToken(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );

      builder.register((ClientRequestFilter) requestContext ->
          requestContext.getHeaders().add("Authorization", "Bearer " + token)
      );
    }

    JerseyClientUtil.configureSslContext(databricksConfigBean.tlsConfigBean, builder);

    if(databricksConfigBean.useProxy) {
      JerseyClientUtil.configureProxy(
          proxyConf.uri,
          proxyUsername,
          proxyPassword,
          builder
      );
    }

    client = builder.build();
    validateWithDatabricks(getContext(), issues);
  }
  return issues;
}
 
Example 19
Source File: RestClientImpl.java    From verigreen with Apache License 2.0 4 votes vote down vote up
@Override
public void setAuthentcation(String userName, String password) {
    
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(userName, password);
    _client.register(feature);
}
 
Example 20
Source File: ToDoStoreFactory.java    From todo-apps with Apache License 2.0 4 votes vote down vote up
private static WebTarget getWebTarget(CloudantServiceInfo info) {
  HttpAuthenticationFeature basicAuthFeature = HttpAuthenticationFeature.basic(info.getUsername(), info.getPassword());
  Client client = ClientBuilder.newClient().register(basicAuthFeature);
  return client.target(info.getUrl());
}