Makes WP GraphQL's authetication "just work". It does this by customizing the CORS headers.

Overview

WP GraphQL CORS

The primary purpose of this plugin is to make the WP GraphQL plugin authentication "just work". It does this by allowing you set the CORS headers that GraphQL will accept, which means that WordPress's default authentication cookies will be accepted.

This means that if a user is logged into WordPress, they will be able to see things like draft and private pages/posts via GraphQL.

Features

  • Allows WP-GraphQL to accept default WordPress cookies
  • Works across multiple domains (so you can have multiple frontends connected to one backend)
  • Allows you to filter out specific cookies for added security (perhaps you don't want to use this for WordPress authentication but do want to access other cookies)
  • Allows you to customize the GraphQL endpoint
  • Extends WP GraphQL to have a logout and login mutation
  • Allows you to filter out which cookies are allowed

Installation

  1. Requires WP GraphQL.
  2. Upload this plugin to WordPress.
  3. Config your GraphQL client (probably Apollo) to include credentials in requests. Generally this is a setting under httpLinkOptions and look to set credentials = "include".

Now if the browser is currently logged into WordPress, WP GraphQL will allow access to authenticated data.

Documentation

If all you want to do is allow draft, private and page previews to be viewed from the frontend, setting Send site credentials. and Add Site Address to "Access-Control-Allow-Origin" header to true will do this.

You'll also need to config your GraphQL client (probably Apollo) to include credentials in requests. Generally this is a setting under httpLinkOptions and look to set credentials = "include".

Logout Mutation

If enabled in the settings, WP GraphQL will have a new mutation available to allow a user to logout. This is useful if you want to build a "logout" button on a sites frontend.

mutation {
    logout(clientMutationId = "anything unique"){
        clientMutationId
        status
    }
}

Login Mutation

If enabled in the settings, WP GraphQL will have a new mutation available to allow a user to login.

mutation {
	loginWithCookies(input: {clientMutationId: "", login: "", password: ""}) {
        clientMutationId
        status
    }
}
Comments
  • Login does not work with Chrome (cookies not set/blocked)

    Login does not work with Chrome (cookies not set/blocked)

    Hey @kidunot89 @drewbaker. The login isn't working for me on Chrome.

    Here's the error message Chrome is logging:

    Because a cookie's SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being set in a cross-site context. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery. Resolve this issue by updating the attributes of the cookie: Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts. Note that only cookies sent over HTTPS may use the Secure attribute. Specify SameSite=Strict or SameSite=Lax if the cookie should not be set by cross-site requests

    image

    Steps to reproduce:

    In Chrome 85, run the following query:

    mutation {
      loginWithCoookies(clientMutationId: "123" login: "mycoolusername" password: "mycoolpassword") {
        status
        __typename
      }
    }
    

    Then run a subsequent authenticated query

    query Me {
      viewer {
        email
        nicename
        __typename
      }
    }
    

    Expected results:

    1. successful login
    {"data":{"loginWithCookies":{"status":"SUCCESS","__typename":"LoginWithCookiesPayload"}}}
    
    1. WordPress logged in cookie set (and sent along with subsequent requests)
    2. authenticated queries are successful
    {"data":{"viewer":{"email":"[email protected]","nicename":"jacob","__typename":"User"}}}
    

    Actual results:

    1. login is successful
    2. cookie was not set and not part of headers on subsequent request
    3. authenticated request returns null
    {"data":{"viewer":null}}
    

    Related to #16

    opened by jacobarriola 9
  • Authorized domains list not working ( next.js app )

    Authorized domains list not working ( next.js app )

    I'm developing a next.js app with WP backend locally and I have faced the following issue -

    1. after activating the plugin next.js build returns an error as expected - it cannot fetch data via GraphQl
    2. a have added http://localhost:3000/ and http://localhost to the authorized domains list -> next.js still can't fetch data - that is unexpected behaviour
    opened by vstrelianyi 8
  • Still get cors issues after using WP Graphql Cors

    Still get cors issues after using WP Graphql Cors

    Hi, We are using WP Graphql and Apollo to fetch data from WordPress in our Next.js codebase. Recently we've tried using your plugin WP Graphql Cors in order to try to get rid of some cors issues we experienced on some queries.

    However it does not seem to work even though we enter the origins we want to allow in WP admin and the "credentials": "inlcude" settings in ApolloClient. We've tried changing to run graphql queries with ApolloServer which resolves the issue, but that adds a lot of extra work and complexitiy for us in other ways that we would prefer to avoid. One of the wpgraphql mutations that fails due to cors is addToCart.

    The console error is "... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." We tried to use the no-cors option but that gives us further errors and is not a secure solution. We also tried adding cors settings in the htaccess file in WP codebase, but that throws us more fetch errors.

    Would kindly appreciate all the help and guidance we can get on this.

    opened by gabriel-nack 7
  • How to install

    How to install

    Hi , I dont understand how to install this plug in, it mentions to make sure WPGraphql is installed. But where do I get the plug in and where do I put it ?

    opened by ebisLab 7
  • Internal server error on login mutation

    Internal server error on login mutation

    try

    mutation MyMutation($login: String!, $password: String!) { login(input: {clientMutationId: "", login: $login, password: $password}) { status } }

    get

    { "errors": [ { "message": "Internal server error", "category": "internal", "locations": [ { "line": 2, "column": 3 } ], "path": [ "login" ] } ], "data": { "login": null } }

    opened by vana-dev 4
  • Unable to activate plugin : Trailing comma cause fatal error

    Unable to activate plugin : Trailing comma cause fatal error

    Installing this plugin release 2.0 cause fatal error when activated in Wordpress because of this comma : image

    In file : \wp-content\plugins\wp-graphql-cors-2.0\includes\admin\admin.php

    opened by vdilly 3
  • registerUser mutation and secure cookies

    registerUser mutation and secure cookies

    The default behaviour of the registerUser mutation from wp-graphql includes setting the current user to the one that was just successfully registered, as seen here.

    However, when using this in conjunction with wp-graphql-cors, we cannot set the response cookie because the default registerUser mutation doesn't set a secure cookie.

    Here's an example of some response headers from a registerUser mutation: image

    The yellow warning message next to each set-cookie response header reads:

    This Set-Cookie didn't specify a "SameSite" attribute and was default to "SameSite=Lax", and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The Set-Cookie had to have been set with "SameSite=None" to enable cross-site usage.

    Hoping to have a discussion on what a potential solution would be, such as:

    1. Create a registerWithCookies mutation similar to loginWithCookies?
    2. Implement something on the Wordpress End?
    3. Something else?

    Note: Also an edge case, but wp-graphql-woocommerce has the ability to register users using the checkout mutation as well. This presents the same issue as the registerUser mutation.

    opened by ardiewen 3
  • Adding Access Control Allow Header custom field & logic to implement …

    Adding Access Control Allow Header custom field & logic to implement …

    This will allow a user to add it's own custom fields into headers and that way prevent any cors issues with custom fields being sent along the request

    image

    EDIT: Reason behind this PR was that we have an apollo client that sends a custom parameter in headers when it reaches out to multiple services. In order to reduce amount of complexity on the client side we've thought it might benefit others to be able to add custom fields to headers within their projects.

    Please do point out if any of the updates don't make sense or require some more info etc.

    opened by tsvecak 3
  • 🐛 Add missing undefinded variable input

    🐛 Add missing undefinded variable input

    When running the loginWithCookies mutation, the server errors out and doesn't return an expected value. Looking at my Sentry report, it looks as though there's a missing variable.

    Specifically, the mutateAndGetPayload is missing the $input variable in its callback function. As a result, the subsequent foreach is throwing an ErrorException for an invalid argument.

    Sentry report: https://sentry.io/share/issue/bb2aaa28f07a4c48bc917ee51a9f05b8/

    opened by jacobarriola 2
  • Login Mutation ends in internal server error

    Login Mutation ends in internal server error

    When I activate the login mutation and query like so:

    mutation LoginUser($input: LoginInput!) {
      login(input: $input) {
        status
      }
    }
    

    I end up getting an internal server error:

    {
      "error": {
        "errors": [
          {
            "debugMessage": "You cannot register duplicate fields on the same Type. The field 'login' already exists on the type 'rootMutation'. Make sure to give the field a unique name.",
            "message": "Internal server error",
            "category": "internal"
          }
        ]
      }
    }
    

    There already is a login mutation from WPGraphQL, so this is a bit confusing.

    Also when I set credentials: 'include' it works if I set the allowed Domains to my localhost, but it doesn't set any Cookies.

    opened by henrikwirth 2
  • Getting Apollo error on SSR for CORS requests

    Getting Apollo error on SSR for CORS requests

    I don't have much data for this as it's hard to debug, but when making a request to WP-GQL for data that would require a cookie, I get a server side error, but then the data does display client side.

    Screen Shot 2019-12-06 at 3 23 17 PM

    opened by drewbaker 2
  • CORS policy + apollo client

    CORS policy + apollo client

    CORS policy + GraphQL + apollo client

    I'm getting an error of CORS policy when using preflight request. The authorization headers are only being returned in preflight, but not in the standard request, causing the error.

    I've been testing and my conclusion is that:

    1. I tried to add fetchOptions: { mode: 'no-cors' } to the Apollo client, but it doesn't allow the fetchPolicy to be no-cors when making a 'POST' request, so preflight will always be sent in this case. Unavoidable.
    2. The WP GraphQL plugin checks if the headers have already been sent and since they have already been sent to preflight, they are not resent in the official request. When receiving the response from the second request, the headers are not present, causing an error.

    It happens because of "headers_sent" function that makes the "prepare_headers" function to be ignored.
    File: wp-graphql/src/Router.php::506

    My temporary solution: I had to force the two headers to be sent in the standard request. Always.

    function add_cors_http_header() {
    	$http_origin = $_SERVER['HTTP_ORIGIN'];
    
    	if ( $http_origin && ( $http_origin == "https://domain1.com" || $http_origin == "https://domain2.com" ) )
    	{  
    		header("Access-Control-Allow-Origin: $http_origin");
    		header( 'Access-Control-Allow-Credentials: true' );
    	}
    }
    add_action( 'graphql_process_http_request', 'add_cors_http_header' );
    
    opened by victormattosvm 4
  • Block unauthorized domains not working

    Block unauthorized domains not working

    Hi, I am trying to block unauthorized domains so only specific domain will have the option to fetch data. I tried several configurations options but none of them got me the right result - but I still succeed to fetch data via Postman. I only want to block unauthorized domains without the need of user authentication.

    What am I doing wrong? Thanks!

    image

    opened by dandin84 2
Releases(2.1)
Owner
Funkhaus
The creative's creative agency. Technical Director and co-founder @drewbaker.
Funkhaus
Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application

CORS Middleware for Laravel Implements https://github.com/asm89/stack-cors for Laravel About The laravel-cors package allows you to send Cross-Origin

Fruitcake 6.2k Jan 8, 2023
A Magento 2 module that enables configurable CORS Headers on the GraphQL and REST APIs

Magento 2 CORS Magento Version Support Ever try to work with the Magento GraphQL API or REST API from your browser and see the following? Access to XM

Graycore, LLC 62 Dec 8, 2022
A library that makes the management of WordPress file headers easier.

Pronamic WordPress File Header Many WordPress plugins contain bash scripts with sed and awk commands to update WordPress file headers. Because sed and

Pronamic 3 Oct 6, 2022
Termage provides a fluent and incredibly powerful object-oriented interface for customizing CLI output text color, background, formatting, theming and more.

Termage provides a fluent and incredibly powerful object-oriented interface for customizing CLI output text color, background, formatting, theming and

TERMAGE 75 Dec 20, 2022
Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework.

Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework. This rep

LaraBug 197 Dec 9, 2022
Feel free to create new file, don't hesitate to pull your code, the most important thing is that the file name here must match your nickname so that file does not conflict with other people.

PHP-Projects hacktoberfest Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to cha

Firmansyah Helmi Kurniawan 43 Nov 28, 2022
Fearless refactoring, it does a lot of smart checks to find certain errors.

Find Bugs Before They Bite Built with ❤️ for lazy laravel developers ;) Why repeat the old errors, if there are so many new errors to commit. (Bertran

Iman 1.2k Dec 29, 2022
The HabboCMS that does the heavy lifting.

shadeCMS The HabboCMS that does the heavy lifting. Installation You first need some information on what you need to install and configurate. 1. MySQL

Zenithican 1 Jul 11, 2022
This Plugin runs commands when a player does a certain emote

The EmoteCommands Plugin This Plugin runs commands when a player does a certain emote You will need a pocketmine server of at least version 4.0.0 Usag

DiamondStrider1 1 Jan 24, 2022
This application (class) does the sending of emails used in the phpmailer library

emailsender - PHP Notification library via email using phpMailer This library has the function of sending email using the phpmailer library. Doing thi

Lucas Alcantara Rodrigues Volpati 1 Feb 9, 2022
Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Motto: "Every business should have a detection script to detect mobile readers." About Mobile Detect is a lightweight PHP class for detecting mobile d

Şerban Ghiţă 10.2k Jan 4, 2023
PHP Secure Headers

Secure Headers Add security related headers to HTTP response. The package includes Service Providers for easy Laravel integration. Version Installatio

null 431 Dec 26, 2022
PHP Exif Library - library for reading and writing Exif headers in JPEG and TIFF files using PHP.

PEL: PHP Exif Library README file for PEL: PHP Exif Library. A library with support for reading and writing Exif headers in JPEG and TIFF images using

null 264 Dec 4, 2022
PHP Secure Headers

Secure Headers Add security related headers to HTTP response. The package includes Service Providers for easy Laravel integration. Version Installatio

null 431 Dec 26, 2022
Harden request headers, login interface and passwords to increase backend security.

JvMTECH.NeosHardening Package for Neos CMS Harden request headers, login interface and passwords to increase backend security. Installation composer r

Jung von Matt TECH 3 May 4, 2022
PHP Secure Headers

Secure Headers Add security related headers to HTTP response. The package includes Service Providers for easy Laravel integration. Version Installatio

null 431 Dec 26, 2022
A simple OOP wrapper to work with HTTP headers in PHP

Headers This package is to allow you to create HTTP Headers in PHP, in a simple and reliable way. Installation composer require http-php/headers Usage

null 5 Aug 9, 2022
CORS (Cross-Origin Resource Sharing) middleware for Hyperf application.

CORS Middleware for Hyperf Implements fruitcake/laravel-cors for Hyperf. Features Handles CORS pre-flight OPTIONS requests Adds CORS headers to your r

Gang Wu 8 Sep 19, 2022
CORS (Cross-Origin Resource Sharing) support for Laravel and Lumen

Description This package adds Cross-Origin Resource Sharing (CORS) support to your Laravel application. The package is based on Framework agnostic (PS

null 48 Feb 1, 2020