Skip to content

Instantly share code, notes, and snippets.

@mattfysh
Last active June 7, 2023 14:45
Show Gist options
  • Save mattfysh/14d37f808583e444be6f40bc939ebe38 to your computer and use it in GitHub Desktop.
Save mattfysh/14d37f808583e444be6f40bc939ebe38 to your computer and use it in GitHub Desktop.
urql + auth-exchange + aws-amplify
import { makeOperation } from '@urql/svelte'
import { authExchange } from '@urql/exchange-auth'
import { Auth } from 'aws-amplify'
import produce from 'immer'
import { set } from 'lodash'
const amplifyAuthExchange = authExchange({
addAuthToOperation: ({ authState, operation }) => {
if (!authState?.token) {
return operation
}
const newContext = produce(operation.context, context => {
set(context, 'fetchOptions.headers.Authorization', authState.token)
})
return makeOperation(operation.kind, operation, newContext)
},
willAuthError: ({ authState }) => {
try {
const [,payload] = authState.token.split('.')
const { exp } = JSON.parse(Buffer.from(payload, 'base64'))
return exp * 1000 < Date.now()
} catch(e) {
return true
}
},
didAuthError: ({ error }) =>
error.graphQLErrors.some(e => e.message === 'Unauthorized'),
getAuth: async () => {
const session = await Auth.currentSession()
if (session) {
// defines the authState elsewhere
return {
token: session.getAccessToken().getJwtToken(),
}
}
Auth.signOut()
return null
},
})
@mattfysh
Copy link
Author

mattfysh commented Mar 21, 2022

Hi @souravjamwal77 - which identity provider are you authenticating against? This example assumes you are using Amplify together with Cognito to exchange username/pass credentials for a token prior to instantiating the urql client

preferably using the Amplify JS library: https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/

@souravjamwal77
Copy link

souravjamwal77 commented Mar 21, 2022

Hi @mattfysh I'm using django backend with graphene(GraphQL client for django) and on frontend side I'm using URQL with SvelteKit.

@souravjamwal77
Copy link

Actually, I just want to see an example in which username and password are sent once and then auth token is stored inside the localStorage. From there I can build my program.

@mattfysh
Copy link
Author

It sounds like you're not using Amplify so the gist above is not going to work for your use case.

Does this repo contain any examples you can use? https://github.com/sveltejs/realworld

@ajenkins
Copy link

ajenkins commented Apr 1, 2022

Thanks, this was helpful. I had to make some tweaks to the getAuth function to get it to work for me though. Just calling await Auth.currentSession() would result in an error when the app loaded because the user isn't signed in yet. The specific error message I was getting was Possible Unhandled Promise Rejection (id: 0): "No current user". And for some reason I would continue to get this error even after I signed in. However, the error would disappear if I reloaded the app because I guess now I had an active session saved in storage.

I had to make these changes to the getAuth function to get it to work:

getAuth: async ({ authState }) => {
  if (!authState) {
    let session;
    try {
      session = await Auth.currentSession();
    } catch {
      // The promise will be rejected if the user isn't signed in yet
      return null;
    }
    if (session) {
      return {
        token: session.getIdToken().getJwtToken(),
      };
    }
    return null;
  }
  Auth.signOut();
  return null;
};

I don't have a question, but just wanted to post this in case anyone else is trying to use urql with Amplify and is running into the same issue I was having. I also had to add import { Buffer } from "buffer"; for willAuthError.

@mattfysh
Copy link
Author

mattfysh commented Apr 2, 2022

Nice spotting @ajenkins - I must have missed this due to my setup where I create the client in a component that isn't mounted until after login, glad you found a solution for this!

@aseer-ws
Copy link

aseer-ws commented Jun 7, 2023

In the latest version of @urql/exchange-auth, it doesn't getAuth function and I am not able to use Promise inside addAuthToOperation
Do you guys an alternate approach for the latest version @mattfysh @souravjamwal77 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment