java client program to send digest authentication request using HttpClient API - java

I have restlet sample client program which sends the digest request. Similar to this I need java client program which sends a digest request using HttpClient api.
Can anybody send me sample code. Thanks in advance.
Reference reference = new Reference("http://localhost:8092/authenticate");
Client client = new Client(Protocol.HTTP);
Request request = new Request(Method.GET, reference);
Response response = client.handle(request);
System.out.println("response: "+response.getStatus());
Form form = new Form();
form.add("username", "rajesh");
form.add("uri", reference.getPath());
// Loop over the challengeRequest objects sent by the server.
for (ChallengeRequest challengeRequest : response
.getChallengeRequests()) {
// Get the data from the server's response.
if (ChallengeScheme.HTTP_DIGEST
.equals(challengeRequest.getScheme())) {
Series<Parameter> params = challengeRequest.getParameters();
form.add(params.getFirst("nonce"));
form.add(params.getFirst("realm"));
form.add(params.getFirst("domain"));
form.add(params.getFirst("algorithm"));
form.add(params.getFirst("qop"));
}
}
// Compute the required data
String a1 = Engine.getInstance().toMd5(
"rajesh" + ":" + form.getFirstValue("realm") + ":" + "rajesh");
String a2 = Engine.getInstance().toMd5(
request.getMethod() + ":" + form.getFirstValue("uri"));
form.add("response", Engine.getInstance().toMd5(
a1 + ":" + form.getFirstValue("nonce") + ":" + a2));
ChallengeResponse challengeResponse = new ChallengeResponse(
ChallengeScheme.HTTP_DIGEST, "", "");
challengeResponse.setCredentialComponents(form);
// Send the completed request
request.setChallengeResponse(challengeResponse);
response = client.handle(request);
// Should be 200.
System.out.println(response.getStatus());

Have you tried the following:
ChallengeResponse challengeResponse = new ChallengeResponse(challengeRequest, "rajesh", <password>);

Here you go:
HttpClient client = new HttpClient();
Credentials creds = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(new AuthScope(host, port, realmName), creds);
GetMethod get = new GetMethod(url);
get.setDoAuthentication(true);
client.getParams().setAuthenticationPreemptive(true); // seems to be necessary in most cases
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Collections.singleton(AuthPolicy.DIGEST));//need to register DIGEST scheme not the basic
client.getAuthSchemes().register(AuthPolicy.DIGEST, new DigestSchemeFactory());
client.executeMethod(get);
result = get.getResponseBodyAsString();

Related

Can't use Dynamics CRM token (401 Unauthorized)

I'm writing a simple android app in Java and recently implemented retrieving a token for a user from Microsoft Dynamics CRM (I have created a connected app in Azure, got application id, secret etc).
I want other users of this application to be able to connect to their CRMs and organizations.
Now I'm trying to use the token with the REST API and getting 401 error.
Read all the related answers here, nothing helped. The code I'm using:
//retrieved the authorization code by this url:
mAuthorizationUrl = Configuration.AUTHORIZE_ENDPOINT + "?response_type=code&client_id="
+ Configuration.CLIENT_ID + "&redirect_uri=" + Configuration.REDIRECT_URI;
...
//Retrieving access_token:
String body_content = "grant_type=authorization_code&client_id=" +
Configuration.CLIENT_ID + "&redirect_uri=" + Configuration.REDIRECT_URI
+ "&code=" + code + "&resource=" + Configuration.CLIENT_ID;
//I don't have app URI (resource) in Azure, so I used app id (client id).
//This worked (see above).
RequestBody body = RequestBody.create(
MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),
body_content);
Request request = new Request.Builder()
.url(Configuration.TOKEN_RETRIEVAL_ENDPOINT)
.post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
String responseString = response.body().string();
JSONObject json = new JSONObject(responseString);
String token = json.getString("access_token");
//NOT WORKING CODE:
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();
Map<String, String> headers = new ArrayMap<>();
headers.put("Authorization", "Bearer " + token));
headers.put("Accept", "application/json");
request = new Request.Builder()
.url(Configuration.REST_ENDPOINT)
.headers(Headers.of(headers))
.build();
try {
response = okHttpClient
.newCall(request)
.execute();
statusCode = response.code();
}
...
//401 UNAUTHORIZED
Endpoints I used:
AUTHORIZE_ENDPOINT = https://login.microsoftonline.com/common/oauth2/authorize
TOKEN_RETRIEVAL_ENDPOINT = https://login.microsoftonline.com/common/oauth2/token
REST_ENDPOINT = url_to_crm/api/data/v9.0/
Here are two sample Java projects that connect and authenticate with the Dynamics Web API via Azure:
Link 1
Link 2
Hope this helps.

Solr Import via ModifiableSolrParams with security credentials

I'm trying to execute import via java using ModifiableSolrParams:
Can you please point me on the right direction or reference on how to add security credentials (username / password) to trigger the import.
Current code
SolrServer server = new HttpSolrServer(baseurl);
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("command", "full-import");
params.set("clean", "true");
params.set("commit", "true");
QueryRequest request = new QueryRequest(params);
request.setPath("/dataimport");
server.request(request);
You need to add HttpRequestInterceptor to you HttpServer. This interceptor will be able to add authorization header to every your request.
For cloud Solr the util class that allow to do this is HttpClientUtil. You can start from this class, or check where in HttpSolrServer is actually HttpClient present.
I veered away from Solrj and went with this approach instead.
HttpClient Client = new DefaultHttpClient();
String userpass = usr + ":" + pwd;
HttpPost httpGet = new HttpPost(dataimport_cmd);
String encoding =
DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
httpGet.setHeader("Authorization", "Basic " + encoding);
Client.execute(httpGet);

