Next Auth B2C - React and Next.js

Viewed 598

I'm trying to implement login to B2C with React with Next and Next Auth library. In localhost everything works fine, but when i deploy the application, something weird happen.
This cookie: next-auth.callback-url is always set to http://localhost:3000 and if i click on my Login Button, it redirects me always to this link : http://localhost:3000/signin?callbackUrl=http://localhost:3000&error=OAuthSignin .
Here some snippet of code:

//[...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);

Here it's _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>
    );
}

And inside LoginForm, i used signIn function provided by the library

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

I exported all env vars with prefix NEXT_PUBLIC, and i printed that vars in dev env. They are all read correctly.

1 Answers
Related