I'm new to OAuth and trying to send a https GET request to retrieve something. Earlier I was using POSTMAN to test that and I was able to execute the GET request with OAUth 1.0 header authorization. The header authorization looks something as
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxxxxxxx" ,oauth_signature_method="HMAC-SHA1" ,oauth_timestamp="1409861973" ,oauth_nonce="x1409861973681" ,oauth_version="1.0" ,oauth_signature="M+Dq62XboEd3+t6VDIcLy86zlQg="
The query looks something as
https://secure.api.abc.net/DataService/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,yyyyy}
Note that I'm able to execute this fine from POSTMAN.
Now, I need to code that in java and I'm able to generate the oauth signature fine, but I'm wondering how do I set the authorization header after that in a https request???
Please advise as I'm new to oauth and want to learn.
I guess if your doing in Java, you will need to use the Apache HttpClient or something similar to make that request to the server and set the OAuth header to the request.
Code sample using the Apache HttpClient below.
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("OAuth", oauthHeaderString);
HttpResponse response = client.execute(request);
Related
I'm working on a project which requires to call GitHub APIs several times and I reached the limit of 60.
I read that with authentication you get 5000 as limit but I can't understand how I can authenticate my requests in my java program. I got my authentication token on Github and this is the way I'm building the request in java:
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
.build();
what should I add to the request to authenticate it?
I tried adding the header authToken:myToken but it didn't work.
Solved:
Once I got the token on my GitHub profile > Settings > Developer Settings > Personal Access Tokens, I added the header `"Authorization: Bearer "myToken" " to the http request so the request becomes:
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder().header("Authorization","Bearer <myToken>")
.uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
.build();
You need to add Http request header Authorization to your request and the header should contain your token. So if your code is written on Java 11 or higher as it appears to be than you need to change your code to:
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
.header("Authorization", "your-tocken")
.build();
i want to send a SAML request to my IDP (Azure AD) but ia m not sure how to send the request at all.
First i used OpenSAML to build an AuthRequest. Which i encoded as a String.
Now i wanted to use ApacheHttpClient to send the request and read the response and i am not sure if OpenSAML provides http sending methods at all so my idea was to use Apaches HttpClient for this for now.
String encodedAuthRequest = generateAuthRequest();
String url = "http://myidp/samlendpoint";
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
// what is to add else?
HttpResponse response = client.execute(request);
I am stuck now since i am not sure how to setup the request, does it need to be a query parameter like ?saml=.... in GET or do i have to put the encoded saml response in the body as POST..
Can someone help or clarify these issue?
Update from Guillaumes answer:
I have this from the IDPs MetaData:
<IDPSSODescriptor>
<SingleSignOnService
Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
Location="https://myidp/saml2" />
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
Location="https://myidp/saml2" />
Depends on which binding you are supposed to use. The IdP documentation or metadata should mention that. There are several:
Redirect Binding (using a GET), by far the most common for Requests
POST Binding
Artifact Binding (more complex, but I have never seen it used for Requests)
...
I suppose that Redirect Binding will be used in your case (EDIT: you added the metadata from your IdP, it mentions that you can use both Redirect and POST bindings). It is described here: https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf page 15.
Short version: your must first use the DEFLATE algorithm to compress your XML Request, encode it using base64, encode it using URL encoding, then pass it as a query parameter named SAMLRequest
?SAMLRequest=<your url-encoded base64-encoded deflated authnrequest>
https://en.wikipedia.org/wiki/SAML_2.0#SP_Redirect_Request.3B_IdP_POST_Response
I have a java/j2ee web application consuming SP web services but recently the SP site got migrated to 2013 and deployed in cloud/office 0365 due to which authentication got broken. SP people suggested to change authentication mechanism to SAML token based authentication and use Microsoft Azure AD. So i on boarded my application into Azure and received Client ID, Authority using which i am able to generate security token(used adal4j java api) . Now i need to complete below 2 steps to complete the authentication process in office 0365 to access SP 2013 web services.
Get access token cookies
Get request digest token
But not able to find any java based API for above 2 steps. Refereed below tutorial buts its something related to aps/.net
http://paulryan.com.au/2014/spo-remote-authentication-rest/
Please help me in providing sample code base for the same.
Appreciate your support
So you used Microsoft Azure Active Directory Authentication Library (ADAL) for Java?
In which case, have a look at AAD Java samples.
You want the ones that consume a Web API.
Per my experience, I think you can try to directly follow your refered article step by step to use the Apache HttpClient to construct the request.
For example, the code below is using the HttpClient to do the post request with the xml body to get the security token.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://login.microsoftonline.com/extSTS.srf");
String xmlBody = "...";
InputStreamEntity reqEntity = new InputStreamEntity(
new ByteArrayInputStream(xmlBody.getBytes(), -1, ContentType.APPLICATION_OCTET_STREAM);
reqEntity.setChunked(true);
httpPost.addHeader("Accept", "application/json; odata=verbose")
httpPost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
String respXmlBody = EntityUtils.toString(response.getEntity());
//Parse the respXmlBody and extract the security token
You can try to follow the code above to get the response includes access token via do the post request with the security token body for the url https://yourdomain.sharepoint.com/_forms/default.aspx?wa=wsignin1.0, and use the code Header[] hs = response.getHeaders("Set-Cookie"); to get the Set-Cookie header array as access token.
Then using them to set the two headers Cookie for getting the request digest token, and parse the response body to extract the FormDigestValue as the request digest token.
POST request to server using java URLConnnection
I need to send a POST request with the two parameters below:
param1=value1
param2=value2
And also I need to send a file.
In the case of Apache these 2 two(sending params and file) things are handled like below
post.setQueryString(queryString) // queryString is url encoded for eg: param1=value1¶m2=value2
post.setRequestEntity(entity) // entity is constructed using file input stream with corresponding format
Please let me know if you have anything related to this problem.
Please note: When I try using Google Chrome REST client plug-in, I am getting the response as below (tried with all request content-types)
UNSUPPORTED FILE FORMAT: 'multipart/form-data' is not a supported content-type
Response code is 400.
Try this API from Apache to send request internally with POST method.
The below is the sample Code to use API
List<org.apache.http.NameValuePair> list =new ArrayList<org.apache.http.NameValuePair>();
HttpPost postMethod = new HttpPost("http://yoururl/ProjectName");
list.add(new BasicNameValuePair("param1", "param1 Value")) ;
postMethod.setEntity(new UrlEncodedFormEntity(list));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(postMethod);
InputStream is = response.getEntity().getContent();
I use Robotium to test Android app. In the middle of a test I need to create POST request to server to some money to user and then verify that changes are reflected in UI.
Request looks like:
wwww.testserver.com/userAddMoney?user_id=1&amount=999
But to authorize on server I need to pass special parameters to Header of request:
Headers: X-Testing-Auth-Secret: kI7wGju76kjhJHGklk76
You could look into the Apache HC package:
HttpPost post = new HttpPost( "http://wwww.testserver.com/userAddMoney" );
...
post.addHeader( "X-Testing-Auth-Secret" , "kI7wGju76kjhJHGklk76" );
...
Cheers,