pinkpanther
pinkpanther

Reputation: 4808

How to set username and password using RESTEasy client builder?

I have a url which needs authentication (like a browser pop up appears asking username and password.)

enter image description here

Generally, we can use the following format to achieve this:

http://username:[email protected]

Using RESTEasy client builder

 Client client = ClientBuilder.newClient();
 WebTarget target = client.target("http://url.com");

How to achieve it without having to construct the http://username:[email protected] myself? I've seen if there are any methods which I could use to set it with no luck. Also I'm not sure how these credentials are passed, headers, cookies etc..

Upvotes: 2

Views: 4170

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209092

Looks like Basic Authentication. If that's the case, you just need to set the Authorization header to Basic base64encode(username:password).

For example:

String credentials = "username:password"
String base64encoded = Base64.getEncoder().encodeToString(credentials.getBytes());
Response response = target.request()
        .header(HttpHeaders.AUTHORIZATION, "Basic " + base64encoded)....

The Base64 class I used is from Java 8. If you're not using Java 8, there are libraries that have Base64 support. Prior to Java 8, there's a com.sun internal Base64 class, but it's advised not to use those.

If you just want to run a quick test (and don't have Java 8 or don't want to go looking for a lib), you can go to this site and just type in your username:password and encode it, then just copy and paste to your code.

For example:

base64encode(username:password) == dXNlcm5hbWU6cGFzc3dvcmQ=

Upvotes: 5

Related Questions