使用Auth0指定next-auth/react的提供程序。

huangapple go评论75阅读模式
英文:

Specify provider for next-auth/react using Auth0

问题

I have a NextJS application which uses Auth0 for authentication. I have two Auth0 tenants which I want to use for two separate register and login functionalities. I understand I can create Roles in one and only work with one, but this is not an option. I have added two Auth0 providers in my [...nextauth].ts file as shown below. Basically, what I want is to have two login buttons, one which has an Auth0 provider for Auth0 tenant 1, and one which has an Auth0 provider for Auth0 tenant 2. I am using next-auth/react for signIn("auth0"), and I want to be able to specify which Auth0 provider should be used to handle this. Here is the code I have:

[...nextauth].ts:

import NextAuth, { type NextAuthOptions } from 'next-auth'
import Auth0Provider from 'next-auth/providers/auth0';

export const authOptions: NextAuthOptions = {
  // Configure one or more authentication providers
  secret: process.env.AUTH0_SECRET,
  pages: {
    signIn: '/login'
  },
  providers: [
    Auth0Provider({
      clientId: process.env.AUTH0_CLIENT_ID as string,
      clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
      idToken: true,
      issuer: process.env.AUTH0_ISSUER_BASE_URL
    }),
    Auth0Provider({
      clientId: process.env.AUTH0_TENANT_CLIENT_ID as string,
      clientSecret: process.env.AUTH0_TENANT_CLIENT_SECRET as string,
      idToken: true,
      issuer: process.env.AUTH0_TENANT_ISSUER_BASE_URL
    })
  ],
  callbacks: {
    signIn({ profile }) {
      return !!profile
    },
    redirect({ url, baseUrl }) {
      return url startsWith baseUrl ? `${baseUrl}/` : baseUrl
    },
    jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token
      }
      return token
    },
    session({ session, token }) {
      return { ...session, ...token }
    }
  }
}
export default NextAuth(authOptions)

Here is my code for my login button:

// material-ui
import { Button, Grid, Typography } from '@mui/material';

// assets
import LockIcon from '@mui/icons-material/Lock';

// func
import { useLanguage } from '@/hooks/i18n/useLanguage';
import { signIn } from 'next-auth/react';

const LoginBtn = () => {
  const { t } = useLanguage();

  return (
    <Grid
      container
      spacing={0}
      direction="column"
      alignItems="center"
      justifyContent="center"
      className="h-screen"
    >
      <Button
        className="h-20 w-72 rounded-full bg-arealizeGreenDark text-arealizeBeigeLight hover:bg-arealizeGreenLight"
        onClick={() => {
          void signIn('auth0');
        }}
      >
        <Typography>{t.general.login_btn}</Typography>
        <LockIcon className="ml-2" />
      </Button>
    </Grid>
  );
}

export default LoginBtn;

As you can see, I have two Auth0Providers implemented in the [...nextauth].ts file. With this, when I click the signin button, it always chooses the top provider. I want a way to specify which provider should be used.

Thanks!

英文:

I have a NextJS application which uses Auth0 for authentication. I have two Auth0 tenants which I want to use for two separate register and login functionalities. I understand I can create Roles in one and only work with one, but this is not an option. I have added two Auth0 providers in my [...nextauth].ts file as shown below. Basically, what I want is to have two login buttons, one which has an Auth0 provider for Auth0 tenant 1, and one which has an Auth0 provider for Auth0 tenant 2. I am using next-auth/react for signIn("auth0"), and I want to be able to specify which Auth0 provider should be used to handle this. Here is the code I have:

[...nextauth].ts:

import NextAuth, { type NextAuthOptions } from &#39;next-auth&#39;
import Auth0Provider from &#39;next-auth/providers/auth0&#39;

