c-klinger / MMM-JsonValue

Extension module for the Magic Mirror allows you to show information from any JSON on your mirror using an HTTP Request to an REST API
MIT License
11 stars 5 forks source link

Use headers for authentication tokens #3

Closed jonathanrobichaud4 closed 2 years ago

jonathanrobichaud4 commented 3 years ago

Hey there,

I'm wondering if there's a way to make requests using headers so I can use an api that requires authorization. Am I missing something or is it not possible?

Thanks

c-klinger commented 3 years ago

Hi, i think this would need some code modifications (passing headers from MMM-JsonValues.js to node_helper-js to and use it for the request). I will keep that in mind as an improvement. Might be interessting for more users.

jonathanrobichaud4 commented 2 years ago

I tried to add the headers option myself but am struggling how to get it to work. I consulted the documentation from magic mirror but it didn't help much. Any idea what I did wrong?

c-klinger commented 2 years ago

Hi @jonathanrobichaud4, can u provide me with an example api for testing or check with the branch https://github.com/c-klinger/MMM-JsonValue/tree/improvement/headers if that fits your use case?

Example for config with header on the branch:

{
    module: "MMM-JsonValue",
    position: "top_left",
    config: {
        apiBase: 'https://api.quotable.io/random',
        method: "GET",
        headers: {"Cache-Control": "max-age=0, no-cache, no-store, must-revalidate","Pragma": "no-cache"},
        title: "MM API TEST WITH HEADERS", // Widget Title, set to null if not needed
        icon: "fa-quote-right", // Font Awesome icon, displayed before any text, set to null if not needed
        prefix: "Quote: \"", // Text displayed before the value, can be a blank String ""
        suffix: "\" (from https://api.quotable.io/random)", // Text displayed after the value, can be a blank String ""
        jsonPath: "content", // value in the json to display, the module use https://github.com/dchester/jsonpath for parsing. You don't need leading $. in your path.

        refreshInterval: 1000 * 60, // refresh every minute
        //skipPadding: true, // yo can un-comment this line if you want to display a related value below; using a second instance.
    }
}
jonathanrobichaud4 commented 2 years ago

It's weird. I took to original code and just put the header in to the node_helper file and that worked but trying to use the new branch I'm getting some errors.

Here's my config:

{
            module: "MMM-JsonValue",
            position: "top_left",
            config: {
                apiBase: 'https://example.com/api/states/sensor.temperature',
                method: "GET",
                headers: {'Authorization': 'Bearer authtoken123'},
                title: "",
                icon: "",
                prefix: "",
                suffix: "°", 
                jsonPath: "state",

                refreshInterval: 1000 * 10,
            }
        },

Here's the log error:

0|MagicMirror  | FetchError: invalid json response body at https://example.com/api/states/sensor.temperature reason: Unexpected token : in JSON at position 3
0|MagicMirror  |     at /home/mirror/MagicMirror/node_modules/node-fetch/lib/index.js:272:32
0|MagicMirror  |     at runMicrotasks (<anonymous>)
0|MagicMirror  |     at processTicksAndRejections (internal/process/task_queues.js:95:5) {
0|MagicMirror  |   type: 'invalid-json'
0|MagicMirror  | }
c-klinger commented 2 years ago

I took to original code and just put the header in to the node_helper file and that worked

I also changed the implementation from request to node-fetch yesterday. What do you reference by "original code"? The branch i linked (with node-fetch) or an older main version (with request).

jonathanrobichaud4 commented 2 years ago

By original code I mean the version with request. It seems like the headers aren't being passed through from the config file because my api endpoint (home assistant) is spitting back auth errors.

ZeFX77 commented 2 years ago

Hello i'm getting the same issue, the headers fork. I put the basic authentification inside the header but get an error from the api. any idea how to solve this ? thanks

jonathanrobichaud4 commented 2 years ago

I just ended up hard coding my token into the node_helper.js and it worked for me as a bandaid solution. I did use the older branch though without the headers fix

mattbryce commented 2 years ago

Hi,

I've run into similar issues with the header not passing through to node-fetch. The issue appears to be that fetchOptions isn't being passed into fetch().

Changing to the below in node_helper.js passed the headers through for me.

doCall: function(urlToCall, httpMethod, httpHeaders, callback) {
        var fetchOptions = { method: httpMethod, headers: httpHeaders };
        fetch(urlToCall, fetchOptions)
            .then(res => res.json())
            .then(json => callback(json))
            .catch(error => console.log(error));
    },

My config section is:

{
    module: "MMM-JsonValue",
    position: "left",
    config: {
        apiBase: "{url}",
        method: "GET",
        headers: {'Authorization': 'Bearer {token}'},
        title: "{Title}", // Widget Title, set to null if not needed
        icon: "", // Font Awesome icon, displayed before any text, set to null if not needed
        prefix: "", // Text displayed before the value, can be a blank String ""
        suffix: "", // Text displayed after the value, can be a blank String ""
        jsonPath: "{value}",
        refreshInterval: 1000 * 90,
        }
},

Thanks

jonathanrobichaud4 commented 2 years ago

Yes thank you this worked for me!

c-klinger commented 2 years ago

Thank you @mattbryce!