markhuot / craftql

A drop-in GraphQL server for Craft CMS
Other
319 stars 53 forks source link

Error: message: Not authorized using default curl command #158

Open swthate opened 5 years ago

swthate commented 5 years ago

This is similar to issue #56

Craft CMS: 3.0.24 CraftQL: 1.1.0 PHP: 7.1.1

This is on a local project running on MAMP Pro. My PHP is set to CGI mode. As far as I can tell it's not in Fast CGI mode (i.e. fastcgi.impersonate = 1; is commented-out).

I have been working on trying to get a basic Vue component to communicate with CraftQL via Axios. The javascript I wrote has nothing to do with this, I think, but here's what I have in case any helpful soul notices any blatant errors in that, too!

// Information needed for connecting to CraftQL endpoint
const token = 'F--ybXjDAsXd7sqlKd-hudg6VedYh2fjyzyGbUEtl2zlLxO1DAaSfkxQ4WBPiL10';
const url = 'http://dstnew.test/api';

// GraphQL query
const query = `
    {
        query businesses(section:[businesses], limit:1) {
            ...on Businesses {
                id
                title
                bizTown {
                    title
                }
            }
        }
    }
`;

const axiosCraftQL = axios.create({
    baseURL: 'http://dstnew.test/api',
    headers: {
        'Authorization': `Bearer: ${token}`,
        'X-Requested-With': 'XMLHttpRequest'
    }
});

new Vue({
    el: '#app',
    delimiters: [ '${', '}' ],
    data: {
        businesses: {}
    },
    mounted() {
        axiosCraftQL
            .get('', { query: query })
            .then(console.log(result));
    }
});

I first noticed something odd when my javascript console returned the following:

spread.js:25 GET http://dstnew.test/api 404 (Not Found)

Then I tried running the sample Curl statement from the plugin settings page. I tried it with a lowercase Authorization and ensured the url in the command and in my site's settings match. The command returns the following:

{"errors":[{"message":"Not authorized"}]}

Thanks!

markhuot commented 5 years ago

Try removing the : from your authorization header. It should be,

'Authorization': `Bearer ${token}`,
swthate commented 5 years ago

Darn, I was hoping it would be that simple. After removing the : the problem persists. And the sample curl command returns that {"errors":[{"message":"Not authorized"}]} message, and it has the correct "Authorization: bearer F--ybX..." syntax.

Update: I also tried updating the URI from api to graphql just to see if that would "refresh" anything. Same error results.

markhuot commented 5 years ago

In your MAMP settings under the host you need to go to the Apache tab and explicitly enable header based authorization with the following <Directory> directive,

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

My config looks like this,

screen shot 2018-09-19 at 10 34 58 am

swthate commented 5 years ago

Hmm, I'm not sure what I have going on. After adding that line to the <Directory> directive like you showed I was getting the same errors. So I spun up an entirely new Craft install, installed CraftQL, made that <Directory> directive change you showed again, and I'm getting the same error message from the sample Curl statement.

I'm running MAMP PRO 4.1.1. Should I update this, or do you think the issue is elsewhere? I've been hesitant to update MAMP because the last time was such a pain. Not a good reason to avoid updates, I know...

markhuot commented 5 years ago

If you're not afraid of a little tinkering you could open up vendor/markhuot/craftql/src/Controllers/ApiController.php and then around line 54 update the $token = bit by adding the following three lines below,

$token = Token::findId(@$matches['tokenId']);
var_dump($matches);
var_dump($token);
die;

Then, if you curl again you should get some debugging info that'll tell us if PHP is getting the authorization header.

swthate commented 5 years ago

Sorry for the delay. Here's what I get from that:

<pre class='xdebug-var-dump' dir='ltr'>
<small>/Users/Steven/Code/craft_test/vendor/markhuot/craftql/src/Controllers/ApiController.php:55:</small>
<b>array</b> <i>(size=0)</i>
  <i><font color='#888a85'>empty</font></i>
</pre><pre class='xdebug-var-dump' dir='ltr'>
<small>/Users/Steven/Code/craft_test/vendor/markhuot/craftql/src/Controllers/ApiController.php:56:</small>
<small>boolean</small> <font color='#75507b'>false</font>
markhuot commented 5 years ago

