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);
Related
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.
I want to get access token OAuth 2.0 from REST API via Java code, the thing is that I've managed to successfully get it back from the server with Bash script (curl command)
Bash script (working):
#!/usr/bin/env bash
# Base URL of TeamForge site.
site_url="https://teamforge.example.com"
# TeamForge authentication credentials.
username="foo"
password="bar"
# Requested scope (all)
scope="urn:ctf:services:ctf
curl -d "grant_type=password&client_id=api-client&scope=$scope&username=$username&password=$password" $site_url/sf/auth/token
With that code snippet I'got this response:
{
"access_token": "eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1ZCI...",
"token_type": "Bearer"
}
When I've tried to translate it to Java code using Unirest :
HttpResponse<JsonNode> jsonResponse = Unirest.post("\"https://teamforge.example.com/sf/auth/token")
.header("accept", "application/json")
.body("{\"grant_type\":\"password\"," +
"\"client_id\":\"api-client\", " +
"\"scope\":\"urn:ctf:services:ctf\"," +
"\"username\":\"foo\"," +
"\"password\":\"bar\"}")
.asJson();
System.out.println(jsonResponse.getBody());
Response was:
{"error_description":"Invalid grant","error":"invalid_grant"}
After a couple of researches and tries, I still don't know what am I missing in my Java code request. Can someone help me to add missing stuff or guide me to right directions?
CollabNet docs:
Saso
Please try:
JsonNode jsonResponse = Unirest.post("https://teamforge.example.com/sf/auth/token")
.header("Content-Type", "application/json")
.field("scope", "urn:ctf:services:ctf")
.field("client_id", "api-client")
.field("grant_type", "password")
.field("username", "foo")
.field("password", "bar")
.asJson()
.getBody();
And one more question are you sure about grant type ?
grant_type = client_credentials maybe you need something like this.
When I do an outh request from my App to laguages url from a repository from Github using the url provided by the API using an access token I get the following response
{
"message":"Resource not accessible by integration",
"documentation_url":"https://developer.github.com/v3/repos/#list-languages"
}
The code looks like this
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, languagesUrl);
oAuthRequest.addHeader("Authorization", "Bearer " + accessToken);
The scopes are "user:email,public_repo"
when I remove the token from the header shows me the languages from the repo but of course with a limit of 60 request per hour... On Thursday It was working OK but since yesterday it's not and the others links of the repositories works fine with the same token.
Do anyone
someone has had the same problem??
I'm trying to connect my Java application to the Watson NLU service. For a start, I tried to follow the tutorial from Bluemix. I created a service on Bluemix and imported the watson Java SDK. Using this tutorial code, I keep receiving 401 - not authorized responses. (Of course i changed username and password for the service).
I guess there's something missing, but i can't figure out what.
NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27,
"{username}",
"{password}"
);
String text = "IBM is an American multinational technology " +
"company headquartered in Armonk, New York, " +
"United States, with operations in over 170 countries.";
EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
.emotion(true)
.sentiment(true)
.limit(2)
.build();
KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
.emotion(true)
.sentiment(true)
.limit(2)
.build();
Features features = new Features.Builder()
.entities(entitiesOptions)
.keywords(keywordsOptions)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.text(text)
.features(features)
.build();
AnalysisResults response = service
.analyze(parameters)
.execute();
System.out.println(response);
i had the same problems in node.js and solved it by adding the correct url of the api gateway to the NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding() object.
please keep in mind, that this depends on your region ..
regards
Leo
A 401 Unauthorized would suggest that there's an issue with the credentials that you're using to access the service. To rule this out, take a start by using the cURL tutorial from that same page:
curl -X POST \
-H "Content-Type: application/json" \
-u "{username}":"{password}" \
-d #parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27"
If, with that same username and password, you still receive a 401 Unauthorized error, then there's likely an issue with that username/password combination. Delete the tile in Bluemix and create a new one to get a new username/password, and give that a try.
If that does work fine, then there's an issue with how the username/password is being inserted into the code. Verify that you've replaced {username} and {password}, the final version should not have any curly brackets in it.
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"