I am using OAUTH2 authentication to import GMAIL contacts . In my code I am storing the config parameters in an array :
$clientid=<my Client id>;
$clientsecret=<my client secret>;
$redirecturi=<my redirect URL>;
$max_results = 25;
Below is how I create the POST array :
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($clientid),
'client_secret'=> urlencode($clientsecret),
'redirect_uri'=> urlencode($redirecturi),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
Now I'm making a CURL call to get the access token :
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
log_message('debug','POST'.$post);
log_message('debug','contents'.$result);
Here is where I am having trouble.
For the first callback , this request access token process return a Error 500 response which is displayed in my logs as follows :
<HTML>
<HEAD>
<TITLE>Error processing OAuth 2 request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Error processing OAuth 2 request</H1>
<H2>Error 500</H2>
</BODY>
</HTML>
But for all subsequent callbacks, I am getting the proper access token .
What's going wrong for the first time ?
Update I somehow did reset my client-secret , and for a time , I got the proper XML response . But , suddenly , out of the blues ,it has started giving me a new error .
Just after the curl call to get the access_token , it shows me {"error":"invalid_grant"}. Why this is so ?
You will get the invalid_grant error if your $auth_code was already used. Authorization codes can only be used once.
Related
I am trying to create a webpage that implements Step 1 of the "Get a 3-Legged Token with Authorization Code Grant" process described in Autodesk's Forge tutorial. But when I run it I get an error: Error : 400 - Invalid redirect_uri
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Get_a_3-Legged_Token_with_Authorization_Code_Grant.php</title>
</head>
<body>
<?php
// Derivedfrom API tutorial here:
// https://developer.autodesk.com/en/docs/oauth/v2/tutorials/get-3-legged-token/
$client_id = "HAqDtKO7VbuRgH0nL0MFJ0B02ElBEK3l";
$forge_Callback_URL_w_query_string = "http%3A%2F%2prod.sonautics.com/send_scan.php%3Fcmd%3Drefresh";
$forge_Your_WebSite_URL = "httpp%3A%2F%2prod.sonautics.com";
echo '<a href="https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code'
. '&client_id=' . $client_id
. '&redirect_uri=' . forge_Callback_URL_w_query_string
. '&scope=data:read">Click here to grant access to your data!</a>'; ?>
</body>
</html>
I am receiving a page that says:
Oops
Error : 400 - Invalid redirect_uri
We're experiencing problems with the application configuration.
Connecting Application
Please try again later.
My code above is very simple:can you help me identify the source of the error and tell me how to fix it?
The redirect_uri parameter should be matched with the Callback URL like the following snapshot in your Forge app of this client id you mentioned here. Please check if they are mismatched currently.
Besides,
the oath scope for viewing models via Forge Viewer is recommended to use viewables:read instead. The scope data:read can be used to read your model files in your bucket by others once your token with this scope is exposed. Please check this announcement: https://forge.autodesk.com/blog/new-viewablesread-scope
My goal is to manage to use the Google APIs in general, in particular here i need to send emails using Gmail API.
I saved in the DB the 'refresh_token' given to me from Google Server the first time i did the login (using Gmail credentials), and now, as written into the guides, it seems that I have to do a server request (I'm using PHP) to the google server like the following.
[I looked also here:
https://developer.salesforce.com/forums/?id=906F00000008tKWIAY
https://developers.google.com/identity/protocols/OAuth2InstalledApp#formingtheurl
]
My code is the following:
$data = //'grant_type=refresh_token'.
//'&refresh_token='.$refreshtoken; (first option)
'&grant_type=password'.
'&username=mygmail'.
'&password=mypasswordgmail'; (second option)
'&client_id='."xxx".
'&client_secret='."yyy".
$additional_headers = array('Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $additional_headers);
$server_output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $status != 200 )
{
echo 'token_url: '.$token_url."<br>";
echo 'params: '.$data."<br><br>";
echo 'response: '.$server_output."<br>";
die("Error: call to URL $token_url failed with status $status<br>");
}
curl_close($ch);
And what I get as an answer is something like (using password):
response: { "error": "unsupported_grant_type", "error_description": "Invalid grant_type: password" }
Error: call to URL https://www.googleapis.com/oauth2/v4/token failed with status 400
Or (using the refresh_token):
response: { "error": "invalid_grant", "error_description": "Bad Request" }
Error: call to URL https://www.googleapis.com/oauth2/v4/token failed with status 400
I use this in the rest of the code:
$guzzleClient = new \GuzzleHttp\Client(array('curl' => array(CURLOPT_SSL_VERIFYPEER => false, ), ));
$redirectUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$gclient = new Google_Client();
$gclient->setHttpClient($guzzleClient);
$gclient->setAuthConfig('client_secret/client_secret.json');
$gclient->setRedirectUri($redirectUri);
$gclient->setAccessType('offline');
$gclient->setApprovalPrompt('force');
$gclient->addScope("https://mail.google.com/");
$gclient->addScope("https://www.googleapis.com/auth/gmail.compose");
$gclient->addScope("https://www.googleapis.com/auth/gmail.modify");
$gclient->addScope("https://www.googleapis.com/auth/gmail.readonly");
$gclient->addScope('https://www.googleapis.com/auth/userinfo.email');
$gclient->addScope('https://www.googleapis.com/auth/userinfo.profile');
what's wrong??
According to this documentation, requests to the Gmail API must be authorized using OAuth 2.0 credentials. You should use server-side flow when your application needs to access Google APIs on behalf of the user, for example when the user is offline. This approach requires passing a one-time authorization code from your client to your server; this code is used to acquire an access token and refresh tokens for your server.
You may refer with this thread regarding your "Invalid grant_type: password" error. It suggested to specify access_type=offline in your request.
Here's an additional reference which might also help.
I tried to send a bearer token to an Auth0 API using Postman and it works perfectly.
I then tried the same using RestSharp (in c#) but it doesn't work at all.
Below is my code. I've tried many different formats but none of them work.. Is there any other way I can try to make it work?
var client = new RestClient("http://domain.auth0.com/api/v2/users");
RestRequest request = new RestRequest(Method.GET);
//request.AddHeader("authorization", "Bearer eyJhbGcJ9.eyJhdWQiOiJ6VU4hVWUE2.token");
//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Accept", "application/json");
//RestClient client = new RestClient("http://domain.auth0.com");
//RestRequest request = new RestRequest("api/v2/users", Method.GET);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("Authorization",
string.Format("Bearer " + "eyJhbGciOI1NiIsI9.eyJhdWQiOiWmVhTWpD2VycyI6eyJhY.token"),
ParameterType.HttpHeader);
//request.AddParameter("Authorization",
// String.Format("Bearer {0}", token),
//ParameterType.HttpHeader);
var response = client.Execute(request);
PS: the token was changed.
The problem is that you're using an HTTP URL. When you issue the first request the token is included, but you receive a redirect response informing that you should be calling the HTTPS endpoint.
Since RestSharp will not include the token in the second request performed automatically due to the first redirect response you get an unauthorized response.
You need to update the URL to be HTTPS which will prevent the redirect and as a consequence solve your problem. If you want to make multiple authenticated request using the same client you also change your code to be:
using RestSharp;
using RestSharp.Authenticators;
class Program
{
static void Main(string[] args)
{
// Use the HTTPS scheme
var client = new RestClient("https://[domain].auth0.com/api/v2/users");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
"eyJhbGciJIUz.eyJhdWQi4QW5OXhCNTNlNDdjIn0.vnzGPiWA", // Update the token
"Bearer");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine("{0}", response.StatusCode);
}
}
If you really need to handle redirects and still send the token, check: https://github.com/restsharp/RestSharp/issues/414
I am working on a ruby project which involve using RESTClient to reach out to an API. The API returns a 400 HTTP Status Code for a particular result with an accompanying response message (A JSON Response).
But when I check the response of my call:
response = RESTClient.post(...) {
logger.info response.to_s
}
I am getting a Proxy Server 400 page html:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
which is not what I'm expecting.
Please what could be wrong?
Also, the behaviour is different with DEV and TEST Environment. On DEV Environment, it's giving the JSON while on TEST, I'm getting this issue.
Thanks.
If this is your API you can enable response in JSON format to any request. Just add this to your base API controller:
before_filter :default_request_format
private
def default_request_format
request.format = :json
end
If this is not your API you should specify Accept header with JSON content type.
i have following params:
$url = "https://example.com/auth_token.json"
$clientId = "...", $secretId = "..."
$callback = "http://example"
$code = "1234" - # i've received if earlier,
$body = "grant_type=authorization_code&code=$code&redirect_uri=$callback"
My goal is to get token with code, service says :
"Send a POST request to $url, providing the Client ID and Secret Key as HTTP Basic Authorization credentials, and a post body containing grant_type=authorization_code
and get in response json with token."
I tried something like this
curl $url --verbose -d $body -X -POST
but answer is - Status :401, nonauthorized and json "Unauthorized client or authentication failed, check your credentials."
then i tried to add
-H "Authorization : Basic ...encoded value..."
and get "Bad request"
Help me please, i missed something,
thx