Thanks, that's helpful. Looks like something between your request and PHP isn't sending the authorization: header through. This definitely feels like the MAMP issue,

https://github.com/yiisoft/yii2/issues/6631

But you've made the change you're supposed to make. You could try adding the line to .htaccess and see if that helps. Maybe MAMP 4 handles it a little differently than MAMP 5…?

swthate commented 5 years ago

Editing .htaccess itself (the only one in web/ right?) didn't have any effect, ugh! Here is what my .htaccess looks like after the edit:

<IfModule mod_rewrite.c>
    SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

    RewriteEngine On
    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

I'll do a Time Machine backup and try updating MAMP tomorrow.

markhuot commented 5 years ago

Yea, you've got what you should have there for getting the authorization header through. I'm sorry I don't have much else to offer. Let me know how the MAMP update goes and if there's anything else I can do to help.

magicspon commented 5 years ago

@swthate did you have any joy updating Mamp?

I also have the same issue when running crafql locally, works perfectly well on a digital ocean droplet.

swthate commented 5 years ago

@markhuot I updated MAMP today, but am having the same issue.

@magicspon I haven't attempted any of this on a staging or live server. That is interesting.

magicspon commented 5 years ago

@swthate yeah, t'is very odd... my colleagues have had no issues running it locally (mamp and/or homestead), just me and my laptop, and weirdly my work machine.... it makes me think, did i google a previous unrelated bug, ran a command, and had some knock on effect to apache, no idea!.. but yup, works perfectly well on digital ocean!

swthate commented 5 years ago

@magicspon even Homestead does it for you locally? I was thinking of trying to spin one of those up today to test. I suppose I still could. Since I have such a recent Time Machine backup, I might try formatting and putting on a fresh macOS install. Start everything from scratch. I'll keep you posted if I do that.

swthate commented 5 years ago

@markhuot and @magicspon :

I just finished upgrading to Mojave. I also upgraded from MAMP PRO 4.x to 5.x.

I wish I knew what changed or fixed it... but the sample curl statement now successfully returns the helloWorld object! Now it's on to the nitty-gritty of actually learning Vue and GraphQL!

Jones-S commented 4 years ago

I have the same problem. It works if I authenticate from a remote server, but on localhost it keeps throwing «Not authorized». I have Mojave, Mamp Pro 5.4, I have added SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0 to web/.htaccess and added it within the MAMP Settings:

image

Nothing helped... Anything else I could try?

$ curl -H "Authorization: bearer xxTokenxx" -H "Content-type: application/json" -d '{"query":"{ helloWorld }"}' http://mylocalcraft.test/api

@markhuot I also tried adding this

        $token = Token::findId(@$matches['tokenId']);
        var_dump($matches);
        var_dump($token);
        die;

to the controller and the terminal would give me back this:

curl -X POST -H "Content-Type: application/json" -H "authorization: Bearer xxx" --data '{"query":"{helloWorld}' \ http://mylocalcraft.test/api

array(0) { } bool(false)

What does that tell me?

Jones-S commented 4 years ago

Ok I found a way: That's what did the trick for me:

image image
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

Found from here: https://support.deskpro.com/en/kb/articles/missing-authorization-headers-with-apache

I tried to omit the Parameter in the < Directory > and it still worked...

rhoffmann commented 4 years ago

I also ran into this issue and tried a lot of the above ideas. On our production Server the bearer in the auth header has to be capitalized as Bearer.

jan-dh commented 4 years ago

Same here, no idea why this was closed.

swthate commented 4 years ago

@jan-dh I closed it because my issue was at least resolved, though perhaps not solved nearly a year ago. It looks like there's quite a bit of activity back on this issue. I have not been using CraftQL myself for quite some time now, so I unfortunately have no wisdom for any of you to glean from, lol. But I think I have the power to reopen the ticket.

jan-dh commented 4 years ago

Was testing out some things and the @Jones-S answers did work for me. 🎉

swthate commented 4 years ago

I will leave it to the powers that be to deem this issue close-worthy or not 😆

Glad you got it working!