Git Product home page Git Product logo

auth-sdk's Introduction

Saleor Auth SDK

Saleor Auth SDK integrates secure and customizable authentication and authorization into storefronts using Saleor.

Below 3kB bundle size (gzipped).

npm Docs Twitter Discord

Discord Badge

Usage

Next.js App Router

Next.js 13+ App Router is the recommended way to use the Saleor Auth SDK. It is the easiest to set up and provides the best user experience.

In order to use Saleor Auth SDK in React Server Components, the client needs to be created in the following way:

import { createSaleorAuthClient } from "@saleor/auth-sdk";
import { getNextServerCookiesStorage } from "@saleor/auth-sdk/next/server";

const getServerAuthClient = () => {
  const nextServerCookiesStorage = getNextServerCookiesStorage();
  return createSaleorAuthClient({
    saleorApiUrl: "…",
    refreshTokenStorage: nextServerCookiesStorage,
    accessTokenStorage: nextServerCookiesStorage,
  });
};

Logging in can be implemented via Server Actions:

<form
  className="bg-white shadow-md rounded p-8"
  action={async (formData) => {
    "use server";

    await getServerAuthClient().signIn(
      {
        email: formData.get("email").toString(),
        password: formData.get("password").toString(),
      },
      { cache: "no-store" },
    );
  }}
>
  {/* … rest of the form … */}
</form>

Then, you can use saleorAuthClient.fetchWithAuth directly for any queries and mutations.

For a full working example, see the Saleor Auth SDK example.

Next.js Pages Router with Apollo Client

Step-by-step video tutorial

Check the following step-by-step video guide on how to set this up. Saleor Auth with Next.js

When using Next.js (Pages Router) along with Apollo Client, there are two essential steps to setting up your application. First, you have to surround your application's root with two providers: <SaleorAuthProvider> and <ApolloProvider>.

<SaleorAuthProvider> comes from our React.js-auth package, located at @saleor/auth-sdk/react, and it needs to be set up with the Saleor auth client instance.

The <ApolloProvider> comes from @apollo/client and it needs the live GraphQL client instance, which is enhanced with the authenticated fetch that comes from the Saleor auth client.

Lastly, you must run the useAuthChange hook. This links the onSignedOut and onSignedIn events.

Let's look at an example:

import { AppProps } from "next/app";
import { ApolloProvider, ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
import { createSaleorAuthClient } from "@saleor/auth-sdk";
import { SaleorAuthProvider, useAuthChange } from "@saleor/auth-sdk/react";

const saleorApiUrl = "<your Saleor API URL>";

// Saleor Client
const saleorAuthClient = createSaleorAuthClient({ saleorApiUrl });

// Apollo Client
const httpLink = createHttpLink({
  uri: saleorApiUrl,
  fetch: saleorAuthClient.fetchWithAuth,
});

export const apolloClient = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

export default function App({ Component, pageProps }: AppProps) {
  useAuthChange({
    saleorApiUrl,
    onSignedOut: () => apolloClient.resetStore(),
    onSignedIn: () => {
      apolloClient.refetchQueries({ include: "all" });
    },
  });

  return (
    <SaleorAuthProvider client={saleorAuthClient}>
      <ApolloProvider client={apolloClient}>
        <Component {...pageProps} />
      </ApolloProvider>
    </SaleorAuthProvider>
  );
}

Then, in your register, login and logout forms you can use the auth methods (signIn, signOut, isAuthenticating) provided by the useSaleorAuthContext(). For example, signIn is usually triggered when submitting the login form credentials.

import React, { FormEvent } from "react";
import { useSaleorAuthContext } from "@saleor/auth-sdk/react";
import { gql, useQuery } from "@apollo/client";

const CurrentUserDocument = gql`
  query CurrentUser {
    me {
      id
      email
      firstName
      lastName
      avatar {
        url
        alt
      }
    }
  }
`;

export default function LoginPage() {
  const { signIn, signOut } = useSaleorAuthContext();

  const { data: currentUser, loading } = useQuery(CurrentUserDocument);

  const submitHandler = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const result = await signIn({
      email: "[email protected]",
      password: "admin",
    });

    if (result.data.tokenCreate.errors) {
      // handle errors
    }
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <main>
      {currentUser?.me ? (
        <>
          <div>Display user {JSON.stringify(currentUser)}</div>
          <button className="button" onClick={() => signOut()}>
            Log Out
          </button>
        </>
      ) : (
        <div>
          <form onSubmit={submitHandler}>
            {/* You must connect your inputs to state or use a form library such as react-hook-form */}
            <input type="email" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <button className="button" type="submit">
              Log In
            </button>
          </form>
        </div>
      )}
    </main>
  );
}

