After a successful login with the Next Auth Azure B2C provider, the session is not being retrieved. #12126
Unanswered
mesilucifer
asked this question in
Help
Replies: 1 comment
-
Using next auth - 4.20.1 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone! I'm working on implementing Azure B2C as a provider with Next Auth. After a successful login, I'm unable to retrieve the session. In the context it says unauthenticated and session to be null but I guess in the redirect uri I m getting the autherization code but next auth is able to get the session . Any help would be greatly appreciated!





Using this code
Next auth config set up :
pages/api/auth/[...nextauth]
`
import { NextApiRequest, NextApiResponse } from "next";
import NextAuth, { NextAuthOptions } from "next-auth";
import { JWT } from "next-auth/jwt";
import AzureADB2CProvider from "next-auth/providers/azure-ad-b2c";
import { My_Account_Scopes } from "../../../constants/constants";
const {
SAF_AUTH_BASE_URL,
SAF_TOKEN_URL,
SAF_ISSUER_URL,
SAF_CLIENT_ID,
SAF_CLIENT_SECRET,
NEXTAUTH_SESSION_MAX_AGE_MINS,
NEXTAUTH_SECRET,
NODE_ENV,
} = process.env;
export const getAuthScopes = (): string => {
const Base_Scopes = ["openid"];
const myAccountScopes = My_Account_Scopes.map(
(scope) =>
${SAF_AUTH_BASE_URL}${scope}
,);
return
${Base_Scopes.join(" ")} ${myAccountScopes.join(" ")}
;};
export const refreshAccessToken = async (token: JWT) => {
try {
const url = SAF_TOKEN_URL;
} catch (error) {
console.log(error);
}
};
const generateHttpCookie = (
nextAuthName: string,
name: string,
httpOnly = true,
sameSite = "lax",
secure = true,
path = "",
) => {
if (NODE_ENV !== "production") return;
return {
[nextAuthName]: {
name,
options: {
httpOnly,
sameSite,
path,
secure,
},
},
};
};
export const authOptions = (res?: NextApiResponse): NextAuthOptions => ({
secret: NEXTAUTH_SECRET,
debug: true,
providers: [
AzureADB2CProvider({
id: "saf",
tenantId: "15866032-2fb5-4e00-889e-49aa4e5cfe8a",
issuer: SAF_ISSUER_URL,
clientId: SAF_CLIENT_ID,
clientSecret: SAF_CLIENT_SECRET,
checks: "pkce",
profile: async (profile) => {
try {
return {
id: profile.sub as string,
dnpId: profile.uuid as string,
email: profile.email as string,
};
} catch (error) {
console.log(console.log("SAF error", error));
}
},
token: SAF_TOKEN_URL,
authorization: {
url: "https://dev-auth.bt.com/15866032-2fb5-4e00-889e-49aa4e5cfe8a/b2c_1a_rpbt_signin/oauth2/v2.0/authorize",
params: {
scope: getAuthScopes(),
redirect_uri: "http://localhost:4200/portal/dashboard",
},
},
}),
],
session: {
strategy: "jwt",
maxAge: Number.parseInt(NEXTAUTH_SESSION_MAX_AGE_MINS as string) * 60,
},
callbacks: {
jwt: async ({ token, user, account }) => {
if (token && user && account) {
token.user = user;
token.idToken = account.id_token as string;
token.accessToken = account.access_token as string;
token.accessTokenExpiresOn = account.expires_on as number;
token.refreshToken = account.refresh_token as string;
token.refreshTokenExpiresIn =
account.refresh_token_expires_in as number;
}
},
cookies: {
pkceCodeVerifier: {
name: "next-auth.pkce.code_verifier",
options: {
httpOnly: true,
sameSite: "none",
path: "/",
secure: true,
},
},
...(NODE_ENV === "production" && {
...generateHttpCookie("sessionToken", "__Secure-next-auth.session-token"),
...generateHttpCookie("callbackUrl", "__Secure-next-auth.callback-url"),
...generateHttpCookie("csrfToken", "__Secure-next-auth.csrf-token"),
}),
},
});
export const setNoCacheHeaders = async (res: NextApiResponse) => {
res.setHeader(
"Cache-Control",
"private, no-cache, no-store, must-revalidate, max-age=0",
);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
};
const auth = async (req: NextApiRequest, res: NextApiResponse) => {
const authOptionsCall = authOptions(res);
setNoCacheHeaders(res);
return await NextAuth(req, res, authOptionsCall);
};
export default auth;
**_app.tsx** custom app provider
import "@arc-ui/components/dist/styles.css";
import "@arc-ui/fonts";
import { SessionProvider } from "next-auth/react";
import { AppProps } from "next/app";
import MainLayout from "../layouts/main-layout";
import "../styles/global.css";
function CustomApp({ Component, pageProps }: AppProps) {
return (
<Component {...pageProps} />
);
}
export default CustomApp;”
pages/dashboard/index.tsx page where session is being retrieved
`
import { BrandLogo, Button, Icon } from "@arc-ui/components/dist";
import { BtIconChevronRightMid } from "@arc-ui/icons/react/BtIconChevronRightMid";
import { BtIconCloud } from "@arc-ui/icons/react/BtIconCloud";
import { useSession } from "next-auth/react";
import { HelpAndSupport } from "../../../components/help-and-support";
import { ManageYourAccount } from "../../../components/manage-your-account";
import { SelectGroup } from "../../../components/select-group";
export default function Dashboard() {
const { data } = useSession();
const username = data
? data.user.email.toString().split("@")[0]?.replace(".", " ")
: "";
const currentHours = new Date().getHours();
const greeting =
currentHours < 12 ? "morning" : currentHours < 16 ? "afternoon" : "evening";
const SERVICES = [
{
headerText: "Broadband & wi-fi",
descriptionText:
"Easily manage your hubs, wi-fi sharing, wi-fi discs and Hybrid",
btnText: "Manage settings",
},
{
headerText: "Cloud Voice Express",
descriptionText:
"Make and take calls on your business number from anywhere, on any device.",
btnText: "Launch now",
},
{
headerText: "Domains, hosting and Microsoft 365",
descriptionText:
"Take control of your BT email, security, backup and more.",
btnText: "Manage settings",
},
{
headerText: "BT Business Apps",
descriptionText:
"All the apps you need for increased security, storage, support and more. All paid for through your regular BT Business bill.",
btnText: "Launch now",
},
{
headerText: "Switching to non-BT Mobile service",
descriptionText: "Info on switching mobile service.",
btnText: "Learn more",
},
];
return (
{"Good " + greeting + ", " +
${username}
}Welcome to your BT Business dashboard
<SelectGroup
BelowComponent={() => (
Change group name
)}
/>
Manage your services
{SERVICES.map((card, idx) => (
<div
key={"card" + idx}
className="flex flex-col min-h-64 bg-white shadow-sm hover:shadow-md border-0 border-l-2 border-l-primary border-solid">
{card.headerText}
{card.descriptionText}
))}
Get mobile apps
BT Business app
View bills, set up and manage devices, check service status, speed
and much more.
More about BT Business app
Cloud Voice Express app
Stay connected and do things faster, wherever you’re working, with
our dedicated app.
More about Cloud Voice Express app
);
}
After the successful from the azure b2c client, getting redirected to
Redirection after successful login :
http://localhost:4200/portal/dashboard?code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56CFdb9565xTHhS-HWinkAabf397gXCBduQUcRKid_Uro0le51ZKjMTmk5s8deD5T-4p5oJGsqunfLCZTT1drFdZz31gxXKhz6vMKZGvVrngO7vI4GabaE4ywYdPl8yZ22I4ee0o8tFweG-obK5nimKyED9yMnQ_-2CoRlCsc6ikoHO8TU2hvRuRaIykhxxLl9OktC_zZQqHm4wAK65Lg_FLspigLy4CKW2rhF1CeavQdPYveItEzGG2qeXvxcHgDUsGJ40jzZVweN0Uhhhm8Ln_2JI8aHoqd3M2701cjYXplCXlfhye7qQ.lHt9HHcA17BSkPU4hO7gAw
Beta Was this translation helpful? Give feedback.
All reactions