Start a new topic

OAuth2 Authorization in Javascript

Hi guys,

I got my LaMetric today and I am trying to follow the OAuth2 tutorial to get my developer API key in order to be able to push notifications locally to the device.

I created a notification app and set its redirect URL to "https://mydomain.com/dev/lametric/auth.html".

The auth.html file looks as follows:
<html>
    <head><title>LaMetric Auth</title></head>
    <body>
        <script>
            var client_id = '22222222-2222-22aa-a22a-222a2aa222a2';
            var client_secret = 'BBBbBbBbb2BbBbBbBBb2BbBBBBBVbV2bBBbbBbbbbBBBb==';
            var grant_type = 'authorization_code';
            var redirect_uri = 'https://mydomain.com/dev/lametric/auth.html';

            var hash = window.location.hash.replace('#', '');
            if (hash === '') {
                // first call
                window.document.location = 'https://developer.lametric.com/api/v2/oauth2/authorize/?client_id=' + client_id + '&response_type=token&scope=basic+devices_read+devices_write';
            }
            else {
                // returning from oauth2
                var hashParts = hash.split('&');
                var code = hashParts[0].split('=')[1];
                var params = 'client_id=' + client_id +
                     '&client_secret=' + client_secret +
                     '&grant_type=' + grant_type +
                     '&redirect_uri=' + redirect_uri +
                     '&code=' + code;
                console.log('params', params);

                xhr = new XMLHttpRequest();
                xhr.open('POST', 'https://developer.lametric.com/api/v2/oauth2/token');
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onload = function() {
                    console.log('xhr', xhr);
                    console.log('status', xhr.status);
                    console.log('response', JSON.parse(xhr.response));
                };
                xhr.send(encodeURI(params));
            }
        </script>
    </body>
</html>

Calling https://mydomain.com/dev/lametric/auth.html in browser redirects me to the according Authorization page where I "allow" access.


On the redirected page the POST request to https://developer.lametric.com/api/v2/oauth2/token always returns a 400 Bad Request response with the message

{error: "invalid_grant", error_description: "Authorization code doesn't exist or is invalid for the client"}

Google returns a lot of results on that error but I could not make much sense of any of it.


Any help is appreciated!



Julian



1 Comment

If you are only trying to get your API key, you can now do so directly from the developer portal in your web browser. If you click on your Account in the top right corner then go to "My Devices" you will see all of your LaMetric devices along with their respective API keys.


Hope this helps.

Login or Signup to post a comment