Desire2Learn Valence API | JSON not loading - desire2learn

I'm using the Python Requests library with the Valence-provided Python SDK to attempt to do a GET request. Something odd is happening with the URL and I'm not sure what. The response I get is 200 (which leads me to believe that the authentication is working), but when I try to print the JSON from the Request object, it instead prints the HTML of the page instead of the JSON.
I'm using modified code that I read from http://docs.valence.desire2learn.com/clients/python/auth.html.
Here's the Python code:
import requests
import auth as d2lauth
from auth import *
app_creds = { 'app_id': '----', 'app_key': '----' }
ac = d2lauth.fashion_app_context(app_id=app_creds['app_id'], app_key=app_creds['app_key'])
auth_url = ac.create_url_for_authentication('ugatest2.view.usg.edu', 'http://localhost:8080')
redirect_url = "https://localhost:8080?x_a=3----&x_b=3dMRgCBAHXJDTA2E6DJIfdWq-gYl-pk77fF_3X5oDUuqc"
uc = ac.create_user_context(auth_url, 'ugatest2.view.usg.edu', True)
route = 'ugatest2.view.usg.edu/d2l/api/versions/'
url = uc.create_authenticated_url(route)
r = requests.get(url)
print(r.text)
The output is the HTML of a page instead of JSON. If I do print(r), I get a status of 200. I think my redirect URL may be the issue, but I'm not sure what exactly is wrong. Thanks for any help!

Two things look off to me:
Using auth_url to create a user context isn't going to work, that's the URL you need to send the user to so they can authenticate. You need to use the URL you were redirected to after authenticating to build the user context. Assuming redirect_url is that URL, you should be passing that to create_user_context and not auth_url.
ugatest2.view.usg.edu/d2l/api/versions/ is not a valid value for passing to create_authenticated_route, /d2l/api/versions is probably what you want. The SDK will prepend the scheme, domain, and port so including those in the value passed is going to result in an incorrect URI.

Once your app is working properly, you'll be able to access a JSON response by using r.json() rather than r.text.

Related

BigCommerce oAuth auth token request always returning 401

I can not figure out what I'm doing wrong. I'm developing an App for BigCommerce and can not get the simple oAuth exchange to work correctly.
The initial get request is being made to https://www.my-app.com/oauth/bigcommerce/auth. This is the code in the controller for that request. It's a Laravel 5.6 app:
use Illuminate\Http\Request;
use Bigcommerce\Api\Client as Bigcommerce;
class BigcommerceOAuthController extends Controller
{
public function auth(Request $request)
{
$object = new \stdClass();
$object->client_id = 'my-client-id';
$object->client_secret = 'my-client-secret';
$object->redirect_uri = 'https://my-app.com/oauth/bigcommerce/auth';
$object->code = $request->get('code');
$object->context = $request->get('context');
$object->scope = $request->get('scope');
$authTokenResponse = Bigcommerce::getAuthToken($object);
$storeHash = str_replace('stores/', '', $request->get('context'));
Bigcommerce::configure(array(
'client_id' => 'my-client-id',
'auth_token' => $authTokenResponse->access_token,
'store_hash' => $storeHash
));
echo "<pre>";
print_r($authTokenResponse);
print_r(Bigcommerce::getTime());
echo "</pre>";
}
}
Every time I try to install my draft app from the BigCommerce control panel, I get an error because $authTokenResponse is not an object. When I debug further into the Bigcommerce\Api\Connection class, I can see that the response from the server is empty, and the status is a 401, which means "Unauthorized".
I can't figure out why I am getting this error. As far as I can see, I'm doing everything right. I've tried urlencoding the string retrieved from $request->get('scope'), since that string becomes unencoded by Laravel, but that didn't seem to help.
I am also confused how this is even supposed to work at all. In the BigCommerce docs, they show this example POST request, which uses application/x-www-form-urlencoded Content-Type and passes the request body as a url encoded string:
POST /oauth2/token HTTP/1.1 Host: login.bigcommerce.com Content-Type:
application/x-www-form-urlencoded Content-Length: 186
client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&code=qr6h3thvbvag2ffq&scope=store_v2_orders&grant_type=authorization_code&redirect_uri=https://app.example.com/oauth&context=stores/{STORE_HASH}
However, if you inspect what's going on in the Connection class, you can see that the Content-Type is being set to application/x-www-form-urlencoded as the docs say, but the request body is being passed in as a json string, not a url string. Shouldn't the request be a url encoded string as the docs suggest?
A couple of things here to check:
Do you have a public URL where you can receive the Auth Callback?
If so, did the store owner registered the app successfully? https://developer.bigcommerce.com/api/registration
When you have the client_id and secret_id. You should have all of the details needed to send a POST request to the BC Auth Token Service at https://login.bigcommerce.com/oauth2/token
The content uses URL encode Make sure to URL encode your content. Be careful of of the encoding of & and = signs when those are actually being used as separators.
More details can be found in this post:
Can BigCommerce Private Apps use OAuth

