【发布时间】:2021-10-10 05:32:44
【问题描述】:
我正在尝试使用带有 Next 和 Next Auth 库的 React 实现登录到 B2C。
在 localhost 中一切正常,但是当我部署应用程序时,发生了一些奇怪的事情。
这个饼干:
next-auth.callback-url 总是设置为 http://localhost:3000,如果我点击我的登录按钮,它总是将我重定向到这个链接:http://localhost:3000/signin?callbackUrl=http://localhost:3000&error=OAuthSignin 。
这里有一些sn-p代码:
//[...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 内部,我使用了库提供的登录功能
// LoginForm.tsx
export const LoginForm = () => {
return (
<>
<Header />
<div css={style.root}>
<Button onClick={() => signIn('azureb2c', { callbackUrl: NEXTAUTH_URL})}>Login</Button>
</div>
</>
);
};
我导出了所有带有前缀 NEXT_PUBLIC 的环境变量,并在开发环境中打印了这些变量。它们都被正确读取了。
【问题讨论】:
-
遇到同样的问题