restsharp and Postman - oauth-2.0

I am attempting to get an OAuth2 access token from ZOHO using RestSharp code. The Postman simulation works correctly so I know there is something I'm missing in my code.
I always get an "invalid client id" result status. However in Postman, it works and returns a code when I click the "Get new access token". I have the same items as in the Postman authorization tab (client_id, client_secret, etc). In Postman, "Body" is set to "none", and there are no parameters or headers. The only difference between my code and postman, is that Postman requires the Callback URL. My code is trying to get the code using "self-client", which bypasses the callback URL.
I have tried several different alternatives to the request call including ParameterType.Body, and ParameterType.GetOrPost. Is GetOrPost the same as a form?
client = New RestClient(ZOHO_API_URL)
request = New RestRequest(TokenUrl, Method.POST)
request.AddHeader("content-type", "application/x-www-form-urlencoded") ' also tried: "application/json")
request.AddParameter("grant_type", "authorization_code",
ParameterType.GetOrPost)
request.AddParameter("client_id", Client_ID, ParameterType.GetOrPost)
request.AddParameter("client_secret", Client_Secret,
ParameterType.GetOrPost)
request.AddParameter("code", Grant_Token, ParameterType.GetOrPost)
response = client.Execute(request)
This is the translated Postman code for RestSharp:
var client = new RestClient("http://");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);
Any ideas on what I am doing wrong. I have tried to view the raw data coming across with Fiddler, but when I do that, Postman indicates a failure.
What code do I need to use to duplicate what Postman is doing?
How do I implement a callback URL if that is also required?

I quickly checked ZoHo REST API docs and it seems like you should use the Limited Input Device authentication flow.
From what I can understand from their help page, you indeed need to do a POST request, but parameters must be specified as query parameters:
https://accounts.zoho.com/oauth/v3/device/code?
client_id=1000.GMB0YULZHJK411248S8I5GZ4CHUEX0&
scope=AaaServer.profile.READ&
grant_type=device_request
You will also get better off with JSON set as a default for serialisation and content type just by using client.UseJson().

It maybe that Postman is following a redirect from your API endpoint as the functionality is different Postman verses RestSharp (possibly missing a trailing slash or similar).
Try adding
client.FollowRedirects = false;
to your RestSharp code and analyse the result.

Related

Unable to get the LTPA token using Rest assured

I am new to rest assured, I want to perform some get and post for test data generation using rest assured. But I am unable to get the LTPA token and pass them to post. This works with postman but I want to do it through java. Any help
final String uri = "https://XXXX/Rest/XXXXX?user=XXXXX&pass=XXXX";
final Response response = RestAssured.given().relaxedHTTPSValidation().accept(ContentType.JSON).get(uri);
System.out.println(response.prettyPrint());
Map<String, String> allCookies = response.cookies();
System.out.println(allCookies);
Output
{JSESSIONID=XXXXXXX:-1}
but i do not see the LTPA2 token
Your LTPA2 token must be in Response headers.
You can get the response headers by
response.headers ();
In case if LTPA token is also not available in headers then share the screenshot of postman so I can help you out.

AWS API Gateway issue for HTTP Method

I created an AWS API-gateway for an HTTP method PUT. When I do a test in API-gateway, that works fine, but when I call it from a REST client, I get 404 bad-request and missing authentication token errors. I didn't set any authorization to true or a required API key to true.
I passed these query parameters to a REST client:
auth_id : 8798iuyiu123123
time_stamp :1231231
test_json : [{"id"=>"1","value"=>"mount"},{"id"=>"2","value"=>"chart"}]
HEADER
content-type : application/json
When I change the test_json value to %5B%7B%22id%22:%221%22,%22value%22:%22test%22%7D,%7B%22id%22:%222%22,%22value%22:%2213+%D8%B4%D8%A7%D8%B1%D8%, then I get the response.
i am new to react, calling from react
Request.put('https://api-gateway.sqwdwed123.com/eretw/update-chart')
.set('Content-Type', 'application/json')
.query({ auth_id: localStorage.auth_id})
.query({ time_stamp:this.props.time_stamp})
.query({ test_json:JSON.stringify(newadd)})
should i pass this test_json through body?
Am I doing anything wrong?
This is usually related to requesting a URL that doesn't exist. Please make sure you're using the correct HTTP method and resource path to a valid resource (the sample invoke URL does not include any resource path). If this still doesn't work. Make sure you actually deployed your API.
The HTTP Response of Bad Request is because you have the Query Parameter that are not URL Encoded. There are 2 things that you can do now:
Pass the test_json as Query Param but making sure that they are URL Encoded. This will put a restriction on the size of the string and hence Not Recommended.
Pass the test_json as Request Body. (Recommended)

Reddit API returns HTTP 403