Next.js (Pages Router) with urql

When using Next.js (Pages Router) along with urql client, there are two essential steps to setting up your application. First, you have to surround your application's root with two providers: <SaleorAuthProvider> and <Provider>.

<SaleorAuthProvider> comes from our React.js-auth package, located at @saleor/auth-sdk/react, and it needs to be set up with the Saleor auth client.

The <Provider> comes from urql and it needs the GraphQL client instance, which is enhanced with the authenticated fetch that comes from the Saleor auth client.

Lastly, you must run the useAuthChange hook. This links the onSignedOut and onSignedIn events and is meant to refresh the GraphQL store and in-flight active GraphQL queries.

Let's look at an example:

import { AppProps } from "next/app";
import { Provider, cacheExchange, fetchExchange, ssrExchange } from "urql";
import { SaleorAuthProvider, useAuthChange } from "@saleor/auth-sdk/react";

const saleorApiUrl = "<your Saleor API URL>";

const saleorAuthClient = createSaleorAuthClient({ saleorApiUrl });

const makeUrqlClient = () =>
  createClient({
    url: saleorApiUrl,
    fetch: saleorAuthClient.fetchWithAuth,
    exchanges: [cacheExchange, fetchExchange],
  });

export default function App({ Component, pageProps }: AppProps) {
  // https://github.com/urql-graphql/urql/issues/297#issuecomment-504782794
  const [urqlClient, setUrqlClient] = useState<Client>(makeUrqlClient());

  useAuthChange({
    saleorApiUrl,
    onSignedOut: () => setUrqlClient(makeUrqlClient()),
    onSignedIn: () => setUrqlClient(makeUrqlClient()),
  });

  return (
    <SaleorAuthProvider client={saleorAuthClient}>
      <Provider value={urqlClient}>
        <Component {...pageProps} />
      </Provider>
    </SaleorAuthProvider>
  );
}

Then, in your register, login and logout forms you can use the auth methods (signIn, signOut) provided by the useSaleorAuthContext(). For example, signIn is usually triggered when submitting the login form credentials.

import React, { FormEvent } from "react";
import { useSaleorAuthContext } from "@saleor/auth-sdk/react";
import { gql, useQuery } from "urql";

const CurrentUserDocument = gql`
  query CurrentUser {
    me {
      id
      email
      firstName
      lastName
      avatar {
        url
        alt
      }
    }
  }
`;

export default function LoginPage() {
  const { signIn, signOut } = useSaleorAuthContext();

  const [{ data: currentUser, fetching: loading }] = useQuery({
    query: CurrentUserDocument,
    pause: isAuthenticating,
  });

  const submitHandler = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const result = await signIn({
      email: "[email protected]",
      password: "admin",
    });

    if (result.data.tokenCreate.errors) {
      // handle errors
    }
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <main>
      {currentUser?.me ? (
        <>
          <div>Display user {JSON.stringify(currentUser)}</div>
          <button className="button" onClick={() => signOut()}>
            Log Out
          </button>
        </>
      ) : (
        <div>
          <form onSubmit={submitHandler}>
            {/* You must connect your inputs to state or use a form library such as react-hook-form */}
            <input type="email" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <button className="button" type="submit">
              Log In
            </button>
          </form>
        </div>
      )}
    </main>
  );
}

