I got a problem with sending bearer token to the One Note API.
String returnUri = "https://login.live.com/oauth20_token.srf";
HttpClient client = HttpClientBuilder.create().build();
HttpPost tokenRequest = new HttpPost(returnUri);
tokenRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
tokenRequest.setEntity(new UrlEncodedFormEntity(Connection.getParametersForURLBody(), Consts.UTF_8));
tokenRequest.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0");
HttpResponse tokenResponse = client.execute(tokenRequest);
HttpGet getTopFiveNotebooks = new HttpGet("https://www.onenote.com/api/v1.0/me/notes/notebooks?top=5");
getTopFiveNotebooks.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + Connection.getValueByKey("access_token", Connection.getTokenInJson(tokenResponse)));
I got the Bearer Token and the header of the HttpGet-Request looks like this, if I look at it in debug-mode:
But when I try to perform the get, the API gives me a 401 Unauthorized Error.
My Scope is scope=wl.basic+onedrive.readwrite, so the token should have all permissions it needs.
Update: If I login into https://apigee.com/onenote/embed/console/onenote/ with my microsoft-account and copy the access-token from there into this piece of code:
getTopFiveNotebooks.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + acces-key-from-the apigee-console)
it performs the get and give me Status 200 back instead of 401.
So is my permission scope wrong?
Edit: My Scope was false.
Yes, you don't have the right scopes.
https://msdn.microsoft.com/en-us/library/office/dn807159.aspx
You need at least "office.onenote" to be able to get the user's notebooks.
Btw, if you look at the body of the 401 response, you'll see which scopes are missing.
Here are some cases where error could happen:
Please pay attention that string of scopes must be encoded too, so
instead of + you should use %20.
Also make sure that this function you used, returns anything:
Connection.getTokenInJson(tokenResponse)
And try this permission scope which works fine for me:
"office.onenote%20office.onenote_create%20office.onenote_update_by_app%20office.onenote_update"
Related
Tried to request with postman which gives desired response.
The java code used for making the same request is as below fails with a 403 status.
String url = "https://steamcommunity.com/inventory/76561198865293952/440/2?l=english&count=5000";
String cookiesString = "sessionid=" + generateSessionId() + ";steamCountry=IN%7Ce744269b3c4e531facb33ecaff29eb44";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest
.newBuilder()
.GET()
.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36")
.header("Accept", "*/*")
.header("Cookie", cookiesString)
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); //prints 403
System.out.println(response.body()); // prints �+�� O��%
/**
* Generates a Steam Session Id.
* #return sessionId.
*/
public static String generateSessionId() {
return new BigInteger(96, new Random()).toString(16);
}
Postman request does not need any headers(Not even User-Agent, only Host is kept, No cookies are needed) at all to get the desired response. Even navigating to link in browser shows the json response.
PostMan request ScreenShot
Postman Request Image with cookies
Thank you. Have a great day.
I am pretty sure that the 2 cookies you have in postman and not in the java code are responsible for having the 403 response.
Postman is a google chrome plugin so when connecting w/ chrome, maybe you stored in the cache the cookies.
You also need to add them to the java code.
Firstly Thanks for all your answers and replies.
So I found that the inventory that I was trying to access was set visible to friends only, so response was 403. So it does work for inventories that are set to public.
I am sorry, I should have check it first.
What I still dont understand is how did the postman desktop client get the intended response? I understand that chrome was able to get the inventory because I have active steam login with cookies that would have been send but postman request did not have any cookies other than sessionid and country. If someone could explain how this happens it would really help me.
I'm trying to send a POST request via HttpClient, but server response says "unauthorized" error. How I can get the Bearer Token? I searched for solutions but I don't understand it..
That's my code and I don't know how I get the token for the request...
HttpPost request = new HttpPost("http://domain...");
request.setHeader(HttpHeaders.ACCEPT, "application/json, text/plain, */*");
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/#json");
request.setHeader(HttpHeaders.ACCEPT_LANGUAGE, "de,en-US;q=0.7,en;q=0.3");
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br");
request.setHeader(HttpHeaders.REFERER, "https://domain...");
request.setHeader("DNT", "1");
request.setHeader(HttpHeaders.HOST, "host..");
String authToken = ""; // ... ?
request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);
StringEntity params = new StringEntity("{}");
params.setContentEncoding("UTF-8");
request.setEntity(params);
response = this.getHttpClient().execute(request);
First you have to authenticate user using user name and password(Using HTTP call) then you will have token in response same you can add it to your next POST call in header.
One get/post call is required before your POST call so that you will have token.
Same token can be used for all further call.
Seems you are trying to access some APIs which requires you to first get some access token (bearer token) before to hitting actual API.
Most flows involve two steps as explained below.
Step 1.
Fetch bearer token with basic authentication (below endpoint and parameter are sample value and will be different for your API)
POST /auth
`request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + authToken);`
Step 2:
Step1 will give you some kind of access token in response. You need to use that to make any subsequent API call.
GET /Student/Mark
`request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authToken);`
You can read more about bearer token at What is the OAuth 2.0 Bearer Token exactly?
Let me know in case you still have any doubts or not able to access your API with the approach I mentioned.
The location header is there, I can see it in browser:
I'm using org.apache.httpcomponents.httpclient to send http request with cookie:
```
URI uri = new URIBuilder().setScheme("https").setHost("api.weibo.com").setPath("/oauth2/authorize").setParameter("client_id","3099336849").setParameter("redirect_uri","http://45.78.24.83/authorize").setParameter("response_type", "code").build();
HttpGet req1 = new HttpGet(uri);
RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
req1.setConfig(config);
req1.setHeader("Connection", "keep-alive");
req1.setHeader("Cookie", cookie);
req1.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
response = httpclient.execute(req1);
```
I googled a lot and tried enable/disable auto redirect,but it doesn't seem to work for me.So can somebody tell me how to get the location header in response just like the browser did?
You cannot see 'location' header, because HttpClient followed that redirect immediately - even before giving you that response.
Try disabling redirect while setting up your HttpClient:
HttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
Check this URL and you'll see the Location Header:
URI uri = new URIBuilder().setScheme("https").setHost("www.googlemail.com").setPath("/").build();
I found out my real question...I didn't pass the auth process in my code,so I keep getting oauth2 page.After I set all the headers in my request just like the browser did and finally I get the right response.
I'm attempting to query a REST api using POST requests in a java application. I think I've set everything correctly, but I keep getting a Bad Request response.
HttpPost request = new HttpPost(requestURI);
request.addHeader("accept", "application/json");
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpEntity entity = new StringEntity(requestBody + new Integer(PatientId).toString() + "}");
request.setEntity(entity);
The requestBody, accompanied by the number and curly brace, are valid JSON, and the requestURI is copy and pasted straight out of the API documentation, so I know I shouldn't be getting a Bad Request due to those.
Am I missing something in the setup?
The Content-Length header is missing. Some servers don't report the correct 4xx error (411 Length Required) and just issue a generic Bad Request error.
It ended up being a random slash that wasn't included in my URI.
I know the default password for 5.9.0's HawtIO/Jolokia is set in the \conf\ folder and is
admin/admin
system/manager
etc
However, none of those password are working when trying to execute the restful commands through Java:
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(null, -80), new UsernamePasswordCredentials("admin", "admin"));
CloseableHttpClient httpclient0 = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
URI uri0 = URI.create("http://localhost:8161/hawtio/auth/login/");
HttpGet httpget = new HttpGet(uri0);
HttpResponse r0 = httpclient0.execute(httpget);
System.out.println("Login form get: " + r0.getStatusLine());
for (Header h : r0.getAllHeaders())
System.out.println(h.getName() + "/" + h.getValue());
HttpEntity entity = r0.getEntity();
InputStream is0 = entity.getContent();
String resp = IOUtils.toString(is0);
System.out.println("Response0: " + resp);
The following code just spits back a 403 Forbidden reply! I've tried many combinations of username and passwords.
Login form get: HTTP/1.1 403 Forbidden
Access-Control-Allow-Origin/*
Content-Length/0
Server/Jetty(7.6.9.v20130131)
What works here?
I recall when running 5.8.0 that "admin/admin" worked, but I'd like to use 5.9.0 instead. It would be lame to back out of this version just because the username and password changed.
Further, which \conf file dictates this password...?
you've almost got it, you just need to POST to that URL instead of doing a GET. And you just set your username/password in the Authorization header. The authentication filter in hawtio avoids sending back a 401 as that makes the browser authentication prompt appear, hence why you don't see 401 returned instead.