export const authOptions: NextAuthOptions = {
  // Configure one or more authentication providers
  secret: process.env.AUTH0_SECRET,
  pages: {
    signIn: &#39;/login&#39;
  },
  providers: [
    Auth0Provider({
      clientId: process.env.AUTH0_CLIENT_ID as string,
      clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
      idToken: true,
      issuer: process.env.AUTH0_ISSUER_BASE_URL
    }),
    Auth0Provider({
      clientId: process.env.AUTH0_TENANT_CLIENT_ID as string,
      clientSecret: process.env.AUTH0_TENANT_CLIENT_SECRET as string,
      idToken: true,
      issuer: process.env.AUTH0_TENANT_ISSUER_BASE_URL
    })
  ],
  callbacks: {
    signIn({ profile }) {
      return !!profile
    },
    redirect({ url, baseUrl }) {
      return url.startsWith(baseUrl) ? `${baseUrl}/` : baseUrl
    },
    jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token
      }
      return token
    },
    session({ session, token }) {
      return { ...session, ...token }
    }
  }
}
export default NextAuth(authOptions)

Here is my code for my login button:

// material-ui
import { Button, Grid, Typography } from &#39;@mui/material&#39;

// assets
import LockIcon from &#39;@mui/icons-material/Lock&#39;

// func
import { useLanguage } from &#39;@/hooks/i18n/useLanguage&#39;
import { signIn } from &#39;next-auth/react&#39;

const LoginBtn = () =&gt; {
  const { t } = useLanguage()

  return (
    &lt;Grid
      container
      spacing={0}
      direction=&quot;column&quot;
      alignItems=&quot;center&quot;
      justifyContent=&quot;center&quot;
      className=&quot;h-screen&quot;&gt;
      &lt;Button
        className=&quot;h-20 w-72 rounded-full bg-arealizeGreenDark text-arealizeBeigeLight hover:bg-arealizeGreenLight&quot;
        onClick={() =&gt; {
          void signIn(&#39;auth0&#39;)
        }}&gt;
        &lt;Typography&gt;{t.general.login_btn}&lt;/Typography&gt;
        &lt;LockIcon className=&quot;ml-2&quot; /&gt;
      &lt;/Button&gt;
    &lt;/Grid&gt;
  )
}

export default LoginBtn

As you can see, I have two Auth0Providers implemented in the [...nextauth].ts file. With this, when I click the signin button, it always chooses the top provider. I want a way to specify which provider should be used.

Thanks!

答案1

得分: 1

您必须为每个提供程序指定唯一的id

[
  Auth0Provider({
    id: "first", // <-- 添加此行
    clientId: process.env.AUTH0_CLIENT_ID as string,
    clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
    idToken: true,
    issuer: process.env.AUTH0_ISSUER_BASE_URL,
  }),
  Auth0Provider({
    id: "second", // <-- 添加此行
    clientId: process.env.AUTH0_TENANT_CLIENT_ID as string,
    clientSecret: process.env.AUTH0_TENANT_CLIENT_SECRET as string,
    idToken: true,
    issuer: process.env.AUTH0_TENANT_ISSUER_BASE_URL,
  }),
];

然后使用提供程序的id调用signIn()方法以进行登录:

signIn('first')
//或
signIn('second')
英文:

You have to specify an unique id for each provider:

[
  Auth0Provider({
    id:&quot;first&quot;, // &lt;-- add this line
    clientId: process.env.AUTH0_CLIENT_ID as string,
    clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
    idToken: true,
    issuer: process.env.AUTH0_ISSUER_BASE_URL,
  }),
  Auth0Provider({
    id:&quot;second&quot;, // &lt;-- add this line
    clientId: process.env.AUTH0_TENANT_CLIENT_ID as string,
    clientSecret: process.env.AUTH0_TENANT_CLIENT_SECRET as string,
    idToken: true,
    issuer: process.env.AUTH0_TENANT_ISSUER_BASE_URL,
  }),
];

Then call the signIn() method with the id of the provider you want to sign in with :

signIn(&#39;first&#39;)
//or
signIn(&#39;second&#39;)

huangapple
  • 本文由 发表于 2023年3月9日 22:36:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定