How i can get the Bearer Token from HttpClient? - java

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.

Related

Adding an authentication token to header in Restlet

I am trying to make an API call using Restlet in java however when I run my code I get an org.restlet.resource.ResourceException: Unauthorized (401) - The request requires user authentication
The format for the API call is as follows for shell: curl "<api_url>" \ -H "Authorization: Bearer <api_token_here>"
However I am unsure how to add this authorization header in Restlet, as you are not able to add the header using .getRequest().getHeaders().add();
Additionally I have tried to set a challenge response however this also does not appear to work.
API = new ClientResource(RequestURL);
API.setProtocol(Protocol.HTTPS);
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.CUSTOM);
AuthHeader.setRawValue("Authorization: Bearer " + APIKey);
API.getRequest().setChallengeResponse(AuthHeader);
API.get();
I appear to have solved the issue with the following code:
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
AuthHeader.setRawValue(APIKey);
AuthHeader.setIdentifier("Bearer");
API.setChallengeResponse(AuthHeader);

How to do OAuth 2 API call and get the response

I want to create a Spring boot application, that will call an API through OAuth2 process.
I've already checked this but can some explain it to me in a simple way.
All I have is the URL (that gets the Bearer token), Client ID and Client Secret.
Once the bearer token is retrieved I want to get the call the actual API with the retrieved bearer token put in the header, So I get the response.
In Spring,
you can use the RestTemplate.exchange method to make API calls.
Since the API is secured using an OAuth2.0 - Access token (bearer token),
the token must be passed in the "Authorization" header.
Try the code shown below to make an API call with header request:
String url = "https://you-api-url";
RestTemplate restTemplate = new RestTemplate();
// set the headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token_value);
HttpEntity entity = new HttpEntity(headers);
// send the GET request
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
// display the response
System.out.println("Response" + response.getBody());
Hope it helps!

One Note Api rejects Bearer Token, Error 401

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"

Getting 401-Unauthorized while getting photo using outlook REST API - java cliet

I am trying to retrieve user photo using outlook REST API(https://msdn.microsoft.com/en-us/office/office365/api/photo-rest-operations#UserphotooperationsGetphoto)
I got the access token following (https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx)
but getting this error : any help?
HTTP/1.1 401 Unauthorized [Content-Length: 0, Server: Microsoft-IIS/8.0, request-id: 6925fcab-9021-4059-af4b-4cbf130faea7, X-CalculatedBETarget: CY1PR0401MB1388.namprd04.prod.outlook.com, X-BackEndHttpStatus: 401, Set-Cookie: exchangecookie=87cb2447eae9401c80a96c497dff06a9; expires=Sat, 22-Apr-2017 07:56:53 GMT; path=/; HttpOnly, x-ms-diagnostics: 2000001;reason="The access token is acquired using an authentication method that is too weak to allow access for this application. Presented auth strength was 1, required is 2.";error_category="invalid_token",
code looks something like this:
HttpClient httpclient = HttpClients.createDefault();
final String bearerToken = getBearerToken();
HttpGet request = new HttpGet("https://outlook.office.com/api/v2.0/me/photo/$value");
request.setHeader(javax.ws.rs.core.HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken);
request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
HttpResponse response = httpclient.execute(request);
return IOUtils.toByteArray(response.getEntity().getContent());
According to the error message. Instead of a client_secret in your request body, you need a client_assertion.
For more details, you can reference the blog Building Daemon or Service Apps with Office 365 Mail, Calendar, and Contacts APIs (OAuth2 client credential flow)
According to the API you call "https://outlook.office.com/api/v2.0/me/photo/$value". It seems that you only want to get the photo for the current login user; if so, you can use Authorization Code Grant Flow to get the token which will not require the client certificates.
UPDATE#1:
Can this be done programmatically/API way
As far as I know, the consent need the user's or admin's interactivity.
https://login.windows.net/common/oauth2/authorize?response_type=code&client_id={0}&resource={1}&redirect_uri={2}&prompt={3}
If you are developing a ASP.NET web application, you can reference the sample project O365-WebApp-MultiTenant.
BTW, when calling the API with app-token, you need to specify the user name.
e.g.
https://outlook.office.com/api/v2.0/users('user1#customdomain.onmicrosoft.com')/messages
UPDATE#2:
The 403 code when updating the photo using the app token is expected result.
As we can see from the figure above, updating the user photo requires the delegated permission "User.Read.Write". The app token does not have permission to update user's photo.

paypal access token not returning

I trying to send a payment with my test application. Im using the paypal java sdk package.
Im not receiving my access token. Im receiving only the bearer token,
Bearer WesirDWp61YcTr8N8XWZHnPk7tCch.ZgcMvLfyp-FRA : appId :
APP-80W284485P519543T
Thus when I try to send a payment Im getting and 401 authorization error because of no access token. The first time I sent the request it returned the access token but every subsequent attempt brings this error:
Java exception "com.paypal.core.rest.PayPalRESTException: Error code : 401
with response : Server returned HTTP resp" when calling method "create" with
signature "(Ljava.lang.String;)Lcom.paypal.api.payments.Payment;" in class
"com.paypal.api.payments.Payment".
I do not understand what is happening here . Am I completely missing the boat here?
Thank You for any response.
Hit this URL with POST Request on Postman.
POST https://api.sandbox.paypal.com/v1/oauth2/token
On Authorization choose basic auth and enter the username as a clientID and password as a ClientSecret.
In Header set Content-Type: application/x-www-form-urlencoded
In Body seelect x-www-form-urlencoded and write grant_type: client_credentials
after that send request you will get the access_token
The bearer token is the access token, more specifically it is the type of access token returned. As per the REST API Reference (which is what the java sdk calls), the call to the oauth end point returns:
{
"scope": "https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.*",
"access_token": "EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG",
"token_type": "Bearer",
"app_id": "APP-6XR95014SS315863X",
"expires_in": 28800
}
The SDK combines the two fields and returns them as the "Bearer token".
This bearer token is all you need to access the REST APIs (with some restrictions based on the permissions/scopes requested and how the bearer token was requested, however that is dependent on creation call). Pass the bearer token in the authorization header:
"Authorization: Bearer EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG"

Categories

Resources