Next Auth B2C - React and Next.js



我正在尝试使用React与Next和Next Auth库实现登录B2C。在localhost中,一切工作正常,但当我部署应用程序时,发生了一些奇怪的事情。
这个cookie:next-auth.callback-url总是设置为http://localhost:3000,如果我点击我的登录按钮,它总是重定向到这个链接:http://localhost:3000/signin?callbackUrl=http://localhost:3000&error=OAuthSignin
下面是一段代码:

//[...nextAuth.tsx]
import { NextApiRequest, NextApiResponse } from 'next';
import NextAuth, { NextAuthOptions } from 'next-auth';
import { AUTH_CLIENT_ID, AUTH_CLIENT_SECRET, AUTH_TENANT_NAME, AUTH_USER_FLOW, NEXTAUTH_URL } from '../../../config';
const tokenUrl = `https://${AUTH_TENANT_NAME}.b2clogin.com/${AUTH_TENANT_NAME}.onmicrosoft.com/${AUTH_USER_FLOW}/oauth2/v2.0/token`;
const options: NextAuthOptions = {
session: {
jwt: true,
},
pages: {
signIn: '/signin',
},
providers: [
{
id: 'azureb2c',
name: 'Azure B2C',
type: 'oauth',
version: '2.0',
scope: 'https://********.onmicrosoft.com/******/API.calls offline_access openid',
params: {
grant_type: 'authorization_code',
},
accessTokenUrl: tokenUrl,
requestTokenUrl: tokenUrl,
authorizationUrl: `https://${AUTH_TENANT_NAME}.b2clogin.com/${AUTH_TENANT_NAME}.onmicrosoft.com/${AUTH_USER_FLOW}/oauth2/v2.0/authorize?response_type=code+id_token&response_mode=form_post`,
profileUrl: 'https://graph.microsoft.com/oidc/userinfo',
profile: (profile) => ({
id: profile.oid.toString(),
fName: profile.given_name,
lName: profile.surname,
email: (profile.emails as Array<string>).length ? profile.emails[0] : null,
}),
clientId: AUTH_CLIENT_ID,
clientSecret: AUTH_CLIENT_SECRET,
idToken: true,
state: false,
},
],
callbacks: {
redirect: async (url, baseUrl) => {
return Promise.resolve(url);
},
},
};
export default (req: NextApiRequest, res: NextApiResponse<any>): void | Promise<void> => NextAuth(req, res, options);

这里是_app.tsx

//_app.tsx
function MyApp({ Component, pageProps }: AppProps) {
const [ability, setAbility] = useState({
role: supervisor,
current: buildAbilityFor(supervisor),
});
const abilities = { ability, setAbility };
const [session, loading] = useSession();
if (loading) return <Spin size="large" />;
return !session ? (
<LoginForm />
) : (
<Provider session={session}>
<AbilityContext.Provider value={abilities}>
<Component {...pageProps} />
</AbilityContext.Provider>
</Provider>
);
}

在LoginForm中,我使用了库

提供的signIn函数。
// LoginForm.tsx
export const LoginForm = () => {
return (
<>
<Header />
<div css={style.root}>
<Button onClick={() => signIn('azureb2c', { callbackUrl: NEXTAUTH_URL})}>Login</Button>
</div>
</>
);
};

我导出了所有带有NEXT_PUBLIC前缀的env变量,并在dev env中打印了这些变量。

您必须设置NEXTAUTH_URL环境变量。

见:https://next-auth.js.org/configuration/options环境变量

默认为localhost:3000,这就是为什么它在dev中工作。

您是否使用Vercel进行部署?您还可以将其设置为仅NEXTAUTH_URL,而不使用NEXT_PUBLIC_前缀。

最新更新