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

how to use cookie from request headers ? #87

Closed
cfab opened this issue Jun 7, 2022 · 8 comments
Closed

how to use cookie from request headers ? #87

cfab opened this issue Jun 7, 2022 · 8 comments

Comments

@cfab
Copy link

cfab commented Jun 7, 2022

Hello,
I'm trying to use wordpress with wp-graphql and I need to post some mutations from my nuxt front-end.
I'm using wp-grapql-cors to login and there is indeed a Set-Cookie in the response headers.
Using Postman, I can see the cookie and with authorization tab set to "inherit from parent", if I post a mutation to create a page for example, it works.
But within nuxt, I dont know how to configure "nuxt-grapql-client" in order to have something equivalent !
Any help or example, is welcome !
Thank you.
PS: Here is a working generated example code from postman using axios:

var axios = require('axios');
var data = JSON.stringify({
  query: `mutation createPost {
  createPost(input: {
    title: "A nice title"
    content: "some content",
    status: PUBLISH
    }) {
    clientMutationId
  }
}`,
  variables: {}
});

var config = {
  method: 'post',
  url: 'https://galpon.test/graphql',
  headers: { 
    'Content-Type': 'application/json', 
    'Cookie': 'wordpress_logged_in_0a80706747350ab2bd151dfb3be09ba4=test2%7C1654774457%7CaUXw73nZkYwr1uxZkZwjcRkYPYPkONqJgDqd2jRTP8c%7C04441e5096ef211a79ba62f83e5cf34e1c9cfeffeb9c1933877f6231dc71d0de'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});
@Diizzayy
Copy link
Owner

Diizzayy commented Jun 7, 2022

I dont know how to configure "nuxt-grapql-client" in order to have something equivalent

@cfab I'll walk you through a basic implementation based on the working code example that you provided

  • Your mutation can be added as follows:

nuxt-app/queries/post.gql

mutation createPost {
  createPost(input: {
    title: "A nice title"
    content: "some content",
    status: PUBLISH
    }) {
    clientMutationId
  }
}
  • Configuring authorization

This module doesn't currently have first class support for Cookie auth but this can be easily achieved as seen below:

nuxt.config.ts

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],

  runtimeConfig: {
    public: {
      'graphql-client': {
        clients: {
          default: {
            host: 'https://galpon.test/graphql',
            token: {
              type: null,
              name: 'Cookie',
              value: 'wordpress_logged_in_0a80706747350ab2bd151dfb3be09ba4=test2%7C1654774457%7CaUXw73nZkYwr1uxZkZwjcRkYPYPkONqJgDqd2jRTP8c%7C04441e5096ef211a79ba62f83e5cf34e1c9cfeffeb9c1933877f6231dc71d0de',
            },
            // retainToken: true,
          },
        },
      },
    },
  },
});

Also, this module relies on GraphQL introspection to improve the developer experience by generating the necessary types for your queries, I'm not certain but I think WPGraphQL disables introspection by default, You however can read how to enable it here.

@cfab Feel free to ask any additional questions that you may have

@cfab
Copy link
Author

cfab commented Jun 7, 2022

Thank you. This is great, but I cannot hard code the token.value as it will be different for each user when they login...

@Diizzayy
Copy link
Owner

Diizzayy commented Jun 7, 2022

@cfab within your code you can leverage the provided useGqlToken composable to apply a user's token after they've logged in successfully.

However though another issue that you'll run into (even outside of this module) is that modern browsers don't allow the cookie header to be manually added to requests, (though this is possible in node server environments as well as in postman but will fail in browsers due to security measures).

@cfab If you can create a repo for your project, I'd be willing to help you setup everything. You can also reach out to me on Discord - Diizzayy#1964

I'd suggest that you look into using the WPGraphQL JWT Plugin for WPGraphQL Authentication.

Once you've successfully installed the plugin. You'll be able to setup your app as seen below

  • Nuxt Config

As you'll now be using JWT tokens via WPGraphQL JWT Plugin for authentication, your configuration would need to be updated as seen below. This will allow the token header to be passed as: Authorization: Bearer <user_token>

nuxt.config.ts

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],

  runtimeConfig: {
    public: {
      'graphql-client': {
        clients: {
          default: {
            host: 'https://galpon.test/graphql'
        },
      },
    },
  },
});
  • User Login

Nuxt-app/queries/user.gql

mutation Login($input: LoginInput!) {
  login(input: $input) {
    authToken
    user {
      username
    }
  }
}

Then within your login code

<script lang="ts" setup>
async function handleLogin () {
  // call login query
  const { login } = await GqlLogin({
    input: {
      username: 'your username',
      password: 'your password'
    }
  })

  // if login was successful, apply user token
  if (login?.authToken) {
    useGqlToken(login.authToken)
  }
}
</script>

@douglasgusson
Copy link

Hello, I would like to know if there is a possibility to include other parameters in the headers through the client configuration, for cases where custom headers are needed to read the API schema.

Thanks in advance!

@Diizzayy
Copy link
Owner

Diizzayy commented Jun 7, 2022

for cases where custom headers are needed to read the API schema

@douglasgusson I haven't yet provided a way for this to be added via nuxt config (though a PR enabling this is on the horizon), and from my understanding this is where it's required for your use-case ( reading the API schema ).

might I ask what the GraphQL service that you're using is and what the necessary headers are?

However though custom headers can be added to requests via the useGqlHeaders composable.

nuxt-app/app.vue

<script lang="ts" setup>
// 'X-Custom-Header' will be applied to all subsequent requests
useGqlHeaders({
  'X-Custom-Header': 'Custom Header Value'
})

// The headers set above will be applied both on SSR, as well as when called on client
const { data } = await useAsyncData('starlink', () => GqlLaunches())
</script>

@douglasgusson
Copy link

Hello, @Diizzayy, thanks for the answer.

My application is multitenancy. So, when I make a request, is needed to put an special header to specify what tenant I want to download the API schema. So, I would be greatfull if you allow to put it on requests. If you preffer, I can make a PR.

@Diizzayy
Copy link
Owner

Diizzayy commented Jun 7, 2022

My application is multitenancy

@douglasgusson Okay I understand, Thank you for the explanation.

If you preffer, I can make a PR

That would be great.

@cfab
Copy link
Author

cfab commented Jun 9, 2022

@cfab If you can create a repo for your project, I'd be willing to help you setup everything. You can also reach out to me on Discord - Diizzayy#1964

@Diizzayy Many thanks for your thorough answer, this is great support ! I'll let you know if I don't manage...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants