Impersonate users (Credentials/Google) #2947
Replies: 6 comments 20 replies
-
I think you are talking about Role-Based Access Control. There are many ways going about that, the easiest is if you add a |
Beta Was this translation helpful? Give feedback.
-
any idea on how to do it with JWT token session which is the default session store? |
Beta Was this translation helpful? Give feedback.
-
I implemented it with the Credentials provider. CredentialsProvider({
name: "impersonate",
id: "impersonate",
credentials: {
adminEmail: {
label: "Admin Email",
type: "text",
placeholder: "[email protected]",
},
userEmail: {
label: "User Email",
type: "text",
placeholder: "[email protected]",
},
},
async authorize(credentials) {
if (!credentials?.adminEmail || !credentials?.userEmail) {
throw new Error("User email or Admin email is missing");
}
const admin = await prisma.user.findUnique({
where: {
email: credentials.adminEmail.toLocaleLowerCase(),
},
});
const user = await prisma.user.findUnique({
where: {
email: credentials.userEmail.toLocaleLowerCase(),
},
});
if (!admin || admin.role !== "ADMIN") {
throw new Error("Access denied");
}
// if user was not found
if (!user) {
throw new Error("No user found");
}
return user;
},
}), call the
|
Beta Was this translation helpful? Give feedback.
-
With Lucia, you can easily do it like this: const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes,
); Is there an equivalent API for Auth.js? |
Beta Was this translation helpful? Give feedback.
-
Hello, is ther any update to implementing impersonation in next auth? Because the OAuth 2.0 standard supports token exhange https://cloudentity.com/developers/basics/oauth-extensions/token-exchange/#how-token-exchange-works wich keycloak f.e. also implements as its a safe way to do impersonation, this would be great if it cloud be added to next-auth as a custom implementation over a credentials provider is a bit tricky as the User object wich gets returned in the authorize method is very limited and has no support to save the exchanged token |
Beta Was this translation helpful? Give feedback.
-
for v5.beta.25 (not sure since when it works) using jwt session (documentation is still terrible... but it works and makes sense, aka might be stable): Client part to send the info to the backen (to the jwt callback) 'use client'
import { SessionProvider, useSession } from "next-auth/react"
import { useRouter } from "next/navigation"
function WrappedButtonImpersonate({ userId }: { userId: string | null }) {
const session = useSession();
const router = useRouter();
async function onClick() {
await session.update({ impersonate: userId });
router.refresh();
}
return <button onClick={onClick}>{userId === null && 'Stop '}Impersonate</button>
}
export function ButtonImpersonate({ userId }: { userId: string }) {
return (
<SessionProvider>
<WrappedButtonImpersonate userId={userId} />
</SessionProvider>
)
}
export function ButtonStopImpersonation() {
return (
<SessionProvider>
<WrappedButtonImpersonate userId={null} />
</SessionProvider>
)
} jwt callback to check, handle and update session (working excerpt) jwt({ token, user, trigger, session }) {
switch (trigger) {
case 'update':
// validate what you need (probably token.isAdmin or something)
if (session.impersonate) {
// impersonate (if you need to load things, make this callback async, it works)
token.userId = session.impersonate;
} else {
// stop impersonating;
token.userId = token.realUserId;
}
break;
case 'signIn':
token.userId = user.id;
token.realUserId ||= user.id; // Keep track of the original user
break
}
return token
},
session({ session, token }) {
// Enhance session with user details
session.user.id = token.userId;
} |
Beta Was this translation helpful? Give feedback.
-
Hi all,
I'm thinking about implementation an impersonation feature where an admin can login as other users. In my app I'm allowing to login with Google and Credentials(username and password).
How to go about implementing such a feature with next-auth? Like for example it wouldn't be possible for an admin to login with someone's else Google account but perhaps there's a way to mutate the session with next-auth? I haven't been able to find it searching the docs.
Anyone with experience implementing this type of functionality?
Beta Was this translation helpful? Give feedback.
All reactions