Coinbase Oauth2 - token request URL - "404 Not found"

First steps of the Coinbase Oauth Authorization seem to work fine.
I request the customer code via the following URL:
"https://www.coinbase.com/oauth/authorize?response_type=code&client_id=XXXXXXXXXXXXXXXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=user+balance"
I get back the code via URL..
Then trying to request the token with given CODE and CLIENT SECRET and CLIENT ID:
"https://api.coinbase.com/oauth/token&grant_type=authorization_code&code=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=XXXXXXX&client_secret=XXXXXXX"
With that I get an "404 Not found" Error..
Is there any obvious mistake in the URL.. or is it most likely an issue with the
Code or Secret etc. itself?
If Yes.. anything important to know there?
All that was followed from the description:
https://developers.coinbase.com/docs/wallet/authentication
Thank you so much for help!
The URL that you pasted:
https://api.coinbase.com/oauth/token&grant_type=authorization_code&code=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=XXXXXXX&client_secret=XXXXXXX
does not contain a query component since there's no ? character in there. You should rather use:
https://api.coinbase.com/oauth/token?grant_type=authorization_code&code=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=XXXXXXX&client_secret=XXXXXXX
and it looks like the documentation that you point to is the source of that error.
Moreover, the OAuth 2.0 spec says to use POST to the token endpoint, which is also stated in the docs but not clearly demonstrated in the sample. So you should send the parameters as form-encoded values an HTTP POST, e.g. the equivalent of the following cURL request:
curl -d "grant_type=authorization_code&code=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=XXXXXXX&client_secret=XXXXXXX" https://api.coinbase.com/oauth/token
Requesting it as a POST BODY did the job!
Although important changes:
- Redirect uri needs to be a proper external domain, uri for mobile apps will create a 401 Error..
-Encoding in ascii
import urllib
import urllib.request
import urllib.parse
data = urllib.parse.urlencode({'grant_type':'authorization_code', 'code': 'XXXXXX',
'redirect_uri': 'https://XXXXXX', 'client_id': 'XXXXXXXXXXX',
'client_secret' : 'XXXXXXXXXXX'})
binary_data = data.encode('ascii')
try:
response = urllib.request.urlopen('https://api.coinbase.com/oauth/token', data=binary_data)
print(response.status)
print(response.read())
except urllib.error.HTTPError as e:
print('%s %s' %(e.code, e.reason))
Got the rough structure from:
https://docs.python.org/3/library/urllib.request.html
Thanks a lot for the fast help!

Google docs API: can't download a file, downloading documents works