Making requests to another App Engine app

From my GAE server side code, Iam using urlfetchservice to update the datastore on another GAE. This results in Response code 302
Please find the code snippet below,
String urlVal = "https://valeo-is-qc-dev.appspot.com/a/qccards/"+modelObj.getQc_reference_id()+"/updatellcreference?llcref="+modelObj.getReference()+"&llcrefid="+modelObj.getId();
URL url = new URL(urlVal);
// Create HTTPRequest and set headers
com.google.appengine.api.urlfetch.FetchOptions fetchOptions = com.google.appengine.api.urlfetch.FetchOptions.Builder.withDefaults();
fetchOptions.doNotValidateCertificate();
fetchOptions.doNotFollowRedirects();
HTTPRequest httpRequest = null;
httpRequest = new HTTPRequest(new URL(url.toString()), HTTPMethod.PUT,fetchOptions);
httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth " + token_id));
httpRequest.addHeader(new HTTPHeader("X-Appengine-Inbound-Appid", "valeo-is-llc-dev"));
httpRequest.addHeader(new HTTPHeader("Host", "https://test-is-abc-dev.appspot.com"));
httpRequest.addHeader(new HTTPHeader("Content-Type", "text/plain"));
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
HTTPResponse httpResponse = null;
httpResponse = fetcher.fetch(httpRequest);
if (httpResponse.getResponseCode() == HttpURLConnection.HTTP_OK) {
LOGGER.log(Level.INFO, "abc def Bridge Response OK --- " + httpResponse.getResponseCode());
LOGGER.log(Level.INFO, "abc def Bridge Response OK --- " + httpResponse.toString());
} else {
// Server returned HTTP error code.
LOGGER.log(Level.INFO, "abc def Bridge Response FAIL --- " + httpResponse.getResponseCode());
}

How to use httpclient 4.3.6 to invoke DCTM 7.1 REST API?

I am looking to interact with a Documentum Repository using their REST API. I would like to use the http-client 4.3 jars to perform this interaction.
I was hoping someone might have a sample that would help point me in the correct direction on how to interact with DCTM.
I am having trouble finding a clear and simple example of how to do this.
Thanks
I know it is a bit late to answer this question. But i want to answer to help those who still need a code for making requests to the rest api. Here is a full example of sending a post request to the rest api for starting a workflow.
For other needs you can check the Document called Documentum xCP Rest Services provided by EMC : https://support.emc.com/docu52500_Documentum-xCP-REST-Services-2.1-Development-Guide.pdf?language=en_US&request=akamai and compare with this example, change it according to it's needs.
UPDATE:
Also if you are not using xcp here is the Documentation for rest api without it emc.com/collateral/TechnicalDocument/docu57895.pdf
You can also check my answer here How can I use REST to copy an object in Documentum 7.x for geting object data and content from the rest api ( without xcp )
String strResponse = "";
String process_id = "system_name of the process you want to start";
String url = "Your App Url Here/processes/" + process_id;
String json = "{"+
"\"run-stateless\" : \"false\","+
"\"data\" :"+
" { "+
" \"variables\" : "+
" { \"Variable name\" : \"Variable value\" } "+
" } "+
"}";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
BufferedReader rd = null;
CloseableHttpResponse cls = null;
try {
HttpPost request = new HttpPost(url);
// set timeouts as you like
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(60 * 1000).setConnectTimeout(20 * 1000)
.setConnectionRequestTimeout(20 * 1000).build();
request.setConfig(config);
StringEntity params = new StringEntity(json);
request.addHeader("Accept", "application/json");
request.addHeader(
"Authorization",
"Basic "
+ com.documentum.xmlconfig.util.Base64
.encode("username here" + ":"
+ "password here"));
request.addHeader("Content-Type", "application/vnd.emc.xcp+json");
request.setEntity(params);
try {
cls = httpClient.execute(request);
HttpEntity entity = cls.getEntity();
rd = new BufferedReader(new InputStreamReader(
entity.getContent()));
String line = "";
while (line != null) {
line = rd.readLine();
strResponse += line;
}
strResponse = strResponse.trim().replace("\n", "");
String statusline = cls.getStatusLine().toString();
if (!statusline.contains("200") && !statusline.contains("201")) {
Log.write("Process is not started");
// log the strResponse or do something with it
} else {
System.out.println("Process started successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
} finally {
// using commons-io-2.4.jar
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(cls);
IOUtils.closeQuietly(rd);
}

Http File upload using Apache MultipartEntityBuilder

Below is the Http post method for file upload in c#. What is the equivalent for this code in java which uses apache library. How to add contentDisposition in java and pass byte array value in it. Providing some online reference is much appreciated.
C# Code
byte[] date = //file in byte format
var fileContent = new StreamContent(new MemoryStream(data));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + filename + "\""
}; // the extra quotes are key here
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
var content = new MultipartFormDataContent();
content.Add(fileContent);
HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _url + uri);
request.Content = content;
My Java Code
StringBody name = new StringBody("\"files\"", ContentType.MULTIPART_FORM_DATA);
StringBody file = new StringBody("\"" + filename + "\"", ContentType.MULTIPART_FORM_DATA);
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("Name", name)
.addPart("FileName", file)
.addBinaryBody("file", data)
.build();
Postmethod = new HttpPost(_url + uri);
Postmethod.addHeader(useragent);
Postmethod.addHeader(Accesstoken);
Postmethod.setEntity(entity);
Postmethod.addHeader("content-type", contentType);
response = httpClient.execute(Postmethod);
The response status code is 400 .Where did I go wrong?
Thanks in Advance..

Categories

Resources