I am trying to ingest a token set from an internal application login into our nextjs-auth0
flow. Does anyone have any experience on ways to achieve this? The only way I have found to do this is by modifying the package.json
of the nextjs-auth0
package to remove exports. This feels super hacky and not safe for production I would love a clean of way of being able to handle this.
Here is a very simple example of this.
import login from "@/lib/dataSource/api/auth/login";
import { StatelessSession } from "@auth0/nextjs-auth0/dist/auth0-session";
import NodeCookies from "@auth0/nextjs-auth0/dist/auth0-session/utils/cookies";
import { getConfig } from "@auth0/nextjs-auth0/dist/config";
import { Session, SessionCache } from "@auth0/nextjs-auth0/dist/session";
import type { NextApiRequest, NextApiResponse } from "next/types";
import { TokenSet } from "openid-client";
/**
* Registration Login Handler
* @param { NextApiRequest } req - The request object
* @param { NextApiResponse } res - The response object
*/
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
/**
* @constant {TokenSet} tokenSet - The token set from the login request
* @default undefined
*/
let tokenSet: TokenSet | undefined;
/**
* Get the base config from the Auth0 SDK
*/
const { baseConfig } = getConfig()
/**
* Create a new Session Cache from the base config
* @constant {SessionCache} sessionCache - The session cache for the current user
*/
const sessionCache = new SessionCache(baseConfig, new StatelessSession(baseConfig, NodeCookies))
try {
/**
* Login the user with the api
* @constant loginRequest - The response from the api login
*/
const loginRequest = await login('email', 'password')
/**
* Setup Token Set
* @constant {TokenSet} tokenSet - The token set from the login request
*/
tokenSet = new TokenSet({
access_token: loginRequest.accessToken,
id_token: loginRequest.idToken,
scope: loginRequest.scope,
expires_in: loginRequest.expiresIn,
token_type: loginRequest.tokenType,
})
} catch (error) {
if (error instanceof Error) {
res.status(401).end(error.message)
}
res.status(500).end('Something went wrong')
}
if (!tokenSet) {
res.status(401).end('Unauthorized')
res.end()
return
}
/**
* Create a Session from the Token Set received from the login request
* @constant {Session} session - The session for the current user
*/
const session: Session = sessionCache.fromTokenSet(tokenSet)
/**
* Set the session in the cache
*/
await sessionCache.set(req, res, session)
/**
* Save the session in the cache
*/
await sessionCache.save(req, res)
/**
* Redirect to the needed path
*/
res.writeHead(302 , {
'Location' : '/'
});
res.end()
}
If anyone has any feedback on this it would be amazingly helpful!