Following the OAuth2 login flow described at https://github.com/reddit/reddit/wiki/OAuth2 I got to the point where POST-ing to https://www.reddit.com/api/v1/access_token returns something like this:
{'token_type': 'bearer', 'expires_in': 3600, 'scope': 'identity', 'access_token': '*****'}
Then I do
GET https://oauth.reddit.com/api/v1/me
With this header:
Authorization: bearer *****
The response is HTTP 403 Unauthorized. But why? It is clear that the access token has 'identity' scope. It is also documented that the /api/v1/me call requires this scope only. (See https://www.reddit.com/dev/api/oauth#GET_api_v1_me )
So why am I getting http 403?
I was experiencing the exact same issue as you described. In my case, I resolved the 403 by adding a faux user agent string in the request headers.
In my case, using HttpClient of C#, this proceeds like so:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("User-Agent", "MockClient/0.1 by Me");
...
}
In my case this was because of a redirect.
Calling a non-oauth endpoint in my application (like https://www.reddit.com/r/learnpython/about.json) with the Authorization header would fail with code 403. But calling https://reddit.com/r/learnpython/about.json (without www) with the Authorization header succeeded. However both endpoints worked when I tried via Postman.
The reason for this is that reddit.com would redirect to www.reddit.com, which results in the Authorization header being dropped by Postman for the second request. In my application code, I was including the header with both requests, which explains the different behavior.
Solution: don't include the Authorization header when calling non-oauth endpoints.

Authenticating to an API with a token

I'm working with the Zendesk API, an HTTPS-only, JSON API and authentication is required to update a resource, and the API supplies an API token to use when authenticating as different users. When updating a resource, I issue a PUT request over SSL, assign the appropriate JSON content to the request body, and specify the Content-Type request header as application/json.
Next, the API instructs its users to authenticate as the end-user by either using the user's email and password (which I can't do for several reasons) or to use the user's email address along with the API token. The following is my attempt to authorize to the API with the Authorization header:
#id = params[:id]
#comment_body = params[:comment]
uri = URI.parse "https://{subdomain}.zendesk.com/api/v2/requests/#{#id}.json"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Put.new(uri.request_uri)
req.body = '{"request": {"comment":{"value":' + "\"#{#comment_body}\"" + '}}}'
req['Content-Type'] = 'application/json'
#The following two lines do not work!
credentials = Base64::encode64("{user_email}/token:{api_token}")
request.headers['Authorization'] = "Basic #{credentials}"
response = http.request(req)
The API specifies that the format for authentication using the API token is {user_email}/token:{api_token}. I encoded that format with Base64::encode64 and passed it to the Authorization Header preceded with Basic, but the response is a 401 Unauthorized. However, replacing those two lines with req.basic_auth {user_email}, {user_password} works fine.
So my question is, how can I authenticate as a different user using the email and the given API token as authentication instead of supplying the user's email and password to req.basic_auth?
The googling I've done on the topic has revealed very little; apparently it's a lot more common to use the normal {username}:{password} format when dealing with the Authorization header than an API token.
Thanks in advance!!
Update: Weirdly, trying to authenticate as the end-user with req['Authorization'] = "Basic #{credentials}" does not return a 401 Unauthorized Error or a WWW-Authenticate header while trying to authorize as request.headers['Authorize'] = "Basic #{credentials}" does.
Finally figured it out after much head-banging and nearly throwing my laptop out the window. Suddenly, the answer seems incredibly obvious.
When using Net::HTTP, its basic_auth method can also accept tokens depending on the API, and the Zendesk API specifies that the format for using the API token is {email}/token:{token}. Basic authentication uses the format {username}:{password}, where the two fields are separated by a colon, meaning in Zendesk's case I can place {email}/token as the first argument and {token} as the second argument (instead of the username as the first argument and the password as the second argument), so the following code is correct:
req.basic_auth "{email}/token", "{api_token}"
I hope anyone who found this useful could leave a comment. Nice to know I spared someone from this frustration.

Authorization headers for google login using restlet

Using restlet, I want to make a post to android's c2dm service. I have tried this from a generic rest client and all worked ok.
However, when I try to post using restlet, I get a (401) - Unauthorized response.
For authorization, I need to set the following header:
Authorization: GoogleLogin auth=my_auth_token
How do I set this header using restlet? I know I need to set a challenge response, but I'm not sure about it's parameters. Is "GoogleLogin " my ChallengeScheme? Do i use it like this:
ChallengeScheme.valueOf("GoogleLogin")
What about setting the token?
Thanks
You can create a custom scheme and set the challenge response with this scheme for your requests :
ChallengeScheme sc = new ChallengeScheme("Google_Login", "GoogleLogin", "Android c2dm service");
clientResource.setChallengeResponse(sc, auth, myauthtoken);

Resources