I encountered the "redirect_uri_mismatch" error when using next-auth.js to sign in through Azure AD B2C.
The error description is as follows: "The redirect URI ‘http://localhost:3000/api/auth/callback/azure-ad-b2c’ provided in the request is not registered for the client ID ‘c716xxx8406’."
I have configured the project as follows
next-auth route
const handler = NextAuth({
AzureADB2CProvider({
tenantId: process.env.AZURE_AD_B2C_TENANT_NAME,
clientId: process.env.AZURE_AD_B2C_CLIENT_ID!,
clientSecret: process.env.AZURE_AD_B2C_CLIENT_SECRET!,
primaryUserFlow: process.env.AZURE_AD_B2C_PRIMARY_USER_FLOW,
authorization: { params: { scope: "offline_access openid" } },
})
],
pages: {
signIn: '/'
}
})
export { handler as GET, handler as POST }
signin button components
export default function Home() {
const { data: session } = useSession()
return (
<main className={styles.main}>
<p>
Signed in as {session?.user?.email ?? ''}
</p>
<button onClick={() => signIn('azure-ad-b2c')}>sign az</button>
<button onClick={() => signOut()}>sign out</button>
</main>
)
}
Azure App Registration and next.js project directory
Should I configure anything else?
next.js version: 13.4.1
next-auth.js version: 4.22.1
2
Answers
I just encountered this problem.
Web Redirect URIs for your App Registration in Azure should have both the NextAuth callback URL (
http://localhost:3000/api/auth/callback/azure-ad-b2c
) as well as theCallback URL
from the identity provider you’re using with your B2C User Flow. You can find this URL in the "configure" panel on the Identity Providers page in your Azure AD B2C tenant. It should look something like:On a related note I see you’re using a custom
signIn
page. Using a customsignIn
page with NextAuth introduces a problem where redirects aren’t always handled correctly depending on how you invoke thesignIn
function (i.e.signIn("azure-ad-b2c")
). See my comment in this this GitHub issue for more details. At the time of writing, this edge-case isn’t mentioned anywhere in the NextAuth documentation.I was finally able to get the AzureADB2C NextAuth provider working once I added both Redirect URIs to my App Registration, and added some additional code to my project to handle post-authentication OAuth2 redirects (which wasn’t working because I was using a custom
signIn
page by settingAuthOptions.pages.signIn
).Hope this helps someone, good luck!
I was getting same error but was able to get around it by matching up ‘id’ value and the endpoint in Redirect URL.