Next.js (Pages Router) with OpenID Connect

Setup _app.tsx as described above. In your login component trigger the external auth flow using the following code:

import { useSaleorAuthContext, useSaleorExternalAuth } from "@saleor/auth-sdk/react";
import { ExternalProvider } from "@saleor/auth-sdk";
import Link from "next/link";
import { gql, useQuery } from "@apollo/client";

export default function Home() {
  const {
    loading: isLoadingCurrentUser,
    error,
    data,
  } = useQuery(gql`
    query CurrentUser {
      me {
        id
        email
        firstName
        lastName
      }
    }
  `);
  const { authURL, loading: isLoadingExternalAuth } = useSaleorExternalAuth({
    saleorApiUrl,
    provider: ExternalProvider.OpenIDConnect,
    redirectURL: "<your Next.js app>/api/auth/callback",
  });

  const { signOut } = useSaleorAuthContext();

  if (isLoadingExternalAuth || isLoadingCurrentUser) {
    return <div>Loading...</div>;
  }

  if (data?.me) {
    return (
      <div>
        {JSON.stringify(data)}
        <button onClick={() => signOut()}>Logout</button>
      </div>
    );
  }
  if (authURL) {
    return (
      <div>
        <Link href={authURL}>Login</Link>
      </div>
    );
  }
  return <div>Something went wrong</div>;
}

You also need to define the auth callback. In pages/api/auth create the callback.ts with the following content:

import { ExternalProvider, SaleorExternalAuth } from "@saleor/auth-sdk";
import { createSaleorExternalAuthHandler } from "@saleor/auth-sdk/next";

const externalAuth = new SaleorExternalAuth("<your Saleor instance URL>", ExternalProvider.OpenIDConnect);

export default createSaleorExternalAuthHandler(externalAuth);

FAQ

How do I reset password?

The SaleorAuthClient class provides you with a reset password method. If the reset password mutation is successful, it will log you in automatically, just like after a regular sign-in. The onSignIn method of useAuthChange hook will also be triggered.

const { resetPassword } = useSaleorAuthContext();

const response = await resetPassword({
  email: "[email protected]",
  password: "newPassword",
  token: "apiToken",
});

auth-sdk's People

Contributors

jyrno42 avatar pitkes22 avatar timuric avatar typeofweb avatar zaiste avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth-sdk's Issues

How to use OIDC with App Route

There seems no documentation of using Open Id in app route. It works in page route but with SSR I cannot make it work. I think cookies are not properly set in callback in createSaleorExternalAuthHandler .

Warn about JWT token iss parameter mismatch

Currently SaleorAuthClient checks the value of the iss parameter in the JWT token and compares it with the URL of the request. If they do not match it will not add Authorization headers to the request.

I encounter this error and spent DAYS debugging authentification not working. It would save me a lot of time if this was documented or if there was a warning in the console that the authorization header is not added due to JWT Token issuer mismatch.

Also unrelated directly to auth-sdk but may save someone time. When I understood that the token issuer must match the request's URL, I decoded the token I got from the saleor. Turned out it pointed to http: insted of https:, and to resolve the issue I once again have to read the source code of the saleor to find that it uses a ENABLE_SSL enviroment variable that is conveniently NOT documented anywhere and it decides based of it if URL should start with http or https.

Token expiration causes Maximum call stack size exceeded error

There is a critical problem with refreshing the token. When you allow the token to expire, any attempt to make a request will cause the token to refresh. My assumption is that the request to the refreshToken also triggers this refresh, creating an infinite loop.

Steps to reproduce (I will use the official demo storefront):

  1. Go to the Saleor storefront (e.g. product page)
  2. Wait for the token to expire (5 minutes)
  3. Do any action that will make a Graphql request (e.g. click Add to cart)
  4. There is a Maximum call stack size exceeded error in the console and everything is broken.

If you run Performance Profiler while an error occurs, you can clearly see that the problem is in the handling of the token refresh.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.