In this guide will show you how to configure WunderGraph to use Google as an authentication provider.
Configuration
Create a OAuth app through Google
- Go to the Credentials page (opens in a new tab).
- Click Create credentials > OAuth client ID.
- Select the Web application application type.
- Name your OAuth 2.0 client and click Create.
For more help, see Google's developer docs (opens in a new tab).
Configure WunderGraph
Open your project's wundergraph.config.ts and scroll down to the authentication object.
Inside the nested cookieBased object is a nested array object called providers.
Inside this array, add an google auth provider as shown below:
// ...
authentication: {
  cookieBased: {
    providers: [
      authProviders.google({
        id: 'google', // unique id for this provider
        clientId: new EnvironmentVariable('GOOGLE_CLIENT_ID'),
        clientSecret: new EnvironmentVariable('GOOGLE_CLIENT_SECRET'),
      }),
    ];
  }
}
// ...Production
On production you have to configure cookie keys and crsf token secret to make sure your application is secure, read more.
Usage
Once configured you can use the WunderGraph client to authenticate users in your application.
Login
The login function takes the provider id as the first argument and a redirectURL as the second argument.
Calling the login function will initiate the authentication flow and redirect the user to the identity provider, after succesful authentication the user will be redirected back to the provided redirectURL or the default redirectURL configured at the provider.
TypeScript Client
import { createClient } from '.wundergraph/generated/client';
 
const client = createClient();
 
client.login('google');Next.js Example
import { useAuth } from 'components/generated/nextjs';
 
export default function Page() {
  const { login } = useAuth();
 
  return <button onClick={() => login('github')}>Login with Keycloak</button>;
}Log out
The logout method can be used to log out the current user. By default this will only remove the authentication cookie from the browser. If you want to log out the user from the identity provider as well, you can pass the logoutOpenidConnectProvider option.
TypeScript Client
client.logout({
  logoutOpenidConnectProvider: true,
});Next.js Example
import { useAuth } from 'components/generated/nextjs';
 
export default function Page() {
  const { logout } = useAuth();
 
  return <button onClick={() => logout({ logoutOpenidConnectProvider: true })}>Logout</button>;
}Customize with Hooks
You can customize the authentication flow by using hooks. For example to create a new user in your database after a successful authentication.
export default configureWunderGraphServer(() => ({
  hooks: {
    authentication: {
      postAuthentication: async ({ user, log }) => {
        log.info(`User ${user.id} has been authenticated`);
      },
    },
  },
}));