I'm trying out http requests to download a pdf file from google docs using google document list API and OAuth 1.0. I'm not using any external api for oauth or google docs.
Following the documentation, I obtained download URL for the pdf which works fine when placed in a browser.
According to documentation I should send a request that looks like this:
GET https://doc-04-20-docs.googleusercontent.com/docs/secure/m7an0emtau/WJm12345/YzI2Y2ExYWVm?h=16655626&e=download&gd=true
However, the download URL has something funny going on with the paremeters, it looks like this:
https://doc-00-00-docs.googleusercontent.com/docs/securesc/5ud8e...tMzQ?h=15287211447292764666&amp\;e=download&amp\;gd=true
(in the url '&amp\;' is actually without '\' but I put it here in the post to avoid escaping it as '&').
So what is the case here; do I have 3 parameters h,e,gd or do I have one parameter h with value 15287211447292764666&ae=download&gd=true, or maybe I have the following 3 param-value pairs: h = 15287211447292764666, amp;e = download, amp;gd = true (which I think is the case and it seems like a bug)?
In order to form a proper http request I need to know exectly what are the parameters names and values, however the download URL I have is confusing. Moreover, if the params names are h,amp;e and amp;gd, is the request containing those params valid for obtaining file content (if not it seems like a bug).
I didn't have problems downloading and uploading documents (msword docs) and my scope for downloading a file is correct.
I experimented with different requests a lot. When I treat the 3 parameters (h,e,gd) separetaly I get Unauthorized 401. If I assume that I have only one parameter - h with value 15287211447292764666&ae=download&gd=true I get 500 Internal Server Error (google api states: 'An unexpected error has occurred in the API.','If the problem persists, please post in the forum.').
If I don't put any paremeters at all or I put 3 parameters -h,amp;e,amp;gd, I get 302 Found. I tried following the redirections sending more requests but I still couldn't get the actual pdf content. I also experimented in OAuth Playground and it seems it's not working as it's supposed to neither. Sending get request in OAuth with the download URL responds with 302 Found instead of responding with the PDF content.
What is going on here? How can I obtain the pdf content in a response? Please help.
I have experimented same issue with oAuth2 (error 401).
Solved by inserting the oAuth2 token in request header and not in URL.
I have replaced &access_token=<token> in the URL by setRequestHeader("Authorization", "Bearer <token>" )

Retrieving the url anchor in a werkzeug request

I have a DAV protocol that stores out-of-band data in the url anchor, e.g. the ghi in DELETE /abc.def#ghi. The server is a Flask application.
I can see the request come in on the wire via tcpdump, but when I look at the werkzeug Request object (such as url() or base_url()), all I get back is /abc.def. The #ghi has been stripped out.
Is there a method that returns this information, or do I have to subclass Request to handle this myself? If so, is there an example I can use as an inspiration?
I ran into the same problem. Facebook authentication API returns the access token behind a hash appended into the redirection url. In the same way, Flask's request.url drops everything in the URL behind the hash sign.
I'm also using Flask so I think you can use my brute-force workaround using Javascript's window.location.href to get the full URL. Then, I just extracted the piece that I needed (the access token), put it into a redirection URL where I can pass the access token as an argument to the receiving view function. Here's the code:
#app.route('/app_response/<response>', methods=['GET'])
def app_response_code(response):
return ''' <script type="text/javascript">
var token = window.location.href.split("access_token=")[1];
window.location = "/app_response_token/" + token;
</script> '''
#app.route('/app_response_token/<token>/', methods=['GET'])
def app_response_token(token):
return token
In case you manage(d) to do this within Werkzeug, I'm interested to know how.
From Wikipedia (Fragment Identifier) (don't have the time to find it in the RFC):
The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the server
So Flask - or any other framework - doesn't have access to #ghi.
You can do this using flask.url_for with the _anchor keyword argument:
url_for('abc.def', _anchor='ghi')

Google Calendar Data API Integration

We're using Oauth to grab Calendar event data. I have successfully authorized the token and exchange it for an access token. When I perform a get request to the API endpoint I get a page that says "Moved Temporarily" with a link to something like https://www.google.com/calendar/feeds/default?gsessionid=xxxxxxxxxxxx
I'd like to interpret the response, whether it's json or xml but I can't get beyond the redirect it's throwing out. Any idea how to follow this?
Here's my call to the feed:
access_token = current_user.google.client
response = access_token.get(ConsumerToken::GOOGLE_URL).body
Yep, just dealt with this myself. It says "Moved Temporarily" because it's a redirect, which the oauth gem unfortunately doesn't follow automatically. You can do something like this:
calendar_response = client.get "http://www.google.com/calendar/feeds/default"
if calendar_response.kind_of? Net::HTTPFound # a.k.a. 302 redirect
calendar_response = client.get(calendar_response['location'])
end
This might be worthy of a patch to oauth...

Resources