how to correctly read sessions on server-side?
Question 💬
Hi,
I have a question about the right way(s) to handle the authentication state of a user with next-auth. I'm working on platform that authenticates with keycloak and I am trying to let next-auth do the job. After several hours of implementing it I've finally found a working solution. But to be honest, I'm sure there must be a better one.
The thing I wonder most about is the way to properly check if a user is logged in or not on server-side. The function providing the current session is unstable_getServerSession() but it's officially not recommended. Our application is completely password-protected and does API calls on every page. So to get the access key the session needs to be evaluated on every page request which makes the function basically a core component of the app. I have serious doubts about that and wonder how others help themselves.
My working solution also handles the unauthenticated state on server-side in a hacky way. The thing is that I need to render the page somehow to let the client-side "take over" and trigger a redirect in case of an unauthenticated state (I use useSession() in a SessionProvider context – which works very well). I accomplished this by simply returning {props: {}} or { notFound: true }. Returning an error is actually right at this place but a 401 would've been nicer than a 404 (but unavailable in next's API). Also I thought about temporarily redirecting the user to keycloak's login page but this ended in a redirect loop between keycloak's and next's page.
The same issues I had when I tried middleware to achieve this.
So what would conceptionally be the right way to go in this case? And I don't think the case I'm describing is very uncommon as usually next projects include server-side and client-side rendering...
How to reproduce ☕️
pages/_app.tsx
function App({ Component, pageProps: { session, ...pageProps } }: AppPropsWithLayout) {
return (
<SessionProvider session={session}>
<AuthGuard>
<>
...
</>
</AuthGuard>
</SessionProvider>
);
}
AuthGuard.tsx
const AuthGuard: React.FunctionComponent<AuthGuardProps> = ({ children, loadingElement, provider }) => {
const { status } = useSession({
required: true,
onUnauthenticated() {
setTimeout(() => {
signIn();
}, 500);
}
});
if (status === 'loading') {
return loadingElement ? (
<>{loadingElement}</>
) : (
<div className="w-screen h-screen flex justify-center items-center">We forward you to auth provider...</div>
);
}
return <>{children}</>;
};
export default AuthGuard;
pages/index.tsx
function Home(props: HomeProps) {
return (
<>
{props.projects.map(p => ... )}
</>
);
}
export const getServerSideProps: any = withAuth(
async (access_key: string) => {
const myRepo = await Repo(access_key);
const projects = await myRepo.getProjects();
return {
props: {
projects: projects,
}
};
}
);
export default Home;
utils.ts
import { GetServerSidePropsContext } from 'next';
import { options } from './pages/api/auth/[...nextauth]';
export const withAuth = (
func: (props: any) => any
) => {
return async (context: GetServerSidePropsContext) => {
const session = (await unstable_getServerSession(
context.req,
context.res,
options
)) ;
if (!session) {
return {
props: {},
};
}
return await func({access_key: session.access_key, ...context});
};
};
Contributing 🙌🏽
No, I am afraid I cannot help regarding this
If storing sessions in a database, use the session token (next-auth.session-token) on the client side to authenticate the user on the server. This should persist beyond reload so will be there on visit. These cookies are HTTP Only, meaning you cannot read nor write them on the client-side. Fetch allows you to pass the credentials: 'include' param which will automatically send the session cookie over via the encrypted request header.
On server-side, you can access session token via req.headers.cookie which will give you the
next-auth.csrf-token, next-auth.callback-url, and next-auth.session-token. From there, relatively easy to check it against your database to ensure it's valid and lookup user. Hope this helps!
Weirdly, I'm having an error with this implementation while building it for my own project right now. I can send across the cookies via headers. I can't view them client side as they are HTTPOnly, but fetch is able to place the in request header via the above code.
The problem appears on the server-side. I can print the cookie string in console, split the string to get session header, but it's somehow not accessible to the program. It's acting as if it's still on the client side and cannot use javascript with the cookies. Banging my head on this one.
export default async function credentialValidation(cookie: string | undefined) {
await connectToMongoDB();
let ObjectId = (mongoose.Types.ObjectId);
console.log('reached function')
if (cookie !== undefined) {
const parsedCookie: string[] = cookie.split('next-auth.session-token=');
const tokenSession: string = parsedCookie[1];
console.log(typeof tokenSession) // prints: string
console.log(tokenSession) // prints: b840796e-09e5-4197-b922-993a5c5cafea
const session: any | null = await SessionModel.find({_id: new ObjectId(tokenSession)}); // ObjectId function acts as if no argument is passed
console.log(session);
if (session !== null) {
if (session.expires > new Date()) {
return({success: true, data: session.userId});
} else {
return({success: false, data: "Expired session"});
}
} else {
return({success: false, data: "No session found"});
}
} else {
return({success: false, data: "No cookie found"})
}
}
Got it working, some syntax cleanup required:
export default async function credentialValidation(req: NextApiRequest) {
await connectToMongoDB();
let ObjectId = (mongoose.Types.ObjectId);
const token = req.cookies['next-auth.session-token'];
if (token !== undefined) {
const session: any | null = await SessionModel.find({sessionToken: token});
if (session !== null) {
if (new Date(session[0].expires) > new Date()) {
return({success: true, data: session[0].userId});
} else {
return({success: false, data: "Expired session"});
}
} else {
return({success: false, data: "No session found"});
}
} else {
return({success: false, data: "No cookie found"})
}
}