Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom authorization header functionality #140

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 31 additions & 8 deletions src/Controllers/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,14 @@ function actionDebug() {

function actionIndex()
{
$token = false;
$settings = CraftQL::getInstance()->getSettings();

$authorization = Craft::$app->request->headers->get('authorization');
preg_match('/^(?:b|B)earer\s+(?<tokenId>.+)/', $authorization, $matches);
$token = Token::findId(@$matches['tokenId']);
$token = static::findToken($settings->authorizationHeader, Craft::$app->request->headers);

// @todo, check user permissions when PRO license

$response = \Craft::$app->getResponse();
if ($allowedOrigins = CraftQL::getInstance()->getSettings()->allowedOrigins) {
if ($allowedOrigins = $settings->allowedOrigins) {
if (is_string($allowedOrigins)) {
$allowedOrigins = [$allowedOrigins];
}
Expand All @@ -65,9 +63,15 @@ function actionIndex()
$response->headers->add('Access-Control-Allow-Origin', $origin);
}
$response->headers->add('Access-Control-Allow-Credentials', 'true');
$response->headers->add('Access-Control-Allow-Headers', 'Authorization, Content-Type');

$allowedHeaders = ['Authorization', 'Content-Type'];
if ($settings->authorizationHeader) {
$allowedHeaders[] = $settings->authorizationHeader;
}

$response->headers->add('Access-Control-Allow-Headers', implode(', ', $allowedHeaders));
}
$response->headers->add('Allow', implode(', ', CraftQL::getInstance()->getSettings()->verbs));
$response->headers->add('Allow', implode(', ', $settings->verbs));

if (\Craft::$app->getRequest()->isOptions) {
return '';
Expand Down Expand Up @@ -120,7 +124,7 @@ function actionIndex()
$result = $this->graphQl->execute($schema, $input, $variables);
Craft::trace('CraftQL: Execution complete');

$customHeaders = CraftQL::getInstance()->getSettings()->headers ?: [];
$customHeaders = $settings->headers ?: [];
foreach ($customHeaders as $key => $value) {
if (is_callable($value)) {
$value = $value($schema, $input, $variables, $result);
Expand Down Expand Up @@ -148,4 +152,23 @@ function actionIndex()

return $this->asJson($result);
}

private static function findToken($authorizationHeader, $headers)
{
// Default, for cases when token header is not found to use user based token
// resolution, if possible.
$tokenId = null;

if ($authorizationHeader) {
if ($headers->has($authorizationHeader)) {
$tokenId = $headers->get($authorizationHeader);
}
} else if ($headers->has('authorization')) {
$authorization = $headers->get('authorization');
preg_match('/^(?:b|B)earer\s+(?<tokenId>.+)/', $authorization, $matches);
$tokenId = @$matches['tokenId'];
}

return Token::findId($tokenId);
}
}
2 changes: 2 additions & 0 deletions src/Controllers/CpController.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ function actionGraphiql()
$this->renderTemplate('craftql/graphiql', [
'url' => "{$url}{$uri}",
'token' => false,
'authorizationHeader' => $instance->settings->authorizationHeader,
]);
}

Expand All @@ -78,6 +79,7 @@ function actionGraphiqlas($token)
$this->renderTemplate('craftql/graphiql', [
'url' => "{$url}{$uri}",
'token' => $token,
'authorizationHeader' => $instance->settings->authorizationHeader,
]);
}
}
7 changes: 6 additions & 1 deletion src/CraftQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,13 @@ protected function createSettingsModel()
*/
protected function settingsHtml()
{
$settings = $this->getSettings();

$curlAuthorizationHeader = $settings->authorizationHeader ? "{$settings->authorizationHeader}:" : 'Authorization: Bearer';

return \Craft::$app->getView()->renderTemplate('craftql/settings', [
'settings' => $this->getSettings()
'settings' => $settings,
'curlAuthorizationHeader' => $curlAuthorizationHeader
]);
}

Expand Down
1 change: 1 addition & 0 deletions src/Models/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

class Settings extends Model
{
public $authorizationHeader = '';
public $uri = 'api';
public $verbs = ['POST'];
public $allowedOrigins = [];
Expand Down
4 changes: 4 additions & 0 deletions src/templates/graphiql.html
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,11 @@
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
{% if authorizationHeader and token %}
'{{ authorizationHeader }}': '{{ token }}',
{% elseif token %}
'Authorization': 'Bearer {{ token }}',
{% endif %}
},
body: JSON.stringify(graphQLParams),
credentials: 'include',
Expand Down
11 changes: 10 additions & 1 deletion src/templates/settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@

2. **Curl**
{% if settings.tokens|length %}<p>You can query your schema directly by passing a GraphQL statement throuh a `query` variable. The following Curl statement should get you started,</p>
<p><pre style="background: whiteSmoke; padding: 15px;"><code class="shell">$ curl -H "Authorization: bearer {{ settings.tokens[0].token|default('{TOKEN}') }}" -H "Content-type: application/json" -d '{"query":"{ helloWorld }"}' {{ siteUrl }}{{ settings.uri }}</code></pre></p>
<p><pre style="background: whiteSmoke; padding: 15px;"><code class="shell">$ curl -H "{{ curlAuthorizationHeader }} {{ settings.tokens[0].token|default('{TOKEN}') }}" -H "Content-type: application/json" -d '{"query":"{ helloWorld }"}' {{ siteUrl }}{{ settings.uri }}</code></pre></p>
{% else %}
<p>Before you can use Curl you need to [add a token]({{ url('craftql/token-gen') }}) for authenticated access in to Craft.</p>
{% endif %}
Expand All @@ -68,6 +68,15 @@
<hr>

<div class="" style="width: 70%">
<h2>Custom Authorization Header</h2>

{{ forms.textField({
first: true,
name: 'authorizationHeader',
value: settings.authorizationHeader,
instructions: 'Custom header to be used to check for authorization token. Useful if site is behind Basic Auth and conflicts with default Authorization Bearer.'
}) }}

<h2>URI</h2>

{{ forms.textField({
Expand Down